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
//! Command-line argument parsing for sqry
pub mod headings;
mod sort;
use crate::output;
use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};
pub use sort::SortField;
use sqry_lsp::LspOptions;
use std::path::PathBuf;
/// sqry - Semantic Query for Code
///
/// Search code by what it means, not just what it says.
/// Uses AST analysis to find functions, classes, and symbols with precision.
#[derive(Parser, Debug)]
#[command(
name = "sqry",
version,
about = "Semantic code search tool",
long_about = "sqry is a semantic code search tool that understands code structure through AST analysis.\n\
Find functions, classes, and symbols with precision using AST-aware queries.\n\n\
Examples:\n \
sqry main # Search for 'main' in current directory\n \
sqry test src/ # Search for 'test' in src/\n \
sqry --kind function . # Find all functions\n \
sqry --json main # Output as JSON\n \
sqry --csv --headers main # Output as CSV with headers\n \
sqry --preview main # Show code context around matches",
group = ArgGroup::new("output_format").args(["json", "csv", "tsv"]),
verbatim_doc_comment
)]
// CLI flags are intentionally modeled as independent booleans for clarity.
#[allow(clippy::struct_excessive_bools)]
pub struct Cli {
/// Subcommand (optional - defaults to search if pattern provided)
#[command(subcommand)]
pub command: Option<Box<Command>>,
/// Search pattern (shorthand for 'search' command)
///
/// Supports regex patterns by default. Use --exact for literal matching.
#[arg(required = false)]
pub pattern: Option<String>,
/// Search path (defaults to current directory)
#[arg(required = false)]
pub path: Option<String>,
/// Output format as JSON
#[arg(long, short = 'j', global = true, group = "output_format", help_heading = headings::COMMON_OPTIONS, display_order = 10)]
pub json: bool,
/// Output format as CSV (comma-separated values)
///
/// RFC 4180 compliant CSV output. Use with --headers to include column names.
/// By default, formula-triggering characters are prefixed with single quote
/// for Excel/LibreOffice safety. Use --raw-csv to disable this protection.
#[arg(long, global = true, group = "output_format", help_heading = headings::COMMON_OPTIONS, display_order = 12)]
pub csv: bool,
/// Output format as TSV (tab-separated values)
///
/// Tab-delimited output for easy Unix pipeline processing.
/// Newlines and tabs in field values are replaced with spaces.
#[arg(long, global = true, group = "output_format", help_heading = headings::COMMON_OPTIONS, display_order = 13)]
pub tsv: bool,
/// Include header row in CSV/TSV output
///
/// Requires --csv or --tsv to be specified.
#[arg(long, global = true, help_heading = headings::OUTPUT_CONTROL, display_order = 11)]
pub headers: bool,
/// Columns to include in CSV/TSV output (comma-separated)
///
/// Available columns: `name`, `qualified_name`, `kind`, `file`, `line`, `column`,
/// `end_line`, `end_column`, `language`, `preview`
///
/// Example: --columns name,file,line
///
/// Requires --csv or --tsv to be specified.
#[arg(long, global = true, value_name = "COLUMNS", help_heading = headings::OUTPUT_CONTROL, display_order = 12)]
pub columns: Option<String>,
/// Output raw CSV without formula injection protection
///
/// By default, values starting with =, +, -, @, tab, or carriage return
/// are prefixed with single quote to prevent Excel/LibreOffice formula
/// injection attacks. Use this flag to disable protection for programmatic
/// processing where raw values are needed.
///
/// Requires --csv or --tsv to be specified.
#[arg(long, global = true, help_heading = headings::OUTPUT_CONTROL, display_order = 13)]
pub raw_csv: bool,
/// Show code context around matches (number of lines before/after)
#[arg(
long, short = 'p', global = true, value_name = "LINES",
default_missing_value = "3", num_args = 0..=1,
help_heading = headings::OUTPUT_CONTROL, display_order = 14,
long_help = "Show code context around matches (number of lines before/after)\n\n\
Displays source code context around each match. Use -p or --preview\n\
for default 3 lines, or specify a number like --preview 5.\n\
Use --preview 0 to show only the matched line without context.\n\n\
Examples:\n \
sqry --preview main # 3 lines context (default)\n \
sqry -p main # Same as above\n \
sqry --preview 5 main # 5 lines context\n \
sqry --preview 0 main # No context, just matched line"
)]
pub preview: Option<usize>,
/// Disable colored output
#[arg(long, global = true, help_heading = headings::COMMON_OPTIONS, display_order = 14)]
pub no_color: bool,
/// Select output color theme (default, dark, light, none)
#[arg(
long,
value_enum,
default_value = "default",
global = true,
help_heading = headings::COMMON_OPTIONS,
display_order = 15
)]
pub theme: crate::output::ThemeName,
/// Sort results (opt-in)
#[arg(
long,
value_enum,
global = true,
help_heading = headings::OUTPUT_CONTROL,
display_order = 16
)]
pub sort: Option<SortField>,
// ===== Pager Flags (P2-29) =====
/// Enable pager for output (auto-detected by default)
///
/// Forces output to be piped through a pager (like `less`).
/// In auto mode (default), paging is enabled when:
/// - Output exceeds terminal height
/// - stdout is connected to an interactive terminal
#[arg(
long,
global = true,
conflicts_with = "no_pager",
help_heading = headings::OUTPUT_CONTROL,
display_order = 17
)]
pub pager: bool,
/// Disable pager (write directly to stdout)
///
/// Disables auto-paging, writing all output directly to stdout.
/// Useful for scripting or piping to other commands.
#[arg(
long,
global = true,
conflicts_with = "pager",
help_heading = headings::OUTPUT_CONTROL,
display_order = 18
)]
pub no_pager: bool,
/// Custom pager command (overrides `$SQRY_PAGER` and `$PAGER`)
///
/// Specify a custom pager command. Supports quoted arguments.
/// Examples:
/// --pager-cmd "less -R"
/// --pager-cmd "bat --style=plain"
/// --pager-cmd "more"
#[arg(
long,
value_name = "COMMAND",
global = true,
help_heading = headings::OUTPUT_CONTROL,
display_order = 19
)]
pub pager_cmd: Option<String>,
/// Filter by symbol type (function, class, struct, etc.)
///
/// Applies to search mode (top-level shorthand and `sqry search`).
/// For structured queries, use `sqry query "kind:function AND ..."` instead.
#[arg(long, short = 'k', value_enum, help_heading = headings::MATCH_BEHAVIOUR, display_order = 20)]
pub kind: Option<SymbolKind>,
/// Filter by programming language
///
/// Applies to search mode (top-level shorthand and `sqry search`).
/// For structured queries, use `sqry query "lang:rust AND ..."` instead.
#[arg(long, short = 'l', help_heading = headings::MATCH_BEHAVIOUR, display_order = 21)]
pub lang: Option<String>,
/// Case-insensitive search
#[arg(long, short = 'i', help_heading = headings::MATCH_BEHAVIOUR, display_order = 11)]
pub ignore_case: bool,
/// Exact match (disable regex)
///
/// Applies to search mode (top-level shorthand and `sqry search`).
#[arg(long, short = 'x', help_heading = headings::MATCH_BEHAVIOUR, display_order = 10)]
pub exact: bool,
/// Show count only (number of matches)
#[arg(long, short = 'c', help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
pub count: bool,
/// Maximum directory depth to search
#[arg(long, default_value = "32", help_heading = headings::FILE_FILTERING, display_order = 20)]
pub max_depth: usize,
/// Include hidden files and directories
#[arg(long, help_heading = headings::FILE_FILTERING, display_order = 10)]
pub hidden: bool,
/// Follow symlinks
#[arg(long, help_heading = headings::FILE_FILTERING, display_order = 11)]
pub follow: bool,
/// Enable fuzzy search (requires index)
///
/// Applies to search mode (top-level shorthand and `sqry search`).
#[arg(long, help_heading = headings::SEARCH_MODES_FUZZY, display_order = 20)]
pub fuzzy: bool,
/// Fuzzy matching algorithm (jaro-winkler or levenshtein)
#[arg(long, default_value = "jaro-winkler", value_name = "ALGORITHM", help_heading = headings::SEARCH_MODES_FUZZY, display_order = 30)]
pub fuzzy_algorithm: String,
/// Minimum similarity score for fuzzy matches (0.0-1.0)
#[arg(long, default_value = "0.6", value_name = "SCORE", help_heading = headings::SEARCH_MODES_FUZZY, display_order = 31)]
pub fuzzy_threshold: f64,
/// Maximum number of fuzzy candidates to consider
#[arg(long, default_value = "1000", value_name = "COUNT", help_heading = headings::SEARCH_MODES_FUZZY, display_order = 40)]
pub fuzzy_max_candidates: usize,
/// Enable JSON streaming mode for fuzzy search
///
/// Emits results as JSON-lines (newline-delimited JSON).
/// Each line is a `StreamEvent` with either a partial result or final summary.
/// Requires --fuzzy (fuzzy search) and is inherently JSON output.
#[arg(long, requires = "fuzzy", help_heading = headings::SEARCH_MODES_FUZZY, display_order = 51)]
pub json_stream: bool,
/// Allow fuzzy matching for query field names (opt-in).
/// Applies typo correction to field names (e.g., "knd" → "kind").
/// Ambiguous corrections are rejected with an error.
#[arg(long, global = true, help_heading = headings::SEARCH_MODES_FUZZY, display_order = 52)]
pub fuzzy_fields: bool,
/// Maximum edit distance for fuzzy field correction
#[arg(
long,
default_value_t = 2,
global = true,
help_heading = headings::SEARCH_MODES_FUZZY,
display_order = 53
)]
pub fuzzy_field_distance: usize,
/// Maximum number of results to return
///
/// Limits the output to a manageable size for downstream consumers.
/// Defaults: search=100, query=1000, fuzzy=50
#[arg(long, global = true, help_heading = headings::OUTPUT_CONTROL, display_order = 20)]
pub limit: Option<usize>,
/// List enabled languages and exit
#[arg(long, global = true, help_heading = headings::COMMON_OPTIONS, display_order = 30)]
pub list_languages: bool,
/// Print cache telemetry to stderr after the command completes
#[arg(long, global = true, help_heading = headings::COMMON_OPTIONS, display_order = 40)]
pub debug_cache: bool,
/// Operate against a logical workspace defined by a `.sqry-workspace` or
/// `.code-workspace` file (STEP_8).
///
/// When set, every subcommand resolves its target through the
/// `LogicalWorkspace` referenced by `<PATH>`. Path-scoped subcommands
/// (`sqry index <PATH>`, `sqry query <PATH> …`) still take their explicit
/// positional argument first; this flag is the fallback when no positional
/// is provided.
///
/// The `SQRY_WORKSPACE_FILE` environment variable resolves identically;
/// when both are present, the explicit `--workspace` flag wins.
///
/// Conflicts with the `sqry workspace …` subcommand (which has its own
/// positional `<workspace>` argument): combining them is a hard error,
/// raised by `main.rs` at dispatch time. The clap `id` is namespaced as
/// `global_workspace_path` so it does not collide with the `workspace`
/// positional that lives on each `WorkspaceCommand` variant.
#[arg(
id = "global_workspace_path",
long = "workspace",
global = true,
value_name = "PATH",
env = "SQRY_WORKSPACE_FILE",
help_heading = headings::COMMON_OPTIONS,
display_order = 41
)]
pub workspace: Option<PathBuf>,
/// Display fully qualified symbol names in CLI output.
///
/// Helpful for disambiguating relation queries (callers/callees) where
/// multiple namespaces define the same method name.
#[arg(long, global = true, help_heading = headings::OUTPUT_CONTROL, display_order = 30)]
pub qualified_names: bool,
// ===== Index Validation Flags (P1-14) =====
/// Index validation strictness level (off, warn, fail)
///
/// Controls how to handle index corruption during load:
/// - off: Skip validation entirely (fastest)
/// - warn: Log warnings but continue (default)
/// - fail: Abort on validation errors
#[arg(long, value_enum, default_value = "warn", global = true, help_heading = headings::INDEX_CONFIGURATION, display_order = 40)]
pub validate: ValidationMode,
/// Automatically rebuild index if validation fails
///
/// When set, if index validation fails in strict mode, sqry will
/// automatically rebuild the index once and retry. Useful for
/// recovering from transient corruption without manual intervention.
#[arg(long, requires = "validate", global = true, help_heading = headings::INDEX_CONFIGURATION, display_order = 41)]
pub auto_rebuild: bool,
/// Maximum ratio of dangling references before rebuild (0.0-1.0)
///
/// Sets the threshold for dangling reference errors during validation.
/// Default: 0.05 (5%). If more than this ratio of symbols have dangling
/// references, validation will fail in strict mode.
#[arg(long, value_name = "RATIO", global = true, help_heading = headings::INDEX_CONFIGURATION, display_order = 42)]
pub threshold_dangling_refs: Option<f64>,
/// Maximum ratio of orphaned files before rebuild (0.0-1.0)
///
/// Sets the threshold for orphaned file errors during validation.
/// Default: 0.20 (20%). If more than this ratio of indexed files are
/// orphaned (no longer exist on disk), validation will fail.
#[arg(long, value_name = "RATIO", global = true, help_heading = headings::INDEX_CONFIGURATION, display_order = 43)]
pub threshold_orphaned_files: Option<f64>,
/// Maximum ratio of ID gaps before warning (0.0-1.0)
///
/// Sets the threshold for ID gap warnings during validation.
/// Default: 0.10 (10%). If more than this ratio of symbol IDs have gaps,
/// validation will warn or fail depending on strictness.
#[arg(long, value_name = "RATIO", global = true, help_heading = headings::INDEX_CONFIGURATION, display_order = 44)]
pub threshold_id_gaps: Option<f64>,
// ===== Hybrid Search Flags =====
/// Force text search mode (skip semantic, use ripgrep)
#[arg(long, short = 't', conflicts_with = "semantic", help_heading = headings::SEARCH_MODES, display_order = 10)]
pub text: bool,
/// Force semantic search mode (skip text fallback)
#[arg(long, short = 's', conflicts_with = "text", help_heading = headings::SEARCH_MODES, display_order = 11)]
pub semantic: bool,
/// Disable automatic fallback to text search
#[arg(long, conflicts_with_all = ["text", "semantic"], help_heading = headings::SEARCH_MODES, display_order = 20)]
pub no_fallback: bool,
/// Number of context lines for text search results
#[arg(long, default_value = "2", help_heading = headings::SEARCH_MODES, display_order = 30)]
pub context: usize,
/// Maximum text search results
#[arg(long, default_value = "1000", help_heading = headings::SEARCH_MODES, display_order = 31)]
pub max_text_results: usize,
}
/// Plugin-selection controls shared by indexing and selected read paths.
#[derive(Args, Debug, Clone, Default)]
pub struct PluginSelectionArgs {
/// Enable all high-cost plugins.
///
/// High-cost plugins are those classified as `high_wall_clock` in the
/// shared plugin registry.
#[arg(long, conflicts_with = "exclude_high_cost", help_heading = headings::PLUGIN_SELECTION, display_order = 10)]
pub include_high_cost: bool,
/// Exclude all high-cost plugins.
///
/// This is mainly useful to override `SQRY_INCLUDE_HIGH_COST=1`.
#[arg(long, conflicts_with = "include_high_cost", help_heading = headings::PLUGIN_SELECTION, display_order = 20)]
pub exclude_high_cost: bool,
/// Force-enable a plugin by id.
///
/// Repeat this flag to enable multiple plugins. Explicit enable beats the
/// global high-cost mode unless the same plugin is also explicitly disabled.
#[arg(long = "enable-plugin", alias = "enable-language", value_name = "ID", help_heading = headings::PLUGIN_SELECTION, display_order = 30)]
pub enable_plugins: Vec<String>,
/// Force-disable a plugin by id.
///
/// Repeat this flag to disable multiple plugins. Explicit disable wins over
/// explicit enable and global high-cost mode.
#[arg(long = "disable-plugin", alias = "disable-language", value_name = "ID", help_heading = headings::PLUGIN_SELECTION, display_order = 40)]
pub disable_plugins: Vec<String>,
}
/// Batch command arguments with taxonomy headings and workflow ordering
#[derive(Args, Debug, Clone)]
pub struct BatchCommand {
/// Directory containing the indexed codebase (`.sqry/graph/snapshot.sqry`).
#[arg(value_name = "PATH", help_heading = headings::BATCH_INPUTS, display_order = 10)]
pub path: Option<String>,
/// File containing queries (one per line).
#[arg(long, value_name = "FILE", help_heading = headings::BATCH_INPUTS, display_order = 20)]
pub queries: PathBuf,
/// Set output format for results.
#[arg(long, value_name = "FORMAT", default_value = "text", value_enum, help_heading = headings::BATCH_OUTPUT_TARGETS, display_order = 10)]
pub output: BatchFormat,
/// Write results to specified file instead of stdout.
#[arg(long, value_name = "FILE", help_heading = headings::BATCH_OUTPUT_TARGETS, display_order = 20)]
pub output_file: Option<PathBuf>,
/// Continue processing if a query fails.
#[arg(long, help_heading = headings::BATCH_SESSION_CONTROL, display_order = 10)]
pub continue_on_error: bool,
/// Print aggregate statistics after completion.
#[arg(long, help_heading = headings::BATCH_SESSION_CONTROL, display_order = 20)]
pub stats: bool,
/// Use sequential execution instead of parallel (for debugging).
///
/// By default, batch queries execute in parallel for better performance.
/// Use this flag to force sequential execution for debugging or profiling.
#[arg(long, help_heading = headings::BATCH_SESSION_CONTROL, display_order = 30)]
pub sequential: bool,
}
/// Completions command arguments with taxonomy headings and workflow ordering
#[derive(Args, Debug, Clone)]
pub struct CompletionsCommand {
/// Shell to generate completions for.
#[arg(value_enum, help_heading = headings::COMPLETIONS_SHELL_TARGETS, display_order = 10)]
pub shell: Shell,
}
/// Available subcommands
#[derive(Subcommand, Debug, Clone)]
#[command(verbatim_doc_comment)]
pub enum Command {
/// Visualize code relationships as diagrams
#[command(display_order = 30)]
Visualize(VisualizeCommand),
/// Search for symbols by pattern (simple pattern matching)
///
/// Fast pattern-based search using regex or literal matching.
/// Use this for quick searches with simple text patterns.
///
/// For complex queries with boolean logic and AST predicates, use 'query' instead.
///
/// Examples:
/// sqry search "test.*" # Find symbols matching regex
/// sqry search "test" --save-as find-tests # Save as alias
/// sqry search "test" --validate fail # Strict index validation
///
/// For kind/language/fuzzy filtering, use the top-level shorthand:
/// sqry --kind function "test" # Filter by kind
/// sqry --exact "main" # Exact match
/// sqry --fuzzy "config" # Fuzzy search
///
/// See also: 'sqry query' for structured AST-aware queries
#[command(display_order = 1, verbatim_doc_comment)]
Search {
/// Search pattern (regex or literal with --exact).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
pattern: String,
/// Search path. For fuzzy search, walks up directory tree to find nearest .sqry-index if needed.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 20)]
path: Option<String>,
/// Save this search as a named alias for later reuse.
///
/// The alias can be invoked with @name syntax:
/// sqry search "test" --save-as find-tests
/// sqry @find-tests src/
#[arg(long, value_name = "NAME", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 10)]
save_as: Option<String>,
/// Save alias to global storage (~/.config/sqry/) instead of local.
///
/// Global aliases are available across all projects.
/// Local aliases (default) are project-specific.
#[arg(long, requires = "save_as", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 20)]
global: bool,
/// Optional description for the saved alias.
#[arg(long, requires = "save_as", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 30)]
description: Option<String>,
/// Index validation mode before search execution.
///
/// Controls how sqry handles stale indices (files removed since indexing):
/// - `warn`: Log warning but continue (default)
/// - `fail`: Exit with code 2 if >20% of indexed files are missing
/// - `off`: Skip validation entirely
///
/// Examples:
/// sqry search "test" --validate fail # Strict mode
/// sqry search "test" --validate off # Fast mode
#[arg(long, value_enum, default_value = "warn", help_heading = headings::SECURITY_LIMITS, display_order = 30)]
validate: ValidationMode,
/// Only show symbols active under given cfg predicate.
///
/// Filters search results to symbols matching the specified cfg condition.
/// Example: --cfg-filter test only shows symbols gated by #[cfg(test)].
#[arg(long, value_name = "PREDICATE", help_heading = headings::SEARCH_INPUT, display_order = 30)]
cfg_filter: Option<String>,
/// Include macro-generated symbols in results (default: excluded).
///
/// By default, symbols generated by macro expansion (e.g., derive impls)
/// are excluded from search results. Use this flag to include them.
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 31)]
include_generated: bool,
/// Show macro boundary metadata in output.
///
/// When enabled, search results include macro boundary information
/// such as cfg conditions, macro source, and generated-symbol markers.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 40)]
macro_boundaries: bool,
},
/// Execute AST-aware query (structured queries with boolean logic)
///
/// Powerful structured queries using predicates and boolean operators.
/// Use this for complex searches that combine multiple criteria.
///
/// For simple pattern matching, use 'search' instead.
///
/// Predicate examples:
/// - kind:function # Find functions
/// - name:test # Name contains 'test'
/// - lang:rust # Rust files only
/// - visibility:public # Public symbols
/// - async:true # Async functions
///
/// Boolean logic:
/// - kind:function AND name:test # Functions with 'test' in name
/// - kind:class OR kind:struct # All classes or structs
/// - lang:rust AND visibility:public # Public Rust symbols
///
/// Relation queries (28 languages with full support):
/// - callers:authenticate # Who calls authenticate?
/// - callees:processData # What does processData call?
/// - exports:UserService # What does `UserService` export?
/// - imports:database # What imports database?
///
/// Supported for: C, C++, C#, CSS, Dart, Elixir, Go, Groovy, Haskell, HTML,
/// Java, JavaScript, Kotlin, Lua, Perl, PHP, Python, R, Ruby, Rust, Scala,
/// Shell, SQL, Svelte, Swift, TypeScript, Vue, Zig
///
/// Saving as alias:
/// sqry query "kind:function AND name:test" --save-as test-funcs
/// sqry @test-funcs src/
///
/// See also: 'sqry search' for simple pattern-based searches
#[command(display_order = 2, verbatim_doc_comment)]
Query {
/// Query expression with predicates.
#[arg(help_heading = headings::QUERY_INPUT, display_order = 10)]
query: String,
/// Search path. If no index exists here, walks up directory tree to find nearest .sqry-index.
#[arg(help_heading = headings::QUERY_INPUT, display_order = 20)]
path: Option<String>,
/// Use persistent session (keeps .sqry-index hot for repeated queries).
#[arg(long, help_heading = headings::PERFORMANCE_DEBUGGING, display_order = 10)]
session: bool,
/// Explain query execution (debug mode).
#[arg(long, help_heading = headings::PERFORMANCE_DEBUGGING, display_order = 20)]
explain: bool,
/// Disable parallel query execution (for A/B performance testing).
///
/// By default, OR branches (3+) and symbol filtering (100+) use parallel execution.
/// Use this flag to force sequential execution for performance comparison.
#[arg(long, help_heading = headings::PERFORMANCE_DEBUGGING, display_order = 30)]
no_parallel: bool,
/// Show verbose output including cache statistics.
#[arg(long, short = 'v', help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
verbose: bool,
/// Maximum query execution time in seconds (default: 30s, max: 30s).
///
/// Queries exceeding this limit will be terminated with partial results.
/// The 30-second ceiling is a NON-NEGOTIABLE security requirement.
/// Specify lower values for faster feedback on interactive queries.
///
/// Examples:
/// sqry query --timeout 10 "impl:Debug" # 10 second timeout
/// sqry query --timeout 5 "kind:function" # 5 second timeout
#[arg(long, value_name = "SECS", help_heading = headings::SECURITY_LIMITS, display_order = 10)]
timeout: Option<u64>,
/// Maximum number of results to return (default: 10000).
///
/// Queries returning more results will be truncated.
/// Use this to limit memory usage for large result sets.
///
/// Examples:
/// sqry query --limit 100 "kind:function" # First 100 functions
/// sqry query --limit 1000 "impl:Debug" # First 1000 Debug impls
#[arg(long, value_name = "N", help_heading = headings::SECURITY_LIMITS, display_order = 20)]
limit: Option<usize>,
/// Save this query as a named alias for later reuse.
///
/// The alias can be invoked with @name syntax:
/// sqry query "kind:function" --save-as all-funcs
/// sqry @all-funcs src/
#[arg(long, value_name = "NAME", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 10)]
save_as: Option<String>,
/// Save alias to global storage (~/.config/sqry/) instead of local.
///
/// Global aliases are available across all projects.
/// Local aliases (default) are project-specific.
#[arg(long, requires = "save_as", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 20)]
global: bool,
/// Optional description for the saved alias.
#[arg(long, requires = "save_as", help_heading = headings::PERSISTENCE_OPTIONS, display_order = 30)]
description: Option<String>,
/// Index validation mode before query execution.
///
/// Controls how sqry handles stale indices (files removed since indexing):
/// - `warn`: Log warning but continue (default)
/// - `fail`: Exit with code 2 if >20% of indexed files are missing
/// - `off`: Skip validation entirely
///
/// Examples:
/// sqry query "kind:function" --validate fail # Strict mode
/// sqry query "kind:function" --validate off # Fast mode
#[arg(long, value_enum, default_value = "warn", help_heading = headings::SECURITY_LIMITS, display_order = 30)]
validate: ValidationMode,
/// Substitute variables in the query expression.
///
/// Variables are referenced as $name in queries and resolved before execution.
/// Specify as KEY=VALUE pairs; can be repeated.
///
/// Examples:
/// sqry query "kind:\$type" --var type=function
/// sqry query "kind:\$k AND lang:\$l" --var k=function --var l=rust
#[arg(long = "var", value_name = "KEY=VALUE", help_heading = headings::QUERY_INPUT, display_order = 30)]
var: Vec<String>,
#[command(flatten)]
plugin_selection: PluginSelectionArgs,
},
/// Execute a structural query through the sqry-db planner (DB13).
///
/// Uses the new salsa-style planner pipeline (parse → compile → fuse →
/// execute) instead of the legacy `query` engine. Accepts the same text
/// syntax documented in `docs/superpowers/specs/2026-04-12-derived-analysis-db-query-planner-design.md`
/// (§3 — Text Syntax Frontend).
///
/// Predicate examples:
/// - `kind:function` Find every function
/// - `kind:function has:caller` Functions that have at least one caller
/// - `kind:function callers:main` Functions called by `main`
/// - `kind:function traverse:reverse(calls,3)` Callers up to 3 hops deep
/// - `kind:function in:src/api/**` Functions under src/api
/// - `kind:function references ~= /handle_.*/i` Regex-matched references
/// - `kind:struct implements:Visitor` Structs implementing `Visitor`
///
/// Subqueries nest via parentheses:
/// - `kind:function callees:(kind:method name:visit_*)`
///
/// DB13 scope note: this subcommand is parallel to the legacy `query`;
/// DB14+ will migrate the legacy handlers and eventually replace
/// `sqry query` with the planner path.
#[command(name = "plan-query", display_order = 3, verbatim_doc_comment)]
PlanQuery {
/// Text query to parse and execute.
#[arg(help_heading = headings::QUERY_INPUT, display_order = 10)]
query: String,
/// Search path (defaults to current directory). If no index exists
/// here, walks up to find the nearest `.sqry-index`.
#[arg(help_heading = headings::QUERY_INPUT, display_order = 20)]
path: Option<String>,
/// Maximum number of results to print (default: 1000).
#[arg(long, value_name = "N", default_value = "1000", help_heading = headings::SECURITY_LIMITS, display_order = 10)]
limit: usize,
},
/// Graph-based queries and analysis
///
/// Advanced graph operations using the unified graph architecture.
/// All subcommands are noun-based and represent different analysis types.
///
/// Available analyses:
/// - `trace-path <from> <to>` # Find shortest path between symbols
/// - `call-chain-depth <symbol>` # Calculate maximum call depth
/// - `dependency-tree <module>` # Show transitive dependencies
/// - nodes # List unified graph nodes
/// - edges # List unified graph edges
/// - cross-language # List cross-language relationships
/// - stats # Show graph statistics
/// - cycles # Detect circular dependencies
/// - complexity # Calculate code complexity
///
/// All commands support --format json for programmatic use.
#[command(display_order = 20)]
Graph {
#[command(subcommand)]
operation: GraphOperation,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::GRAPH_CONFIGURATION, display_order = 10)]
path: Option<String>,
/// Output format (json, text, dot, mermaid, d2).
#[arg(long, short = 'f', default_value = "text", help_heading = headings::GRAPH_CONFIGURATION, display_order = 20)]
format: String,
/// Show verbose output with detailed metadata.
#[arg(long, short = 'v', help_heading = headings::GRAPH_CONFIGURATION, display_order = 30)]
verbose: bool,
},
/// Start an interactive shell that keeps the session cache warm
#[command(display_order = 60)]
Shell {
/// Directory containing the `.sqry-index` file.
#[arg(value_name = "PATH", help_heading = headings::SHELL_CONFIGURATION, display_order = 10)]
path: Option<String>,
},
/// Execute multiple queries from a batch file using a warm session
#[command(display_order = 61)]
Batch(BatchCommand),
/// Build symbol index and graph analyses for fast queries
///
/// Creates a persistent index of all symbols in the specified directory.
/// The index is saved to .sqry/ and includes precomputed graph analyses
/// for cycle detection, reachability, and path queries.
/// Uses parallel processing by default for faster indexing.
#[command(display_order = 10)]
Index {
/// Directory to index (defaults to current directory).
#[arg(help_heading = headings::INDEX_INPUT, display_order = 10)]
path: Option<String>,
/// Force rebuild even if index exists.
#[arg(long, short = 'f', alias = "rebuild", help_heading = headings::INDEX_CONFIGURATION, display_order = 10)]
force: bool,
/// Show index status without building.
///
/// Returns metadata about the existing index (age, symbol count, languages).
/// Useful for programmatic consumers to check if indexing is needed.
#[arg(long, short = 's', help_heading = headings::INDEX_CONFIGURATION, display_order = 20)]
status: bool,
/// Automatically add .sqry-index/ to .gitignore if not already present.
#[arg(long, help_heading = headings::INDEX_CONFIGURATION, display_order = 30)]
add_to_gitignore: bool,
/// Number of threads for parallel indexing (default: auto-detect).
///
/// Set to 1 for single-threaded (useful for debugging).
/// Defaults to number of CPU cores.
#[arg(long, short = 't', help_heading = headings::PERFORMANCE_TUNING, display_order = 10)]
threads: Option<usize>,
/// Disable incremental indexing (hash-based change detection).
///
/// When set, indexing will skip the persistent hash index and avoid
/// hash-based change detection entirely. Useful for debugging or
/// forcing metadata-only evaluation.
#[arg(long = "no-incremental", help_heading = headings::PERFORMANCE_TUNING, display_order = 20)]
no_incremental: bool,
/// Override cache directory for incremental indexing (default: .sqry-cache).
///
/// Points sqry at an alternate cache location for the hash index.
/// Handy for ephemeral or sandboxed environments.
#[arg(long = "cache-dir", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 10)]
cache_dir: Option<String>,
/// Disable index compression (P1-12: Index Compression).
///
/// By default, indexes are compressed with zstd for faster load times
/// and reduced disk space. Use this flag to store uncompressed indexes
/// (useful for debugging or compatibility testing).
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 20)]
no_compress: bool,
/// Metrics export format for validation status (json or prometheus).
///
/// Used with --status --json to export validation metrics in different
/// formats. Prometheus format outputs OpenMetrics-compatible text for
/// monitoring systems. JSON format (default) provides structured data.
#[arg(long, short = 'M', value_enum, default_value = "json", requires = "status", help_heading = headings::OUTPUT_CONTROL, display_order = 30)]
metrics_format: MetricsFormat,
/// Enable live macro expansion during indexing (executes cargo expand — security opt-in).
///
/// When enabled, sqry runs `cargo expand` to capture macro-generated symbols.
/// This executes build scripts and proc macros, so only use on trusted codebases.
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 30)]
enable_macro_expansion: bool,
/// Set active cfg flags for conditional compilation analysis.
///
/// Can be specified multiple times (e.g., --cfg test --cfg unix).
/// Symbols gated by `#[cfg()]` will be marked active/inactive based on these flags.
#[arg(long = "cfg", value_name = "PREDICATE", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 31)]
cfg_flags: Vec<String>,
/// Use pre-generated expand cache instead of live expansion.
///
/// Points to a directory containing cached macro expansion output
/// (generated by `sqry cache expand`). Avoids executing cargo expand
/// during indexing.
#[arg(long, value_name = "DIR", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 32)]
expand_cache: Option<PathBuf>,
/// Enable JVM classpath analysis.
///
/// Detects the project's build system (Gradle, Maven, Bazel, sbt),
/// resolves dependency JARs, parses bytecode into class stubs, and
/// emits synthetic graph nodes for classpath types. Enables cross-
/// reference resolution from workspace source to library classes.
///
/// Requires the `jvm-classpath` feature at compile time.
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 40)]
classpath: bool,
/// Disable classpath analysis (overrides config defaults).
#[arg(long, conflicts_with = "classpath", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 41)]
no_classpath: bool,
/// Classpath analysis depth.
///
/// `full` (default): include all transitive dependencies.
/// `shallow`: only direct (compile-scope) dependencies.
#[arg(long, value_enum, default_value = "full", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 42)]
classpath_depth: ClasspathDepthArg,
/// Manual classpath file (one JAR path per line).
///
/// When provided, skips build system detection and resolution entirely.
/// Lines starting with `#` are treated as comments.
#[arg(long, value_name = "FILE", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 43)]
classpath_file: Option<PathBuf>,
/// Override build system detection for classpath analysis.
///
/// Valid values: gradle, maven, bazel, sbt (case-insensitive).
#[arg(long, value_name = "SYSTEM", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 44)]
build_system: Option<String>,
/// Force classpath re-resolution (ignore cached classpath).
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 45)]
force_classpath: bool,
#[command(flatten)]
plugin_selection: PluginSelectionArgs,
},
/// Build precomputed graph analyses for fast query performance
///
/// Computes CSR adjacency, SCC (Strongly Connected Components), condensation DAGs,
/// and 2-hop interval labels to eliminate O(V+E) query-time costs. Analysis files
/// are persisted to .sqry/analysis/ and enable fast cycle detection, reachability
/// queries, and path finding.
///
/// Note: `sqry index` already builds a ready graph with analysis artifacts.
/// Run `sqry analyze` when you want to rebuild analyses with explicit
/// tuning controls or after changing analysis configuration.
///
/// Examples:
/// sqry analyze # Rebuild analyses for current index
/// sqry analyze --force # Force analysis rebuild
#[command(display_order = 13, verbatim_doc_comment)]
Analyze {
/// Search path (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Force rebuild even if analysis files exist.
#[arg(long, short = 'f', help_heading = headings::INDEX_CONFIGURATION, display_order = 10)]
force: bool,
/// Number of threads for parallel analysis (default: auto-detect).
///
/// Controls the rayon thread pool size for SCC/condensation DAG
/// computation. Set to 1 for single-threaded (useful for debugging).
/// Defaults to number of CPU cores.
#[arg(long, short = 't', help_heading = headings::PERFORMANCE_TUNING, display_order = 10)]
threads: Option<usize>,
/// Override maximum 2-hop label intervals per edge kind.
///
/// Controls the maximum number of reachability intervals computed
/// per edge kind. Larger budgets enable O(1) reachability queries
/// but use more memory. Default: from config or 15,000,000.
#[arg(long = "label-budget", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 30)]
label_budget: Option<u64>,
/// Override density gate threshold.
///
/// Skip 2-hop label computation when `condensation_edges > threshold * scc_count`.
/// Prevents multi-minute hangs on dense import/reference graphs.
/// 0 = disabled. Default: from config or 64.
#[arg(long = "density-threshold", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 31)]
density_threshold: Option<u64>,
/// Override budget-exceeded policy: `"degrade"` (BFS fallback) or `"fail"`.
///
/// When the label budget is exceeded for an edge kind:
/// - `"degrade"`: Fall back to BFS on the condensation DAG (default)
/// - "fail": Return an error and abort analysis
#[arg(long = "budget-exceeded-policy", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 32, value_parser = clap::builder::PossibleValuesParser::new(["degrade", "fail"]))]
budget_exceeded_policy: Option<String>,
/// Skip 2-hop interval label computation entirely.
///
/// When set, the analysis builds CSR + SCC + Condensation DAG but skips
/// the expensive 2-hop label phase. Reachability queries fall back to BFS
/// on the condensation DAG (~10-50ms per query instead of O(1)).
/// Useful for very large codebases where label computation is too slow.
#[arg(long = "no-labels", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 33)]
no_labels: bool,
},
/// Start the sqry Language Server Protocol endpoint
#[command(display_order = 50)]
Lsp {
#[command(flatten)]
options: LspOptions,
},
/// Update existing symbol index
///
/// Incrementally updates the index by re-indexing only changed files.
/// Much faster than a full rebuild for large codebases.
#[command(display_order = 11)]
Update {
/// Directory with existing index (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Number of threads for parallel indexing (default: auto-detect).
///
/// Set to 1 for single-threaded (useful for debugging).
/// Defaults to number of CPU cores.
#[arg(long, short = 't', help_heading = headings::PERFORMANCE_TUNING, display_order = 10)]
threads: Option<usize>,
/// Disable incremental indexing (force metadata-only or full updates).
///
/// When set, the update process will not use the hash index and will
/// rely on metadata-only checks for staleness.
#[arg(long = "no-incremental", help_heading = headings::UPDATE_CONFIGURATION, display_order = 10)]
no_incremental: bool,
/// Override cache directory for incremental indexing (default: .sqry-cache).
///
/// Points sqry at an alternate cache location for the hash index.
#[arg(long = "cache-dir", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 10)]
cache_dir: Option<String>,
/// Show statistics about the update.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
stats: bool,
/// Enable JVM classpath analysis.
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 40)]
classpath: bool,
/// Disable classpath analysis (overrides config defaults).
#[arg(long, conflicts_with = "classpath", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 41)]
no_classpath: bool,
/// Classpath analysis depth.
#[arg(long, value_enum, default_value = "full", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 42)]
classpath_depth: ClasspathDepthArg,
/// Manual classpath file (one JAR path per line).
#[arg(long, value_name = "FILE", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 43)]
classpath_file: Option<PathBuf>,
/// Override build system detection for classpath analysis.
#[arg(long, value_name = "SYSTEM", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 44)]
build_system: Option<String>,
/// Force classpath re-resolution (ignore cached classpath).
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 45)]
force_classpath: bool,
#[command(flatten)]
plugin_selection: PluginSelectionArgs,
},
/// Watch directory and auto-update index on file changes
///
/// Monitors the directory for file system changes and automatically updates
/// the index in real-time. Uses OS-level file monitoring (inotify/FSEvents/Windows)
/// for <1ms change detection latency.
///
/// Press Ctrl+C to stop watching.
#[command(display_order = 12)]
Watch {
/// Directory to watch (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Number of threads for parallel indexing (default: auto-detect).
///
/// Set to 1 for single-threaded (useful for debugging).
/// Defaults to number of CPU cores.
#[arg(long, short = 't', help_heading = headings::PERFORMANCE_TUNING, display_order = 10)]
threads: Option<usize>,
/// Build initial index if it doesn't exist.
#[arg(long, help_heading = headings::WATCH_CONFIGURATION, display_order = 10)]
build: bool,
/// Debounce duration in milliseconds.
///
/// Wait time after detecting a change before processing to collect
/// rapid-fire changes (e.g., from editor saves).
///
/// Default is platform-aware: 400ms on macOS, 100ms on Linux/Windows.
/// Can also be set via `SQRY_LIMITS__WATCH__DEBOUNCE_MS` env var.
#[arg(long, short = 'd', help_heading = headings::WATCH_CONFIGURATION, display_order = 20)]
debounce: Option<u64>,
/// Show detailed statistics for each update.
#[arg(long, short = 's', help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
stats: bool,
/// Enable JVM classpath analysis.
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 40)]
classpath: bool,
/// Disable classpath analysis (overrides config defaults).
#[arg(long, conflicts_with = "classpath", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 41)]
no_classpath: bool,
/// Classpath analysis depth.
#[arg(long, value_enum, default_value = "full", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 42)]
classpath_depth: ClasspathDepthArg,
/// Manual classpath file (one JAR path per line).
#[arg(long, value_name = "FILE", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 43)]
classpath_file: Option<PathBuf>,
/// Override build system detection for classpath analysis.
#[arg(long, value_name = "SYSTEM", help_heading = headings::ADVANCED_CONFIGURATION, display_order = 44)]
build_system: Option<String>,
/// Force classpath re-resolution (ignore cached classpath).
#[arg(long, help_heading = headings::ADVANCED_CONFIGURATION, display_order = 45)]
force_classpath: bool,
#[command(flatten)]
plugin_selection: PluginSelectionArgs,
},
/// Repair corrupted index by fixing common issues
///
/// Automatically detects and fixes common index corruption issues:
/// - Orphaned symbols (files no longer exist)
/// - Dangling references (symbols reference non-existent dependencies)
/// - Invalid checksums
///
/// Use --dry-run to preview changes without modifying the index.
#[command(display_order = 14)]
Repair {
/// Directory with existing index (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Remove symbols for files that no longer exist on disk.
#[arg(long, help_heading = headings::REPAIR_OPTIONS, display_order = 10)]
fix_orphans: bool,
/// Remove dangling references to non-existent symbols.
#[arg(long, help_heading = headings::REPAIR_OPTIONS, display_order = 20)]
fix_dangling: bool,
/// Recompute index checksum after repairs.
#[arg(long, help_heading = headings::REPAIR_OPTIONS, display_order = 30)]
recompute_checksum: bool,
/// Fix all detected issues (combines all repair options).
#[arg(long, conflicts_with_all = ["fix_orphans", "fix_dangling", "recompute_checksum"], help_heading = headings::REPAIR_OPTIONS, display_order = 5)]
fix_all: bool,
/// Preview changes without modifying the index (dry run).
#[arg(long, help_heading = headings::REPAIR_OPTIONS, display_order = 40)]
dry_run: bool,
},
/// Manage AST cache
///
/// Control the disk-persisted AST cache that speeds up queries by avoiding
/// expensive tree-sitter parsing. The cache is stored in .sqry-cache/ and
/// is shared across all sqry processes.
#[command(display_order = 41)]
Cache {
#[command(subcommand)]
action: CacheAction,
},
/// Manage graph config (.sqry/graph/config/config.json)
///
/// Configure sqry behavior through the unified config partition.
/// All settings are stored in `.sqry/graph/config/config.json`.
///
/// Examples:
/// sqry config init # Initialize config with defaults
/// sqry config show # Display effective config
/// sqry config set `limits.max_results` 10000 # Update a setting
/// sqry config get `limits.max_results` # Get a single value
/// sqry config validate # Validate config file
/// sqry config alias set my-funcs "kind:function" # Create alias
/// sqry config alias list # List all aliases
#[command(display_order = 40, verbatim_doc_comment)]
Config {
#[command(subcommand)]
action: ConfigAction,
},
/// Generate shell completions
///
/// Generate shell completion scripts for bash, zsh, fish, or `PowerShell`.
/// Install by redirecting output to the appropriate location for your shell.
///
/// Examples:
/// sqry completions bash > /`etc/bash_completion.d/sqry`
/// sqry completions zsh > ~/.zfunc/_sqry
/// sqry completions fish > ~/.config/fish/completions/sqry.fish
#[command(display_order = 45, verbatim_doc_comment)]
Completions(CompletionsCommand),
/// Manage multi-repository workspaces
#[command(display_order = 42)]
Workspace {
#[command(subcommand)]
action: WorkspaceCommand,
},
/// Manage saved query aliases
///
/// Save frequently used queries as named aliases for easy reuse.
/// Aliases can be stored globally (~/.config/sqry/) or locally (.sqry-index.user).
///
/// Examples:
/// sqry alias list # List all aliases
/// sqry alias show my-funcs # Show alias details
/// sqry alias delete my-funcs # Delete an alias
/// sqry alias rename old-name new # Rename an alias
///
/// To create an alias, use --save-as with search/query commands:
/// sqry query "kind:function" --save-as my-funcs
/// sqry search "test" --save-as find-tests --global
///
/// To execute an alias, use @name syntax:
/// sqry @my-funcs
/// sqry @find-tests src/
#[command(display_order = 43, verbatim_doc_comment)]
Alias {
#[command(subcommand)]
action: AliasAction,
},
/// Manage query history
///
/// View and manage your query history. History is recorded automatically
/// for search and query commands (unless disabled via `SQRY_NO_HISTORY=1`).
///
/// Examples:
/// sqry history list # List recent queries
/// sqry history list --limit 50 # Show last 50 queries
/// sqry history search "function" # Search history
/// sqry history clear # Clear all history
/// sqry history clear --older 30d # Clear entries older than 30 days
/// sqry history stats # Show history statistics
///
/// Sensitive data (API keys, tokens) is automatically redacted.
#[command(display_order = 44, verbatim_doc_comment)]
History {
#[command(subcommand)]
action: HistoryAction,
},
/// Natural language interface for sqry queries
///
/// Translate natural language descriptions into sqry commands.
/// Uses a safety-focused translation pipeline that validates all
/// generated commands before execution.
///
/// Response tiers based on confidence:
/// - Execute (≥85%): Run command automatically
/// - Confirm (65-85%): Ask for user confirmation
/// - Disambiguate (<65%): Present options to choose from
/// - Reject: Cannot safely translate
///
/// Examples:
/// sqry ask "find all public functions in rust"
/// sqry ask "who calls authenticate"
/// sqry ask "trace path from main to database"
/// sqry ask --auto-execute "find all classes"
///
/// Safety: Commands are validated against a whitelist and checked
/// for shell injection, path traversal, and other attacks.
#[command(display_order = 3, verbatim_doc_comment)]
Ask {
/// Natural language query to translate.
#[arg(help_heading = headings::NL_INPUT, display_order = 10)]
query: String,
/// Search path (defaults to current directory).
#[arg(help_heading = headings::NL_INPUT, display_order = 20)]
path: Option<String>,
/// Auto-execute high-confidence commands without confirmation.
///
/// When enabled, commands with ≥85% confidence will execute
/// immediately. Otherwise, all commands require confirmation.
#[arg(long, help_heading = headings::NL_CONFIGURATION, display_order = 10)]
auto_execute: bool,
/// Show the translated command without executing.
///
/// Useful for understanding what command would be generated
/// from your natural language query.
#[arg(long, help_heading = headings::NL_CONFIGURATION, display_order = 20)]
dry_run: bool,
/// Minimum confidence threshold for auto-execution (0.0-1.0).
///
/// Commands with confidence below this threshold will always
/// require confirmation, even with --auto-execute.
#[arg(long, default_value = "0.85", help_heading = headings::NL_CONFIGURATION, display_order = 30)]
threshold: f32,
},
/// View usage insights and manage local diagnostics
///
/// sqry captures anonymous behavioral patterns locally to help you
/// understand your usage and improve the tool. All data stays on
/// your machine unless you explicitly choose to share.
///
/// Examples:
/// sqry insights show # Show current week's summary
/// sqry insights show --week 2025-W50 # Show specific week
/// sqry insights config # Show configuration
/// sqry insights config --disable # Disable uses capture
/// sqry insights status # Show storage status
/// sqry insights prune --older 90d # Clean up old data
///
/// Privacy: All data is stored locally. No network calls are made
/// unless you explicitly use --share (which generates a file, not
/// a network request).
#[command(display_order = 62, verbatim_doc_comment)]
Insights {
#[command(subcommand)]
action: InsightsAction,
},
/// Generate a troubleshooting bundle for issue reporting
///
/// Creates a structured bundle containing diagnostic information
/// that can be shared with the sqry team. All data is sanitized -
/// no code content, file paths, or secrets are included.
///
/// The bundle includes:
/// - System information (OS, architecture)
/// - sqry version and build type
/// - Sanitized configuration
/// - Recent use events (last 24h)
/// - Recent errors
///
/// Examples:
/// sqry troubleshoot # Generate to stdout
/// sqry troubleshoot -o bundle.json # Save to file
/// sqry troubleshoot --dry-run # Preview without generating
/// sqry troubleshoot --include-trace # Include workflow trace
///
/// Privacy: No paths, code content, or secrets are included.
/// Review the output before sharing if you have concerns.
#[command(display_order = 63, verbatim_doc_comment)]
Troubleshoot {
/// Output file path (default: stdout)
#[arg(short = 'o', long, value_name = "FILE", help_heading = headings::INSIGHTS_OUTPUT, display_order = 10)]
output: Option<String>,
/// Preview bundle contents without generating
#[arg(long = "dry-run", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 10)]
dry_run: bool,
/// Include workflow trace (opt-in, requires explicit consent)
///
/// Adds a sequence of recent workflow steps to the bundle.
/// The trace helps understand how operations were performed
/// but reveals more behavioral patterns than the default bundle.
#[arg(long, help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 20)]
include_trace: bool,
/// Time window for events to include (e.g., 24h, 7d)
///
/// Defaults to 24 hours. Longer windows provide more context
/// but may include older events.
#[arg(long, default_value = "24h", value_name = "DURATION", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 30)]
window: String,
},
/// Find duplicate code in the codebase
///
/// Detects similar or identical code patterns using structural analysis.
/// Supports different duplicate types:
/// - body: Functions with identical/similar bodies
/// - signature: Functions with identical signatures
/// - struct: Structs with similar field layouts
///
/// Examples:
/// sqry duplicates # Find body duplicates
/// sqry duplicates --type signature # Find signature duplicates
/// sqry duplicates --threshold 90 # 90% similarity threshold
/// sqry duplicates --exact # Exact matches only
#[command(display_order = 21, verbatim_doc_comment)]
Duplicates {
/// Search path (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Type of duplicate detection.
///
/// - body: Functions with identical/similar bodies (default)
/// - signature: Functions with identical signatures
/// - struct: Structs with similar field layouts
#[arg(long, short = 't', default_value = "body", help_heading = headings::DUPLICATE_OPTIONS, display_order = 10)]
r#type: String,
/// Similarity threshold (0-100, default: 80).
///
/// Higher values require more similarity to be considered duplicates.
/// 100 means exact matches only.
#[arg(long, default_value = "80", help_heading = headings::DUPLICATE_OPTIONS, display_order = 20)]
threshold: u32,
/// Maximum results to return.
#[arg(long, default_value = "100", help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
max_results: usize,
/// Exact matches only (equivalent to --threshold 100).
#[arg(long, help_heading = headings::DUPLICATE_OPTIONS, display_order = 30)]
exact: bool,
},
/// Find circular dependencies in the codebase
///
/// Detects cycles in call graphs, import graphs, or module dependencies.
/// Uses Tarjan's SCC algorithm for efficient O(V+E) detection.
///
/// Examples:
/// sqry cycles # Find call cycles
/// sqry cycles --type imports # Find import cycles
/// sqry cycles --min-depth 3 # Cycles with 3+ nodes
/// sqry cycles --include-self # Include self-loops
#[command(display_order = 22, verbatim_doc_comment)]
Cycles {
/// Search path (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Type of cycle detection.
///
/// - calls: Function/method call cycles (default)
/// - imports: File import cycles
/// - modules: Module-level cycles
#[arg(long, short = 't', default_value = "calls", help_heading = headings::CYCLE_OPTIONS, display_order = 10)]
r#type: String,
/// Minimum cycle depth (default: 2).
#[arg(long, default_value = "2", help_heading = headings::CYCLE_OPTIONS, display_order = 20)]
min_depth: usize,
/// Maximum cycle depth (default: unlimited).
#[arg(long, help_heading = headings::CYCLE_OPTIONS, display_order = 30)]
max_depth: Option<usize>,
/// Include self-loops (A → A).
#[arg(long, help_heading = headings::CYCLE_OPTIONS, display_order = 40)]
include_self: bool,
/// Maximum results to return.
#[arg(long, default_value = "100", help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
max_results: usize,
},
/// Find unused/dead code in the codebase
///
/// Detects symbols that are never referenced using reachability analysis.
/// Entry points (main, public lib exports, tests) are considered reachable.
///
/// Examples:
/// sqry unused # Find all unused symbols
/// sqry unused --scope public # Only public unused symbols
/// sqry unused --scope function # Only unused functions
/// sqry unused --lang rust # Only in Rust files
#[command(display_order = 23, verbatim_doc_comment)]
Unused {
/// Search path (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Scope of unused detection.
///
/// - all: All unused symbols (default)
/// - public: Public symbols with no external references
/// - private: Private symbols with no references
/// - function: Unused functions only
/// - struct: Unused structs/types only
#[arg(long, short = 's', default_value = "all", help_heading = headings::UNUSED_OPTIONS, display_order = 10)]
scope: String,
/// Filter by language.
#[arg(long, help_heading = headings::UNUSED_OPTIONS, display_order = 20)]
lang: Option<String>,
/// Filter by symbol kind.
#[arg(long, help_heading = headings::UNUSED_OPTIONS, display_order = 30)]
kind: Option<String>,
/// Maximum results to return.
#[arg(long, default_value = "100", help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
max_results: usize,
},
/// Export the code graph in various formats
///
/// Exports the unified code graph to DOT, D2, Mermaid, or JSON formats
/// for visualization or further analysis.
///
/// Examples:
/// sqry export # DOT format to stdout
/// sqry export --format mermaid # Mermaid format
/// sqry export --format d2 -o graph.d2 # D2 format to file
/// sqry export --highlight-cross # Highlight cross-language edges
/// sqry export --filter-lang rust,python # Filter languages
#[command(display_order = 31, verbatim_doc_comment)]
Export {
/// Search path (defaults to current directory).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
path: Option<String>,
/// Output format.
///
/// - dot: Graphviz DOT format (default)
/// - d2: D2 diagram format
/// - mermaid: Mermaid markdown format
/// - json: JSON format for programmatic use
#[arg(long, short = 'f', default_value = "dot", help_heading = headings::EXPORT_OPTIONS, display_order = 10)]
format: String,
/// Graph layout direction.
///
/// - lr: Left to right (default)
/// - tb: Top to bottom
#[arg(long, short = 'd', default_value = "lr", help_heading = headings::EXPORT_OPTIONS, display_order = 20)]
direction: String,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::EXPORT_OPTIONS, display_order = 30)]
filter_lang: Option<String>,
/// Filter by edge types (comma-separated: calls,imports,exports).
#[arg(long, help_heading = headings::EXPORT_OPTIONS, display_order = 40)]
filter_edge: Option<String>,
/// Highlight cross-language edges.
#[arg(long, help_heading = headings::EXPORT_OPTIONS, display_order = 50)]
highlight_cross: bool,
/// Show node details (signatures, docs).
#[arg(long, help_heading = headings::EXPORT_OPTIONS, display_order = 60)]
show_details: bool,
/// Show edge labels.
#[arg(long, help_heading = headings::EXPORT_OPTIONS, display_order = 70)]
show_labels: bool,
/// Output file (default: stdout).
#[arg(long, short = 'o', help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
output: Option<String>,
},
/// Explain a symbol with context and relations
///
/// Get detailed information about a symbol including its code context,
/// callers, callees, and other relationships.
///
/// Examples:
/// sqry explain src/main.rs main # Explain main function
/// sqry explain src/lib.rs `MyStruct` # Explain a struct
/// sqry explain --no-context file.rs func # Skip code context
/// sqry explain --no-relations file.rs fn # Skip relations
#[command(alias = "exp", display_order = 26, verbatim_doc_comment)]
Explain {
/// File containing the symbol.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
file: String,
/// Symbol name to explain.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 20)]
symbol: String,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 30)]
path: Option<String>,
/// Skip code context in output.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
no_context: bool,
/// Skip relation information in output.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 20)]
no_relations: bool,
},
/// Find symbols similar to a reference symbol
///
/// Uses fuzzy name matching to find symbols that are similar
/// to a given reference symbol.
///
/// Examples:
/// sqry similar src/lib.rs processData # Find similar to processData
/// sqry similar --threshold 0.8 file.rs fn # 80% similarity threshold
/// sqry similar --limit 20 file.rs func # Limit to 20 results
#[command(alias = "sim", display_order = 27, verbatim_doc_comment)]
Similar {
/// File containing the reference symbol.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
file: String,
/// Reference symbol name.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 20)]
symbol: String,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 30)]
path: Option<String>,
/// Minimum similarity threshold (0.0 to 1.0, default: 0.7).
#[arg(long, short = 't', default_value = "0.7", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
threshold: f64,
/// Maximum results to return (default: 20).
#[arg(long, short = 'l', default_value = "20", help_heading = headings::GRAPH_FILTERING, display_order = 20)]
limit: usize,
},
/// Extract a focused subgraph around seed symbols
///
/// Collects nodes and edges within a specified depth from seed symbols,
/// useful for understanding local code structure.
///
/// Examples:
/// sqry subgraph main # Subgraph around main
/// sqry subgraph -d 3 func1 func2 # Depth 3, multiple seeds
/// sqry subgraph --no-callers main # Only callees
/// sqry subgraph --include-imports main # Include import edges
#[command(alias = "sub", display_order = 28, verbatim_doc_comment)]
Subgraph {
/// Seed symbol names (at least one required).
#[arg(required = true, help_heading = headings::SEARCH_INPUT, display_order = 10)]
symbols: Vec<String>,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 20)]
path: Option<String>,
/// Maximum traversal depth from seeds (default: 2).
#[arg(long, short = 'd', default_value = "2", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
depth: usize,
/// Maximum nodes to include (default: 50).
#[arg(long, short = 'n', default_value = "50", help_heading = headings::GRAPH_FILTERING, display_order = 20)]
max_nodes: usize,
/// Exclude callers (incoming edges).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 30)]
no_callers: bool,
/// Exclude callees (outgoing edges).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 40)]
no_callees: bool,
/// Include import relationships.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 50)]
include_imports: bool,
},
/// Analyze what would break if a symbol changes
///
/// Performs reverse dependency analysis to find all symbols
/// that directly or indirectly depend on the target.
///
/// Examples:
/// sqry impact authenticate # Impact of changing authenticate
/// sqry impact -d 5 `MyClass` # Deep analysis (5 levels)
/// sqry impact --direct-only func # Only direct dependents
/// sqry impact --show-files func # Show affected files
#[command(alias = "imp", display_order = 24, verbatim_doc_comment)]
Impact {
/// Symbol to analyze.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
symbol: String,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 20)]
path: Option<String>,
/// Maximum analysis depth (default: 3).
#[arg(long, short = 'd', default_value = "3", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
depth: usize,
/// Maximum results to return (default: 100).
#[arg(long, short = 'l', default_value = "100", help_heading = headings::GRAPH_FILTERING, display_order = 20)]
limit: usize,
/// Only show direct dependents (depth 1).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 30)]
direct_only: bool,
/// Show list of affected files.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
show_files: bool,
},
/// Compare semantic changes between git refs
///
/// Analyzes AST differences between two git refs to detect added, removed,
/// modified, and renamed symbols. Provides structured output showing what
/// changed semantically, not just textually.
///
/// Examples:
/// sqry diff main HEAD # Compare branches
/// sqry diff v1.0.0 v2.0.0 --json # Release comparison
/// sqry diff HEAD~5 HEAD --kind function # Functions only
/// sqry diff main feature --change-type added # New symbols only
#[command(alias = "sdiff", display_order = 25, verbatim_doc_comment)]
Diff {
/// Base git ref (commit, branch, or tag).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
base: String,
/// Target git ref (commit, branch, or tag).
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 20)]
target: String,
/// Path to git repository (defaults to current directory).
///
/// Can be the repository root or any path within it - sqry will walk up
/// the directory tree to find the .git directory.
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 30)]
path: Option<String>,
/// Maximum total results to display (default: 100).
#[arg(long, short = 'l', default_value = "100", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
limit: usize,
/// Filter by symbol kinds (comma-separated).
#[arg(long, short = 'k', help_heading = headings::GRAPH_FILTERING, display_order = 20)]
kind: Option<String>,
/// Filter by change types (comma-separated).
///
/// Valid values: `added`, `removed`, `modified`, `renamed`, `signature_changed`
///
/// Example: --change-type added,modified
#[arg(long, short = 'c', help_heading = headings::GRAPH_FILTERING, display_order = 30)]
change_type: Option<String>,
},
/// Hierarchical semantic search (RAG-optimized)
///
/// Performs semantic search with results grouped by file and container,
/// optimized for retrieval-augmented generation (RAG) workflows.
///
/// Examples:
/// sqry hier "kind:function" # All functions, grouped
/// sqry hier "auth" --max-files 10 # Limit file groups
/// sqry hier --kind function "test" # Filter by kind
/// sqry hier --context 5 "validate" # More context lines
#[command(display_order = 4, verbatim_doc_comment)]
Hier {
/// Search query.
#[arg(help_heading = headings::SEARCH_INPUT, display_order = 10)]
query: String,
/// Search path (defaults to current directory).
#[arg(long, help_heading = headings::SEARCH_INPUT, display_order = 20)]
path: Option<String>,
/// Maximum symbols before grouping (default: 200).
#[arg(long, short = 'l', default_value = "200", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
limit: usize,
/// Maximum files in output (default: 20).
#[arg(long, default_value = "20", help_heading = headings::GRAPH_FILTERING, display_order = 20)]
max_files: usize,
/// Context lines around matches (default: 3).
#[arg(long, short = 'c', default_value = "3", help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
context: usize,
/// Filter by symbol kinds (comma-separated).
#[arg(long, short = 'k', help_heading = headings::GRAPH_FILTERING, display_order = 30)]
kind: Option<String>,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 40)]
lang: Option<String>,
},
/// Configure MCP server integration for AI coding tools
///
/// Auto-detect and configure sqry MCP for Claude Code, Codex, and Gemini CLI.
/// The setup command writes tool-specific configuration so AI coding assistants
/// can use sqry's semantic code search capabilities.
///
/// Examples:
/// sqry mcp setup # Auto-configure all detected tools
/// sqry mcp setup --tool claude # Configure Claude Code only
/// sqry mcp setup --scope global --dry-run # Preview global config changes
/// sqry mcp status # Show current MCP configuration
/// sqry mcp status --json # Machine-readable status
#[command(display_order = 51, verbatim_doc_comment)]
Mcp {
#[command(subcommand)]
command: McpCommand,
},
/// Manage the sqry daemon (sqryd).
///
/// The daemon provides persistent, shared code-graph indexing for
/// faster queries across concurrent editor sessions.
///
/// Examples:
/// sqry daemon start # Start the daemon in the background
/// sqry daemon stop # Stop the running daemon
/// sqry daemon status # Show daemon health and workspaces
/// sqry daemon status --json # Machine-readable status
/// sqry daemon logs --follow # Tail the daemon log
#[command(display_order = 35, verbatim_doc_comment)]
Daemon {
#[command(subcommand)]
action: Box<DaemonAction>,
},
}
/// Daemon management subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum DaemonAction {
/// Start the sqry daemon in the background.
///
/// Locates the `sqryd` binary (sibling to `sqry` or on PATH),
/// spawns it with `sqryd start --detach`, and waits for readiness.
Start {
/// Path to the sqryd binary (default: auto-detect).
#[arg(long)]
sqryd_path: Option<PathBuf>,
/// Maximum seconds to wait for daemon readiness.
#[arg(long, default_value_t = 10)]
timeout: u64,
},
/// Stop the running sqry daemon.
Stop {
/// Maximum seconds to wait for graceful shutdown.
#[arg(long, default_value_t = 15)]
timeout: u64,
},
/// Show daemon status (version, uptime, memory, workspaces).
Status {
/// Emit machine-readable JSON instead of human-readable output.
#[arg(long)]
json: bool,
},
/// Tail the daemon log file.
Logs {
/// Number of lines to show from the end of the log.
#[arg(long, short = 'n', default_value_t = 50)]
lines: usize,
/// Follow the log file for new output (like `tail -f`).
#[arg(long, short = 'f')]
follow: bool,
},
/// Load a workspace into the running daemon.
///
/// Connects to the daemon and sends a `daemon/load` request with the
/// canonicalized path. The daemon's `WorkspaceManager` indexes the
/// workspace, caches the graph in memory, and starts watching for
/// file changes to rebuild incrementally.
Load {
/// Workspace root directory to load.
path: PathBuf,
},
/// Trigger an in-place graph rebuild for a loaded workspace.
///
/// Sends a `daemon/rebuild` request to the running daemon for the specified
/// workspace root. Once wired (CLI_REBUILD_3), the daemon will re-index the
/// workspace and replace the in-memory graph atomically on completion.
///
/// Use `--force` to discard any incremental state and perform a full rebuild
/// from scratch (equivalent to dropping and re-loading the workspace).
///
/// The command will wait up to `--timeout` seconds for the rebuild to finish
/// and report the result as human-readable text or, with `--json`, as a
/// machine-readable JSON object.
#[command(verbatim_doc_comment)]
Rebuild {
/// Workspace root directory to rebuild.
path: PathBuf,
/// Force a full rebuild from scratch, discarding incremental state.
#[arg(long)]
force: bool,
/// Maximum seconds to wait for the rebuild to complete.
/// Default is 1800 seconds (30 minutes). Pass 0 to fire-and-forget.
#[arg(long, default_value_t = 1800)]
timeout: u64,
/// Emit machine-readable JSON output instead of human-readable text.
#[arg(long)]
json: bool,
},
}
/// MCP server integration subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum McpCommand {
/// Auto-configure sqry MCP for detected AI tools (Claude Code, Codex, Gemini)
///
/// Detects installed AI coding tools and writes configuration entries
/// pointing to the sqry-mcp binary. Uses tool-appropriate scoping:
/// - Claude Code: per-project entries with pinned workspace root (default)
/// - Codex/Gemini: global entries using CWD-based workspace discovery
///
/// Note: Codex and Gemini only support global MCP configs.
/// They rely on being launched from within a project directory
/// for sqry-mcp's CWD discovery to resolve the correct workspace.
Setup {
/// Target tool(s) to configure.
#[arg(long, value_enum, default_value = "all")]
tool: ToolTarget,
/// Configuration scope.
///
/// - auto: project scope for Claude (when inside a repo), global for Codex/Gemini
/// - project: per-project Claude entry with pinned workspace root
/// - global: global entries for all tools (CWD-dependent for workspace resolution)
///
/// Note: For Codex and Gemini, --scope project and --scope global behave
/// identically because these tools only support global MCP configs.
#[arg(long, value_enum, default_value = "auto")]
scope: SetupScope,
/// Explicit workspace root path (overrides auto-detection).
///
/// Only applicable for Claude Code project scope. Rejected for
/// Codex/Gemini because setting a workspace root in their global
/// config would pin to one repo and break multi-repo workflows.
#[arg(long)]
workspace_root: Option<PathBuf>,
/// Overwrite existing sqry configuration.
#[arg(long)]
force: bool,
/// Preview changes without writing.
#[arg(long)]
dry_run: bool,
/// Skip creating .bak backup files.
#[arg(long)]
no_backup: bool,
},
/// Show current MCP configuration status across all tools
///
/// Reports the sqry-mcp binary location and configuration state
/// for each supported AI tool, including scope, workspace root,
/// and any detected issues (shim usage, drift, missing config).
Status {
/// Output as JSON for programmatic use.
#[arg(long)]
json: bool,
},
}
/// Target AI tool(s) for MCP configuration
#[derive(Debug, Clone, ValueEnum)]
pub enum ToolTarget {
/// Configure Claude Code only
Claude,
/// Configure Codex only
Codex,
/// Configure Gemini CLI only
Gemini,
/// Configure all detected tools (default)
All,
}
/// Configuration scope for MCP setup
#[derive(Debug, Clone, ValueEnum)]
pub enum SetupScope {
/// Per-project for Claude, global for Codex/Gemini (auto-detect)
Auto,
/// Per-project entries with pinned workspace root
Project,
/// Global entries (CWD-dependent workspace resolution)
Global,
}
/// Graph-based query operations
#[derive(Subcommand, Debug, Clone)]
pub enum GraphOperation {
/// Find shortest path between two symbols
///
/// Traces the shortest execution path from one symbol to another,
/// following Call, `HTTPRequest`, and `FFICall` edges.
///
/// Example: sqry graph trace-path main processData
TracePath {
/// Source symbol name (e.g., "main", "User.authenticate").
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
from: String,
/// Target symbol name.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 20)]
to: String,
/// Filter by languages (comma-separated, e.g., "javascript,python").
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
languages: Option<String>,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
full_paths: bool,
},
/// Calculate maximum call chain depth from a symbol
///
/// Computes the longest call chain starting from the given symbol,
/// useful for complexity analysis and recursion detection.
///
/// Example: sqry graph call-chain-depth main
CallChainDepth {
/// Symbol name to analyze.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
languages: Option<String>,
/// Show the actual call chain, not just the depth.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
show_chain: bool,
},
/// Show transitive dependencies for a module
///
/// Analyzes all imports transitively to build a complete dependency tree,
/// including circular dependency detection.
///
/// Example: sqry graph dependency-tree src/main.js
#[command(alias = "deps")]
DependencyTree {
/// Module path or name.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
module: String,
/// Maximum depth to traverse (default: unlimited).
#[arg(long, help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 10)]
max_depth: Option<usize>,
/// Show circular dependencies only.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
cycles_only: bool,
},
/// List all cross-language relationships
///
/// Finds edges connecting symbols in different programming languages,
/// such as TypeScript→JavaScript imports, Python→C FFI calls, SQL table
/// access, Dart `MethodChannel` invocations, and Flutter widget hierarchies.
///
/// Supported languages for --from-lang/--to-lang:
/// js, ts, py, cpp, c, csharp (cs), java, go, ruby, php,
/// swift, kotlin, scala, sql, dart, lua, perl, shell (bash),
/// groovy, http
///
/// Examples:
/// sqry graph cross-language --from-lang dart --edge-type `channel_invoke`
/// sqry graph cross-language --from-lang sql --edge-type `table_read`
/// sqry graph cross-language --edge-type `widget_child`
#[command(verbatim_doc_comment)]
CrossLanguage {
/// Filter by source language.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
from_lang: Option<String>,
/// Filter by target language.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 20)]
to_lang: Option<String>,
/// Edge type filter.
///
/// Supported values:
/// call, import, http, ffi,
/// `table_read`, `table_write`, `triggered_by`,
/// `channel_invoke`, `widget_child`
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 30)]
edge_type: Option<String>,
/// Minimum confidence threshold (0.0-1.0).
#[arg(long, default_value = "0.0", help_heading = headings::GRAPH_FILTERING, display_order = 40)]
min_confidence: f64,
},
/// List unified graph nodes
///
/// Enumerates nodes from the unified graph snapshot and applies filters.
/// Useful for inspecting graph coverage and metadata details.
Nodes {
/// Filter by node kind(s) (comma-separated: function,method,macro).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
kind: Option<String>,
/// Filter by language(s) (comma-separated: rust,python).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 20)]
languages: Option<String>,
/// Filter by file path substring (case-insensitive).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 30)]
file: Option<String>,
/// Filter by name substring (case-sensitive).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 40)]
name: Option<String>,
/// Filter by qualified name substring (case-sensitive).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 50)]
qualified_name: Option<String>,
/// Maximum results (default: 1000, max: 10000; use 0 for default).
#[arg(long, default_value = "1000", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
limit: usize,
/// Skip N results.
#[arg(long, default_value = "0", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
offset: usize,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 30)]
full_paths: bool,
},
/// List unified graph edges
///
/// Enumerates edges from the unified graph snapshot and applies filters.
/// Useful for inspecting relationships and cross-cutting metadata.
Edges {
/// Filter by edge kind tag(s) (comma-separated: calls,imports).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
kind: Option<String>,
/// Filter by source label substring (case-sensitive).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 20)]
from: Option<String>,
/// Filter by target label substring (case-sensitive).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 30)]
to: Option<String>,
/// Filter by source language.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 40)]
from_lang: Option<String>,
/// Filter by target language.
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 50)]
to_lang: Option<String>,
/// Filter by file path substring (case-insensitive, source file only).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 60)]
file: Option<String>,
/// Maximum results (default: 1000, max: 10000; use 0 for default).
#[arg(long, default_value = "1000", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
limit: usize,
/// Skip N results.
#[arg(long, default_value = "0", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
offset: usize,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 30)]
full_paths: bool,
},
/// Show graph statistics and summary
///
/// Displays overall graph metrics including node counts by language,
/// edge counts by type, and cross-language relationship statistics.
///
/// Example: sqry graph stats
Stats {
/// Show detailed breakdown by file.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
by_file: bool,
/// Show detailed breakdown by language.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
by_language: bool,
},
/// Show unified graph snapshot status
///
/// Reports on the state of the unified graph snapshot stored in
/// `.sqry/graph/` directory. Displays build timestamp, node/edge counts,
/// and snapshot age.
///
/// Example: sqry graph status
Status,
/// Show Phase 1 fact-layer provenance for a symbol
///
/// Prints the snapshot's fact epoch, node provenance (first/last seen
/// epoch, content hash), file provenance, and an edge-provenance summary
/// for the matched symbol. This is the end-to-end proof that the V8
/// save → load → accessor → CLI path is wired.
///
/// Example: sqry graph provenance `my_function`
#[command(alias = "prov")]
Provenance {
/// Symbol name to inspect (qualified or unqualified).
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Output as JSON.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
json: bool,
},
/// Resolve a symbol through the Phase 2 binding plane
///
/// Loads the snapshot, constructs a BindingPlane facade, runs
/// BindingPlane::resolve() for the given symbol, and prints the outcome
/// along with the list of matched bindings. This is the end-to-end proof
/// point for the Phase 2 binding plane (FR9).
///
/// With `--explain` the ordered witness step trace is printed below the
/// binding list, showing every bucket probe, candidate considered, and
/// the terminal Chose/Ambiguous/Unresolved step.
///
/// Example: sqry graph resolve my_function
/// Example: sqry graph resolve my_function --explain
/// Example: sqry graph resolve my_function --explain --json
#[command(alias = "res")]
Resolve {
/// Symbol name to resolve (qualified or unqualified).
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Print the ordered witness step trace (bucket probes, candidate
/// evaluations, and the terminal Chose/Ambiguous/Unresolved step).
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
explain: bool,
/// Emit a stable JSON document instead of human-readable text.
/// The JSON shape (symbol/outcome/bindings/explain) is the documented
/// stable external contract for scripting and tool integration.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
json: bool,
},
/// Detect circular dependencies in the codebase
///
/// Finds all cycles in the call and import graphs, which can indicate
/// potential design issues or circular dependency problems.
///
/// Example: sqry graph cycles
#[command(alias = "cyc")]
Cycles {
/// Minimum cycle length to report (default: 2).
#[arg(long, default_value = "2", help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 10)]
min_length: usize,
/// Maximum cycle length to report (default: unlimited).
#[arg(long, help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 20)]
max_length: Option<usize>,
/// Only analyze import edges (ignore calls).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
imports_only: bool,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 20)]
languages: Option<String>,
},
/// Calculate code complexity metrics
///
/// Analyzes cyclomatic complexity, call graph depth, and other
/// complexity metrics for functions and modules.
///
/// Example: sqry graph complexity
#[command(alias = "cx")]
Complexity {
/// Target symbol or module (default: analyze all).
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
target: Option<String>,
/// Sort by complexity score.
#[arg(long = "sort-complexity", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
sort_complexity: bool,
/// Show only items above this complexity threshold.
#[arg(long, default_value = "0", help_heading = headings::GRAPH_FILTERING, display_order = 10)]
min_complexity: usize,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 20)]
languages: Option<String>,
},
/// Find direct callers of a symbol
///
/// Lists all symbols that directly call the specified function, method,
/// or other callable. Useful for understanding symbol usage and impact analysis.
///
/// Example: sqry graph direct-callers authenticate
#[command(alias = "callers")]
DirectCallers {
/// Symbol name to find callers for.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Maximum results (default: 100).
#[arg(long, short = 'l', default_value = "100", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
limit: usize,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
languages: Option<String>,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
full_paths: bool,
},
/// Find direct callees of a symbol
///
/// Lists all symbols that are directly called by the specified function
/// or method. Useful for understanding dependencies and refactoring scope.
///
/// Example: sqry graph direct-callees processData
#[command(alias = "callees")]
DirectCallees {
/// Symbol name to find callees for.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Maximum results (default: 100).
#[arg(long, short = 'l', default_value = "100", help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
limit: usize,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
languages: Option<String>,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 20)]
full_paths: bool,
},
/// Show call hierarchy for a symbol
///
/// Displays incoming and/or outgoing call relationships in a tree format.
/// Useful for understanding code flow and impact of changes.
///
/// Example: sqry graph call-hierarchy main --depth 3
#[command(alias = "ch")]
CallHierarchy {
/// Symbol name to show hierarchy for.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Maximum depth to traverse (default: 3).
#[arg(long, short = 'd', default_value = "3", help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 10)]
depth: usize,
/// Direction: incoming, outgoing, or both (default: both).
#[arg(long, default_value = "both", help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 20)]
direction: String,
/// Filter by languages (comma-separated).
#[arg(long, help_heading = headings::GRAPH_FILTERING, display_order = 10)]
languages: Option<String>,
/// Show full file paths in output.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
full_paths: bool,
},
/// Check if a symbol is in a cycle
///
/// Determines whether a specific symbol participates in any circular
/// dependency chains. Can optionally show the cycle path.
///
/// Example: sqry graph is-in-cycle `UserService` --show-cycle
#[command(alias = "incycle")]
IsInCycle {
/// Symbol name to check.
#[arg(help_heading = headings::GRAPH_ANALYSIS_INPUT, display_order = 10)]
symbol: String,
/// Cycle type to check: calls, imports, or all (default: calls).
#[arg(long, default_value = "calls", help_heading = headings::GRAPH_ANALYSIS_OPTIONS, display_order = 10)]
cycle_type: String,
/// Show the full cycle path if found.
#[arg(long, help_heading = headings::GRAPH_OUTPUT_OPTIONS, display_order = 10)]
show_cycle: bool,
},
}
/// Output format choices for `sqry batch`.
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)]
pub enum BatchFormat {
/// Human-readable text output (default)
Text,
/// Aggregated JSON output containing all query results
Json,
/// Newline-delimited JSON objects (one per query)
Jsonl,
/// Comma-separated summary per query
Csv,
}
/// Cache management actions
#[derive(Subcommand, Debug, Clone)]
pub enum CacheAction {
/// Show cache statistics
///
/// Display hit rate, size, and entry count for the AST cache.
Stats {
/// Path to check cache for (defaults to current directory).
#[arg(help_heading = headings::CACHE_INPUT, display_order = 10)]
path: Option<String>,
},
/// Clear the cache
///
/// Remove all cached AST data. Next queries will re-parse files.
Clear {
/// Path to clear cache for (defaults to current directory).
#[arg(help_heading = headings::CACHE_INPUT, display_order = 10)]
path: Option<String>,
/// Confirm deletion (required for safety).
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 10)]
confirm: bool,
},
/// Prune the cache
///
/// Remove old or excessive cache entries to reclaim disk space.
/// Supports time-based (--days) and size-based (--size) retention policies.
Prune {
/// Target cache directory (defaults to user cache dir).
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 10)]
path: Option<String>,
/// Remove entries older than N days.
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 20)]
days: Option<u64>,
/// Cap cache to maximum size (e.g., "1GB", "500MB").
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 30)]
size: Option<String>,
/// Preview deletions without removing files.
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 10)]
dry_run: bool,
},
/// Generate or refresh the macro expansion cache
///
/// Runs `cargo expand` to generate expanded macro output, then caches
/// the results for use during indexing. Requires `cargo-expand` installed.
///
/// # Security
///
/// This executes build scripts and proc macros. Only use on trusted codebases.
Expand {
/// Force regeneration even if cache is fresh.
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 40)]
refresh: bool,
/// Only expand a specific crate (default: all workspace crates).
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 50)]
crate_name: Option<String>,
/// Show what would be expanded without actually running cargo expand.
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 20)]
dry_run: bool,
/// Cache output directory (default: .sqry/expand-cache/).
#[arg(long, help_heading = headings::CACHE_INPUT, display_order = 60)]
output: Option<PathBuf>,
},
}
/// Config action subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum ConfigAction {
/// Initialize config with defaults
///
/// Creates `.sqry/graph/config/config.json` with default settings.
/// Use --force to overwrite existing config.
///
/// Examples:
/// sqry config init
/// sqry config init --force
#[command(verbatim_doc_comment)]
Init {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Overwrite existing config.
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 20)]
force: bool,
},
/// Show effective config
///
/// Displays the complete config with source annotations.
/// Use --key to show a single value.
///
/// Examples:
/// sqry config show
/// sqry config show --json
/// sqry config show --key `limits.max_results`
#[command(verbatim_doc_comment)]
Show {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Output as JSON.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
json: bool,
/// Show only this config key (e.g., `limits.max_results`).
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 20)]
key: Option<String>,
},
/// Set a config value
///
/// Updates a config key and persists to disk.
/// Shows a diff before applying (use --yes to skip).
///
/// Examples:
/// sqry config set `limits.max_results` 10000
/// sqry config set `locking.stale_takeover_policy` warn
/// sqry config set `output.page_size` 100 --yes
#[command(verbatim_doc_comment)]
Set {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Config key (e.g., `limits.max_results`).
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 20)]
key: String,
/// New value.
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 30)]
value: String,
/// Skip confirmation prompt.
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 40)]
yes: bool,
},
/// Get a config value
///
/// Retrieves a single config value.
///
/// Examples:
/// sqry config get `limits.max_results`
/// sqry config get `locking.stale_takeover_policy`
#[command(verbatim_doc_comment)]
Get {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Config key (e.g., `limits.max_results`).
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 20)]
key: String,
},
/// Validate config file
///
/// Checks config syntax and schema validity.
///
/// Examples:
/// sqry config validate
#[command(verbatim_doc_comment)]
Validate {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
},
/// Manage query aliases
#[command(subcommand)]
Alias(ConfigAliasAction),
}
/// Config alias subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum ConfigAliasAction {
/// Create or update an alias
///
/// Examples:
/// sqry config alias set my-funcs "kind:function"
/// sqry config alias set my-funcs "kind:function" --description "All functions"
#[command(verbatim_doc_comment)]
Set {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Alias name.
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 20)]
name: String,
/// Query expression.
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 30)]
query: String,
/// Optional description.
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 40)]
description: Option<String>,
},
/// List all aliases
///
/// Examples:
/// sqry config alias list
/// sqry config alias list --json
#[command(verbatim_doc_comment)]
List {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Output as JSON.
#[arg(long, help_heading = headings::OUTPUT_CONTROL, display_order = 10)]
json: bool,
},
/// Remove an alias
///
/// Examples:
/// sqry config alias remove my-funcs
#[command(verbatim_doc_comment)]
Remove {
/// Project root path (defaults to current directory).
// Path defaults to current directory if not specified
#[arg(long, help_heading = headings::CONFIG_INPUT, display_order = 5)]
path: Option<String>,
/// Alias name to remove.
#[arg(help_heading = headings::CONFIG_INPUT, display_order = 20)]
name: String,
},
}
/// Visualize code relationships from relation queries.
///
/// Examples:
/// sqry visualize "callers:main" --format mermaid
/// sqry visualize "imports:std" --format graphviz --output-file deps.dot
/// sqry visualize "callees:process" --depth 5 --max-nodes 200
#[derive(Debug, Args, Clone)]
#[command(
about = "Visualize code relationships as diagrams",
long_about = "Visualize code relationships as diagrams.\n\n\
Examples:\n sqry visualize \"callers:main\" --format mermaid\n \
sqry visualize \"imports:std\" --format graphviz --output-file deps.dot\n \
sqry visualize \"callees:process\" --depth 5 --max-nodes 200",
after_help = "Examples:\n sqry visualize \"callers:main\" --format mermaid\n \
sqry visualize \"imports:std\" --format graphviz --output-file deps.dot\n \
sqry visualize \"callees:process\" --depth 5 --max-nodes 200"
)]
pub struct VisualizeCommand {
/// Relation query (e.g., callers:main, callees:helper).
#[arg(help_heading = headings::VISUALIZATION_INPUT, display_order = 10)]
pub query: String,
/// Target path (defaults to CLI positional path).
#[arg(long, help_heading = headings::VISUALIZATION_INPUT, display_order = 20)]
pub path: Option<String>,
/// Diagram syntax format (mermaid, graphviz, d2).
///
/// Specifies the diagram language/syntax to generate.
/// Output will be plain text in the chosen format.
#[arg(long, short = 'f', value_enum, default_value = "mermaid", help_heading = headings::DIAGRAM_CONFIGURATION, display_order = 10)]
pub format: DiagramFormatArg,
/// Layout direction for the graph.
#[arg(long, value_enum, default_value = "top-down", help_heading = headings::DIAGRAM_CONFIGURATION, display_order = 20)]
pub direction: DirectionArg,
/// File path to save the output (stdout when omitted).
#[arg(long, help_heading = headings::DIAGRAM_CONFIGURATION, display_order = 30)]
pub output_file: Option<PathBuf>,
/// Maximum traversal depth for graph expansion.
#[arg(long, short = 'd', default_value_t = 3, help_heading = headings::TRAVERSAL_CONTROL, display_order = 10)]
pub depth: usize,
/// Maximum number of nodes to include in the diagram (1-500).
#[arg(long, default_value_t = 100, help_heading = headings::TRAVERSAL_CONTROL, display_order = 20)]
pub max_nodes: usize,
}
/// Supported diagram text formats.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum DiagramFormatArg {
Mermaid,
Graphviz,
D2,
}
/// Diagram layout direction.
#[derive(Debug, Clone, Copy, ValueEnum)]
#[value(rename_all = "kebab-case")]
pub enum DirectionArg {
TopDown,
BottomUp,
LeftRight,
RightLeft,
}
/// Workspace management subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum WorkspaceCommand {
/// Initialise a new workspace registry
Init {
/// Directory that will contain the workspace registry.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Preferred discovery mode for initial scans.
#[arg(long, value_enum, default_value_t = WorkspaceDiscoveryMode::IndexFiles, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 10)]
mode: WorkspaceDiscoveryMode,
/// Friendly workspace name stored in the registry metadata.
#[arg(long, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 20)]
name: Option<String>,
},
/// Scan for repositories inside the workspace root
Scan {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Discovery mode to use when scanning for repositories.
#[arg(long, value_enum, default_value_t = WorkspaceDiscoveryMode::IndexFiles, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 10)]
mode: WorkspaceDiscoveryMode,
/// Remove entries whose indexes are no longer present.
#[arg(long, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 20)]
prune_stale: bool,
},
/// Add a repository to the workspace manually
Add {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Path to the repository root (must contain .sqry-index).
#[arg(value_name = "REPO", help_heading = headings::WORKSPACE_INPUT, display_order = 20)]
repo: String,
/// Optional friendly name for the repository.
#[arg(long, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 10)]
name: Option<String>,
},
/// Remove a repository from the workspace
Remove {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Repository identifier (workspace-relative path).
#[arg(value_name = "REPO_ID", help_heading = headings::WORKSPACE_INPUT, display_order = 20)]
repo_id: String,
},
/// Run a workspace-level query across registered repositories
Query {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Query expression (supports repo: predicates).
#[arg(value_name = "QUERY", help_heading = headings::WORKSPACE_INPUT, display_order = 20)]
query: String,
/// Override parallel query threads.
#[arg(long, help_heading = headings::PERFORMANCE_TUNING, display_order = 10)]
threads: Option<usize>,
},
/// Emit aggregate statistics for the workspace
Stats {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
},
/// Print the aggregate index status for every source root in the workspace
Status {
/// Workspace root containing the .sqry-workspace file.
#[arg(value_name = "WORKSPACE", help_heading = headings::WORKSPACE_INPUT, display_order = 10)]
workspace: String,
/// Emit machine-readable JSON instead of the human-friendly summary.
#[arg(long, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 10)]
json: bool,
/// Bypass the 60-second aggregate-status cache and force a recompute.
#[arg(long, help_heading = headings::WORKSPACE_CONFIGURATION, display_order = 20)]
no_cache: bool,
},
}
/// CLI discovery modes converted to workspace `DiscoveryMode` values
#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum WorkspaceDiscoveryMode {
#[value(name = "index-files", alias = "index")]
IndexFiles,
#[value(name = "git-roots", alias = "git")]
GitRoots,
}
/// Alias management subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum AliasAction {
/// List all saved aliases
///
/// Shows aliases from both global (~/.config/sqry/) and local (.sqry-index.user)
/// storage. Local aliases take precedence over global ones with the same name.
///
/// Examples:
/// sqry alias list # List all aliases
/// sqry alias list --local # Only local aliases
/// sqry alias list --global # Only global aliases
/// sqry alias list --json # JSON output
#[command(verbatim_doc_comment)]
List {
/// Show only local aliases (project-specific).
#[arg(long, conflicts_with = "global", help_heading = headings::ALIAS_CONFIGURATION, display_order = 10)]
local: bool,
/// Show only global aliases (cross-project).
#[arg(long, conflicts_with = "local", help_heading = headings::ALIAS_CONFIGURATION, display_order = 20)]
global: bool,
},
/// Show details of a specific alias
///
/// Displays the command, arguments, description, and storage location
/// for the named alias.
///
/// Example: sqry alias show my-funcs
Show {
/// Name of the alias to show.
#[arg(value_name = "NAME", help_heading = headings::ALIAS_INPUT, display_order = 10)]
name: String,
},
/// Delete a saved alias
///
/// Removes an alias from storage. If the alias exists in both local
/// and global storage, specify --local or --global to delete from
/// a specific location.
///
/// Examples:
/// sqry alias delete my-funcs # Delete (prefers local)
/// sqry alias delete my-funcs --global # Delete from global only
/// sqry alias delete my-funcs --force # Skip confirmation
#[command(verbatim_doc_comment)]
Delete {
/// Name of the alias to delete.
#[arg(value_name = "NAME", help_heading = headings::ALIAS_INPUT, display_order = 10)]
name: String,
/// Delete from local storage only.
#[arg(long, conflicts_with = "global", help_heading = headings::ALIAS_CONFIGURATION, display_order = 10)]
local: bool,
/// Delete from global storage only.
#[arg(long, conflicts_with = "local", help_heading = headings::ALIAS_CONFIGURATION, display_order = 20)]
global: bool,
/// Skip confirmation prompt.
#[arg(long, short = 'f', help_heading = headings::SAFETY_CONTROL, display_order = 10)]
force: bool,
},
/// Rename an existing alias
///
/// Changes the name of an alias while preserving its command and arguments.
/// The alias is renamed in the same storage location where it was found.
///
/// Example: sqry alias rename old-name new-name
Rename {
/// Current name of the alias.
#[arg(value_name = "OLD_NAME", help_heading = headings::ALIAS_INPUT, display_order = 10)]
old_name: String,
/// New name for the alias.
#[arg(value_name = "NEW_NAME", help_heading = headings::ALIAS_INPUT, display_order = 20)]
new_name: String,
/// Rename in local storage only.
#[arg(long, conflicts_with = "global", help_heading = headings::ALIAS_CONFIGURATION, display_order = 10)]
local: bool,
/// Rename in global storage only.
#[arg(long, conflicts_with = "local", help_heading = headings::ALIAS_CONFIGURATION, display_order = 20)]
global: bool,
},
/// Export aliases to a JSON file
///
/// Exports aliases for backup or sharing. The export format is compatible
/// with the import command for easy restoration.
///
/// Examples:
/// sqry alias export aliases.json # Export all
/// sqry alias export aliases.json --local # Export local only
#[command(verbatim_doc_comment)]
Export {
/// Output file path (use - for stdout).
#[arg(value_name = "FILE", help_heading = headings::ALIAS_INPUT, display_order = 10)]
file: String,
/// Export only local aliases.
#[arg(long, conflicts_with = "global", help_heading = headings::ALIAS_CONFIGURATION, display_order = 10)]
local: bool,
/// Export only global aliases.
#[arg(long, conflicts_with = "local", help_heading = headings::ALIAS_CONFIGURATION, display_order = 20)]
global: bool,
},
/// Import aliases from a JSON file
///
/// Imports aliases from an export file. Handles conflicts with existing
/// aliases using the specified strategy.
///
/// Examples:
/// sqry alias import aliases.json # Import to local
/// sqry alias import aliases.json --global # Import to global
/// sqry alias import aliases.json --on-conflict skip
#[command(verbatim_doc_comment)]
Import {
/// Input file path (use - for stdin).
#[arg(value_name = "FILE", help_heading = headings::ALIAS_INPUT, display_order = 10)]
file: String,
/// Import to local storage (default).
#[arg(long, conflicts_with = "global", help_heading = headings::ALIAS_CONFIGURATION, display_order = 10)]
local: bool,
/// Import to global storage.
#[arg(long, conflicts_with = "local", help_heading = headings::ALIAS_CONFIGURATION, display_order = 20)]
global: bool,
/// How to handle conflicts with existing aliases.
#[arg(long, value_enum, default_value = "error", help_heading = headings::ALIAS_CONFIGURATION, display_order = 30)]
on_conflict: ImportConflictArg,
/// Preview import without making changes.
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 10)]
dry_run: bool,
},
}
/// History management subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum HistoryAction {
/// List recent query history
///
/// Shows recently executed queries with their timestamps, commands,
/// and execution status.
///
/// Examples:
/// sqry history list # List recent (default 100)
/// sqry history list --limit 50 # Last 50 entries
/// sqry history list --json # JSON output
#[command(verbatim_doc_comment)]
List {
/// Maximum number of entries to show.
#[arg(long, short = 'n', default_value = "100", help_heading = headings::HISTORY_CONFIGURATION, display_order = 10)]
limit: usize,
},
/// Search query history
///
/// Searches history entries by pattern. The pattern is matched
/// against command names and arguments.
///
/// Examples:
/// sqry history search "function" # Find queries with "function"
/// sqry history search "callers:" # Find caller queries
#[command(verbatim_doc_comment)]
Search {
/// Search pattern (matched against command and args).
#[arg(value_name = "PATTERN", help_heading = headings::HISTORY_INPUT, display_order = 10)]
pattern: String,
/// Maximum number of results.
#[arg(long, short = 'n', default_value = "100", help_heading = headings::HISTORY_CONFIGURATION, display_order = 10)]
limit: usize,
},
/// Clear query history
///
/// Removes history entries. Can clear all entries or only those
/// older than a specified duration.
///
/// Examples:
/// sqry history clear # Clear all (requires --confirm)
/// sqry history clear --older 30d # Clear entries older than 30 days
/// sqry history clear --older 1w # Clear entries older than 1 week
#[command(verbatim_doc_comment)]
Clear {
/// Remove only entries older than this duration (e.g., 30d, 1w, 24h).
#[arg(long, value_name = "DURATION", help_heading = headings::HISTORY_CONFIGURATION, display_order = 10)]
older: Option<String>,
/// Confirm clearing history (required when clearing all).
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 10)]
confirm: bool,
},
/// Show history statistics
///
/// Displays aggregate statistics about query history including
/// total entries, most used commands, and storage information.
Stats,
}
/// Insights management subcommands
#[derive(Subcommand, Debug, Clone)]
pub enum InsightsAction {
/// Show usage summary for a time period
///
/// Displays aggregated usage statistics including query counts,
/// timing metrics, and workflow patterns.
///
/// Examples:
/// sqry insights show # Current week
/// sqry insights show --week 2025-W50 # Specific week
/// sqry insights show --json # JSON output
#[command(verbatim_doc_comment)]
Show {
/// ISO week to display (e.g., 2025-W50). Defaults to current week.
#[arg(long, short = 'w', value_name = "WEEK", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 10)]
week: Option<String>,
},
/// Show or modify uses configuration
///
/// View the current configuration or change settings like
/// enabling/disabling uses capture.
///
/// Examples:
/// sqry insights config # Show current config
/// sqry insights config --enable # Enable uses capture
/// sqry insights config --disable # Disable uses capture
/// sqry insights config --retention 90 # Set retention to 90 days
#[command(verbatim_doc_comment)]
Config {
/// Enable uses capture.
#[arg(long, conflicts_with = "disable", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 10)]
enable: bool,
/// Disable uses capture.
#[arg(long, conflicts_with = "enable", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 20)]
disable: bool,
/// Set retention period in days.
#[arg(long, value_name = "DAYS", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 30)]
retention: Option<u32>,
},
/// Show storage status and statistics
///
/// Displays information about the uses storage including
/// total size, file count, and date range of stored events.
///
/// Example:
/// sqry insights status
Status,
/// Clean up old event data
///
/// Removes event logs older than the specified duration.
/// Uses the configured retention period if --older is not specified.
///
/// Examples:
/// sqry insights prune # Use configured retention
/// sqry insights prune --older 90d # Prune older than 90 days
/// sqry insights prune --dry-run # Preview without deleting
#[command(verbatim_doc_comment)]
Prune {
/// Remove entries older than this duration (e.g., 30d, 90d).
/// Defaults to configured retention period.
#[arg(long, value_name = "DURATION", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 10)]
older: Option<String>,
/// Preview deletions without removing files.
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 10)]
dry_run: bool,
},
/// Generate an anonymous usage snapshot for sharing
///
/// Creates a privacy-safe snapshot of your usage patterns that you can
/// share with the sqry community or attach to bug reports. All fields
/// are strongly-typed enums and numerics — no code content, paths, or
/// identifiers are ever included.
///
/// Uses are disabled → exits 1. Empty weeks produce a valid snapshot
/// with total_uses: 0 (not an error).
///
/// JSON output is controlled by the global --json flag.
///
/// Examples:
/// sqry insights share # Current week, human-readable
/// sqry --json insights share # JSON to stdout
/// sqry insights share --output snap.json # Write JSON to file
/// sqry insights share --week 2026-W09 # Specific week
/// sqry insights share --from 2026-W07 --to 2026-W09 # Merge 3 weeks
/// sqry insights share --dry-run # Preview without writing
#[cfg(feature = "share")]
#[command(verbatim_doc_comment)]
Share {
/// Specific ISO week to share (e.g., 2026-W09). Defaults to current week.
/// Conflicts with --from / --to.
#[arg(long, value_name = "WEEK", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 10,
conflicts_with_all = ["from", "to"])]
week: Option<String>,
/// Start of multi-week range (e.g., 2026-W07). Requires --to.
#[arg(long, value_name = "WEEK", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 11,
conflicts_with = "week", requires = "to")]
from: Option<String>,
/// End of multi-week range (e.g., 2026-W09). Requires --from.
#[arg(long, value_name = "WEEK", help_heading = headings::INSIGHTS_CONFIGURATION, display_order = 12,
conflicts_with = "week", requires = "from")]
to: Option<String>,
/// Write JSON snapshot to this file.
#[arg(long, short = 'o', value_name = "FILE", help_heading = headings::INSIGHTS_OUTPUT, display_order = 20,
conflicts_with = "dry_run")]
output: Option<PathBuf>,
/// Preview what would be shared without writing a file.
#[arg(long, help_heading = headings::SAFETY_CONTROL, display_order = 30,
conflicts_with = "output")]
dry_run: bool,
},
}
/// Import conflict resolution strategies
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
#[value(rename_all = "lowercase")]
pub enum ImportConflictArg {
/// Fail on any conflict (default)
Error,
/// Skip conflicting aliases
Skip,
/// Overwrite existing aliases
Overwrite,
}
/// Shell types for completions
#[derive(Debug, Clone, Copy, ValueEnum)]
#[allow(missing_docs)]
#[allow(clippy::enum_variant_names)]
pub enum Shell {
Bash,
Zsh,
Fish,
PowerShell,
Elvish,
}
/// Symbol types for filtering
#[derive(Debug, Clone, Copy, ValueEnum)]
#[allow(missing_docs)]
pub enum SymbolKind {
Function,
Class,
Method,
Struct,
Enum,
Interface,
Trait,
Variable,
Constant,
Type,
Module,
Namespace,
}
impl std::fmt::Display for SymbolKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SymbolKind::Function => write!(f, "function"),
SymbolKind::Class => write!(f, "class"),
SymbolKind::Method => write!(f, "method"),
SymbolKind::Struct => write!(f, "struct"),
SymbolKind::Enum => write!(f, "enum"),
SymbolKind::Interface => write!(f, "interface"),
SymbolKind::Trait => write!(f, "trait"),
SymbolKind::Variable => write!(f, "variable"),
SymbolKind::Constant => write!(f, "constant"),
SymbolKind::Type => write!(f, "type"),
SymbolKind::Module => write!(f, "module"),
SymbolKind::Namespace => write!(f, "namespace"),
}
}
}
/// Index validation strictness modes
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
#[value(rename_all = "lowercase")]
pub enum ValidationMode {
/// Skip validation entirely (fastest)
Off,
/// Log warnings but continue (default)
Warn,
/// Abort on validation errors
Fail,
}
/// Metrics export format for validation status
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum MetricsFormat {
/// JSON format (default, structured data)
#[value(alias = "jsn")]
Json,
/// Prometheus `OpenMetrics` text format
#[value(alias = "prom")]
Prometheus,
}
/// Classpath analysis depth for the `--classpath-depth` flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum ClasspathDepthArg {
/// Include all transitive dependencies.
Full,
/// Only direct (compile-scope) dependencies.
Shallow,
}
// Helper function to get the command with applied taxonomy
impl Cli {
/// Get the command with taxonomy headings applied
#[must_use]
pub fn command_with_taxonomy() -> clap::Command {
use clap::CommandFactory;
let cmd = Self::command();
headings::apply_root_layout(cmd)
}
/// Validate CLI arguments that have dependencies not enforceable via clap
///
/// Returns an error message if validation fails, None if valid.
#[must_use]
pub fn validate(&self) -> Option<&'static str> {
let tabular_mode = self.csv || self.tsv;
// --headers, --columns, and --raw-csv require CSV or TSV mode
if self.headers && !tabular_mode {
return Some("--headers requires --csv or --tsv");
}
if self.columns.is_some() && !tabular_mode {
return Some("--columns requires --csv or --tsv");
}
if self.raw_csv && !tabular_mode {
return Some("--raw-csv requires --csv or --tsv");
}
if tabular_mode && let Err(msg) = output::parse_columns(self.columns.as_ref()) {
return Some(Box::leak(msg.into_boxed_str()));
}
None
}
/// Get the search path, defaulting to current directory if not specified
#[must_use]
pub fn search_path(&self) -> &str {
self.path.as_deref().unwrap_or(".")
}
/// Resolve the path-scoped subcommand path, applying the global
/// `--workspace` / `SQRY_WORKSPACE_FILE` fallback (`STEP_8`).
///
/// Precedence (least-surprise, codified in
/// `docs/development/workspace-aware-cross-repo/03_IMPLEMENTATION_PLAN.md`
/// Step 8):
/// 1. Explicit positional `<path>` on the subcommand wins.
/// 2. The global `--workspace <PATH>` flag (or `SQRY_WORKSPACE_FILE`
/// environment variable; CLI flag wins on conflict) is the fallback.
/// 3. Otherwise, the top-level `cli.path` shorthand or `"."`.
///
/// Callers pass `positional` from the subcommand's own positional argument.
///
/// # Errors
///
/// Returns an error if the workspace fallback (from `--workspace` or
/// `SQRY_WORKSPACE_FILE`) is set but contains non-UTF-8 bytes. The
/// downstream CLI pipeline (positional `<path>` arguments and
/// `commands::run_index` / `commands::run_query` signatures) operates on
/// `&str`, so a non-UTF-8 workspace path cannot be propagated faithfully —
/// silently falling back to `"."` (or the top-level `cli.path`) would
/// violate the documented precedence semantics. Surface the failure
/// instead so the operator can supply a UTF-8 path. (STEP_8 codex iter1
/// fix.)
pub fn resolve_subcommand_path<'a>(
&'a self,
positional: Option<&'a str>,
) -> anyhow::Result<&'a str> {
if let Some(p) = positional {
return Ok(p);
}
if let Some(ws) = self.workspace.as_deref() {
return ws.to_str().ok_or_else(|| {
anyhow::anyhow!(
"--workspace / SQRY_WORKSPACE_FILE path is not valid UTF-8: {}. \
sqry's path-scoped subcommands require UTF-8 paths; supply a \
valid UTF-8 workspace path or pass an explicit positional \
argument.",
ws.display()
)
});
}
Ok(self.search_path())
}
/// Returns the workspace path supplied via `--workspace` /
/// `SQRY_WORKSPACE_FILE`, if any (`STEP_8`).
///
/// Surfaced for downstream consumers (LSP/MCP/test harnesses); the
/// CLI binary itself currently routes through `resolve_subcommand_path`,
/// so the binary build flags this as unused.
#[allow(dead_code)]
#[must_use]
pub fn workspace_path(&self) -> Option<&std::path::Path> {
self.workspace.as_deref()
}
/// Return the plugin-selection arguments for the active subcommand.
#[must_use]
pub fn plugin_selection_args(&self) -> PluginSelectionArgs {
match self.command.as_deref() {
Some(
Command::Query {
plugin_selection, ..
}
| Command::Index {
plugin_selection, ..
}
| Command::Update {
plugin_selection, ..
}
| Command::Watch {
plugin_selection, ..
},
) => plugin_selection.clone(),
_ => PluginSelectionArgs::default(),
}
}
/// Check if tabular output mode is enabled
#[allow(dead_code)]
#[must_use]
pub fn is_tabular_output(&self) -> bool {
self.csv || self.tsv
}
/// Create pager configuration from CLI flags
///
/// Returns `PagerConfig` based on `--pager`, `--no-pager`, and `--pager-cmd` flags.
///
/// # Structured Output Handling
///
/// For machine-readable formats (JSON, CSV, TSV), paging is disabled by default
/// to avoid breaking pipelines. Use `--pager` to explicitly enable paging for
/// these formats.
#[must_use]
pub fn pager_config(&self) -> crate::output::PagerConfig {
// Structured output bypasses pager unless --pager is explicit
let is_structured_output = self.json || self.csv || self.tsv;
let effective_no_pager = self.no_pager || (is_structured_output && !self.pager);
crate::output::PagerConfig::from_cli_flags(
self.pager,
effective_no_pager,
self.pager_cmd.as_deref(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::large_stack_test;
/// Guard: keep the `Command` enum from silently ballooning.
/// If this fails, consider extracting the largest variant into a Box<T>.
#[test]
fn test_command_enum_size() {
let size = std::mem::size_of::<Command>();
assert!(
size <= 256,
"Command enum is {size} bytes, should be <= 256"
);
}
large_stack_test! {
#[test]
fn test_cli_parse_basic_search() {
let cli = Cli::parse_from(["sqry", "main"]);
assert!(cli.command.is_none());
assert_eq!(cli.pattern, Some("main".to_string()));
assert_eq!(cli.path, None); // Defaults to None, use cli.search_path() to get "."
assert_eq!(cli.search_path(), ".");
}
}
large_stack_test! {
#[test]
fn test_cli_parse_with_path() {
let cli = Cli::parse_from(["sqry", "test", "src/"]);
assert_eq!(cli.pattern, Some("test".to_string()));
assert_eq!(cli.path, Some("src/".to_string()));
assert_eq!(cli.search_path(), "src/");
}
}
large_stack_test! {
#[test]
fn test_cli_parse_search_subcommand() {
let cli = Cli::parse_from(["sqry", "search", "main"]);
assert!(matches!(cli.command.as_deref(), Some(Command::Search { .. })));
}
}
large_stack_test! {
#[test]
fn test_cli_parse_query_subcommand() {
let cli = Cli::parse_from(["sqry", "query", "kind:function"]);
assert!(matches!(cli.command.as_deref(), Some(Command::Query { .. })));
}
}
large_stack_test! {
#[test]
fn test_cli_flags() {
let cli = Cli::parse_from(["sqry", "main", "--json", "--no-color", "--ignore-case"]);
assert!(cli.json);
assert!(cli.no_color);
assert!(cli.ignore_case);
}
}
large_stack_test! {
#[test]
fn test_validation_mode_default() {
let cli = Cli::parse_from(["sqry", "index"]);
assert_eq!(cli.validate, ValidationMode::Warn);
assert!(!cli.auto_rebuild);
}
}
large_stack_test! {
#[test]
fn test_validation_mode_flags() {
let cli = Cli::parse_from(["sqry", "index", "--validate", "fail", "--auto-rebuild"]);
assert_eq!(cli.validate, ValidationMode::Fail);
assert!(cli.auto_rebuild);
}
}
large_stack_test! {
#[test]
fn test_plugin_selection_flags_parse() {
let cli = Cli::parse_from([
"sqry",
"index",
"--include-high-cost",
"--enable-plugin",
"json",
"--disable-plugin",
"rust",
]);
let plugin_selection = cli.plugin_selection_args();
assert!(plugin_selection.include_high_cost);
assert_eq!(plugin_selection.enable_plugins, vec!["json".to_string()]);
assert_eq!(plugin_selection.disable_plugins, vec!["rust".to_string()]);
}
}
large_stack_test! {
#[test]
fn test_plugin_selection_language_aliases_parse() {
let cli = Cli::parse_from([
"sqry",
"index",
"--enable-language",
"json",
"--disable-language",
"rust",
]);
let plugin_selection = cli.plugin_selection_args();
assert_eq!(plugin_selection.enable_plugins, vec!["json".to_string()]);
assert_eq!(plugin_selection.disable_plugins, vec!["rust".to_string()]);
}
}
large_stack_test! {
#[test]
fn test_validate_rejects_invalid_columns() {
let cli = Cli::parse_from([
"sqry",
"--csv",
"--columns",
"name,unknown",
"query",
"path",
]);
let msg = cli.validate().expect("validation should fail");
assert!(msg.contains("Unknown column"), "Unexpected message: {msg}");
}
}
large_stack_test! {
#[test]
fn test_index_rebuild_alias_sets_force() {
// Verify --rebuild is an alias for --force
let cli = Cli::parse_from(["sqry", "index", "--rebuild", "."]);
if let Some(Command::Index { force, .. }) = cli.command.as_deref() {
assert!(force, "--rebuild should set force=true");
} else {
panic!("Expected Index command");
}
}
}
large_stack_test! {
#[test]
fn test_index_force_still_works() {
// Ensure --force continues to work (backward compat)
let cli = Cli::parse_from(["sqry", "index", "--force", "."]);
if let Some(Command::Index { force, .. }) = cli.command.as_deref() {
assert!(force, "--force should set force=true");
} else {
panic!("Expected Index command");
}
}
}
large_stack_test! {
#[test]
fn test_graph_deps_alias() {
// Verify "deps" is an alias for dependency-tree
let cli = Cli::parse_from(["sqry", "graph", "deps", "main"]);
assert!(matches!(
cli.command.as_deref(),
Some(Command::Graph {
operation: GraphOperation::DependencyTree { .. },
..
})
));
}
}
large_stack_test! {
#[test]
fn test_graph_cyc_alias() {
let cli = Cli::parse_from(["sqry", "graph", "cyc"]);
assert!(matches!(
cli.command.as_deref(),
Some(Command::Graph {
operation: GraphOperation::Cycles { .. },
..
})
));
}
}
large_stack_test! {
#[test]
fn test_graph_cx_alias() {
let cli = Cli::parse_from(["sqry", "graph", "cx"]);
assert!(matches!(
cli.command.as_deref(),
Some(Command::Graph {
operation: GraphOperation::Complexity { .. },
..
})
));
}
}
large_stack_test! {
#[test]
fn test_graph_nodes_args() {
let cli = Cli::parse_from([
"sqry",
"graph",
"nodes",
"--kind",
"function",
"--languages",
"rust",
"--file",
"src/",
"--name",
"main",
"--qualified-name",
"crate::main",
"--limit",
"5",
"--offset",
"2",
"--full-paths",
]);
if let Some(Command::Graph {
operation:
GraphOperation::Nodes {
kind,
languages,
file,
name,
qualified_name,
limit,
offset,
full_paths,
},
..
}) = cli.command.as_deref()
{
assert_eq!(kind, &Some("function".to_string()));
assert_eq!(languages, &Some("rust".to_string()));
assert_eq!(file, &Some("src/".to_string()));
assert_eq!(name, &Some("main".to_string()));
assert_eq!(qualified_name, &Some("crate::main".to_string()));
assert_eq!(*limit, 5);
assert_eq!(*offset, 2);
assert!(full_paths);
} else {
panic!("Expected Graph Nodes command");
}
}
}
large_stack_test! {
#[test]
fn test_graph_edges_args() {
let cli = Cli::parse_from([
"sqry",
"graph",
"edges",
"--kind",
"calls",
"--from",
"main",
"--to",
"worker",
"--from-lang",
"rust",
"--to-lang",
"python",
"--file",
"src/main.rs",
"--limit",
"10",
"--offset",
"1",
"--full-paths",
]);
if let Some(Command::Graph {
operation:
GraphOperation::Edges {
kind,
from,
to,
from_lang,
to_lang,
file,
limit,
offset,
full_paths,
},
..
}) = cli.command.as_deref()
{
assert_eq!(kind, &Some("calls".to_string()));
assert_eq!(from, &Some("main".to_string()));
assert_eq!(to, &Some("worker".to_string()));
assert_eq!(from_lang, &Some("rust".to_string()));
assert_eq!(to_lang, &Some("python".to_string()));
assert_eq!(file, &Some("src/main.rs".to_string()));
assert_eq!(*limit, 10);
assert_eq!(*offset, 1);
assert!(full_paths);
} else {
panic!("Expected Graph Edges command");
}
}
}
// ===== Pager Tests (P2-29) =====
large_stack_test! {
#[test]
fn test_pager_flag_default() {
let cli = Cli::parse_from(["sqry", "query", "kind:function"]);
assert!(!cli.pager);
assert!(!cli.no_pager);
assert!(cli.pager_cmd.is_none());
}
}
large_stack_test! {
#[test]
fn test_pager_flag() {
let cli = Cli::parse_from(["sqry", "--pager", "query", "kind:function"]);
assert!(cli.pager);
assert!(!cli.no_pager);
}
}
large_stack_test! {
#[test]
fn test_no_pager_flag() {
let cli = Cli::parse_from(["sqry", "--no-pager", "query", "kind:function"]);
assert!(!cli.pager);
assert!(cli.no_pager);
}
}
large_stack_test! {
#[test]
fn test_pager_cmd_flag() {
let cli = Cli::parse_from([
"sqry",
"--pager-cmd",
"bat --style=plain",
"query",
"kind:function",
]);
assert_eq!(cli.pager_cmd, Some("bat --style=plain".to_string()));
}
}
large_stack_test! {
#[test]
fn test_pager_and_no_pager_conflict() {
// These flags conflict and clap should reject
let result =
Cli::try_parse_from(["sqry", "--pager", "--no-pager", "query", "kind:function"]);
assert!(result.is_err());
}
}
large_stack_test! {
#[test]
fn test_pager_flags_global() {
// Pager flags work with any subcommand
let cli = Cli::parse_from(["sqry", "--no-pager", "search", "test"]);
assert!(cli.no_pager);
let cli = Cli::parse_from(["sqry", "--pager", "index"]);
assert!(cli.pager);
}
}
large_stack_test! {
#[test]
fn test_pager_config_json_bypasses_pager() {
use crate::output::pager::PagerMode;
// JSON output should bypass pager by default
let cli = Cli::parse_from(["sqry", "--json", "search", "test"]);
let config = cli.pager_config();
assert_eq!(config.enabled, PagerMode::Never);
}
}
large_stack_test! {
#[test]
fn test_pager_config_csv_bypasses_pager() {
use crate::output::pager::PagerMode;
// CSV output should bypass pager by default
let cli = Cli::parse_from(["sqry", "--csv", "search", "test"]);
let config = cli.pager_config();
assert_eq!(config.enabled, PagerMode::Never);
}
}
large_stack_test! {
#[test]
fn test_pager_config_tsv_bypasses_pager() {
use crate::output::pager::PagerMode;
// TSV output should bypass pager by default
let cli = Cli::parse_from(["sqry", "--tsv", "search", "test"]);
let config = cli.pager_config();
assert_eq!(config.enabled, PagerMode::Never);
}
}
large_stack_test! {
#[test]
fn test_pager_config_json_with_explicit_pager() {
use crate::output::pager::PagerMode;
// JSON with explicit --pager should enable pager
let cli = Cli::parse_from(["sqry", "--json", "--pager", "search", "test"]);
let config = cli.pager_config();
assert_eq!(config.enabled, PagerMode::Always);
}
}
large_stack_test! {
#[test]
fn test_pager_config_text_output_auto() {
use crate::output::pager::PagerMode;
// Text output (default) should use auto pager mode
let cli = Cli::parse_from(["sqry", "search", "test"]);
let config = cli.pager_config();
assert_eq!(config.enabled, PagerMode::Auto);
}
}
// ===== Macro boundary CLI tests =====
large_stack_test! {
#[test]
fn test_cache_expand_args_parsing() {
let cli = Cli::parse_from([
"sqry", "cache", "expand",
"--refresh",
"--crate-name", "my_crate",
"--dry-run",
"--output", "/tmp/expand-out",
]);
if let Some(Command::Cache { action }) = cli.command.as_deref() {
match action {
CacheAction::Expand {
refresh,
crate_name,
dry_run,
output,
} => {
assert!(refresh);
assert_eq!(crate_name.as_deref(), Some("my_crate"));
assert!(dry_run);
assert_eq!(output.as_deref(), Some(std::path::Path::new("/tmp/expand-out")));
}
_ => panic!("Expected CacheAction::Expand"),
}
} else {
panic!("Expected Cache command");
}
}
}
large_stack_test! {
#[test]
fn test_cache_expand_defaults() {
let cli = Cli::parse_from(["sqry", "cache", "expand"]);
if let Some(Command::Cache { action }) = cli.command.as_deref() {
match action {
CacheAction::Expand {
refresh,
crate_name,
dry_run,
output,
} => {
assert!(!refresh);
assert!(crate_name.is_none());
assert!(!dry_run);
assert!(output.is_none());
}
_ => panic!("Expected CacheAction::Expand"),
}
} else {
panic!("Expected Cache command");
}
}
}
large_stack_test! {
#[test]
fn test_index_macro_flags_parsing() {
let cli = Cli::parse_from([
"sqry", "index",
"--enable-macro-expansion",
"--cfg", "test",
"--cfg", "unix",
"--expand-cache", "/tmp/expand",
]);
if let Some(Command::Index {
enable_macro_expansion,
cfg_flags,
expand_cache,
..
}) = cli.command.as_deref()
{
assert!(enable_macro_expansion);
assert_eq!(cfg_flags, &["test".to_string(), "unix".to_string()]);
assert_eq!(expand_cache.as_deref(), Some(std::path::Path::new("/tmp/expand")));
} else {
panic!("Expected Index command");
}
}
}
large_stack_test! {
#[test]
fn test_index_macro_flags_defaults() {
let cli = Cli::parse_from(["sqry", "index"]);
if let Some(Command::Index {
enable_macro_expansion,
cfg_flags,
expand_cache,
..
}) = cli.command.as_deref()
{
assert!(!enable_macro_expansion);
assert!(cfg_flags.is_empty());
assert!(expand_cache.is_none());
} else {
panic!("Expected Index command");
}
}
}
large_stack_test! {
#[test]
fn test_search_macro_flags_parsing() {
let cli = Cli::parse_from([
"sqry", "search", "test_fn",
"--cfg-filter", "test",
"--include-generated",
"--macro-boundaries",
]);
if let Some(Command::Search {
cfg_filter,
include_generated,
macro_boundaries,
..
}) = cli.command.as_deref()
{
assert_eq!(cfg_filter.as_deref(), Some("test"));
assert!(include_generated);
assert!(macro_boundaries);
} else {
panic!("Expected Search command");
}
}
}
large_stack_test! {
#[test]
fn test_search_macro_flags_defaults() {
let cli = Cli::parse_from(["sqry", "search", "test_fn"]);
if let Some(Command::Search {
cfg_filter,
include_generated,
macro_boundaries,
..
}) = cli.command.as_deref()
{
assert!(cfg_filter.is_none());
assert!(!include_generated);
assert!(!macro_boundaries);
} else {
panic!("Expected Search command");
}
}
}
// ===== Daemon subcommand CLI tests (Task 10 U2) =====
large_stack_test! {
#[test]
fn daemon_start_parses() {
let cli = Cli::parse_from(["sqry", "daemon", "start"]);
if let Some(Command::Daemon { action }) = cli.command.as_deref() {
match action.as_ref() {
DaemonAction::Start { sqryd_path, timeout } => {
assert!(sqryd_path.is_none(), "sqryd_path should default to None");
assert_eq!(*timeout, 10, "default timeout should be 10");
}
other => panic!("Expected DaemonAction::Start, got {:?}", other),
}
} else {
panic!("Expected Command::Daemon");
}
}
}
large_stack_test! {
#[test]
fn daemon_stop_parses() {
let cli = Cli::parse_from(["sqry", "daemon", "stop", "--timeout", "30"]);
if let Some(Command::Daemon { action }) = cli.command.as_deref() {
match action.as_ref() {
DaemonAction::Stop { timeout } => {
assert_eq!(*timeout, 30, "timeout should be 30");
}
other => panic!("Expected DaemonAction::Stop, got {:?}", other),
}
} else {
panic!("Expected Command::Daemon");
}
}
}
large_stack_test! {
#[test]
fn daemon_status_json_parses() {
let cli = Cli::parse_from(["sqry", "daemon", "status", "--json"]);
if let Some(Command::Daemon { action }) = cli.command.as_deref() {
match action.as_ref() {
DaemonAction::Status { json } => {
assert!(*json, "--json flag should be true");
}
other => panic!("Expected DaemonAction::Status, got {:?}", other),
}
} else {
panic!("Expected Command::Daemon");
}
}
}
large_stack_test! {
#[test]
fn daemon_logs_follow_parses() {
let cli = Cli::parse_from(["sqry", "daemon", "logs", "--follow", "--lines", "100"]);
if let Some(Command::Daemon { action }) = cli.command.as_deref() {
match action.as_ref() {
DaemonAction::Logs { lines, follow } => {
assert_eq!(*lines, 100, "lines should be 100");
assert!(*follow, "--follow flag should be true");
}
other => panic!("Expected DaemonAction::Logs, got {:?}", other),
}
} else {
panic!("Expected Command::Daemon");
}
}
}
large_stack_test! {
#[test]
fn daemon_load_parses() {
let cli = Cli::parse_from(["sqry", "daemon", "load", "/some/workspace"]);
if let Some(Command::Daemon { action }) = cli.command.as_deref() {
match action.as_ref() {
DaemonAction::Load { path } => {
assert_eq!(
path,
&std::path::PathBuf::from("/some/workspace"),
"path should be /some/workspace"
);
}
other => panic!("Expected DaemonAction::Load, got {:?}", other),
}
} else {
panic!("Expected Command::Daemon");
}
}
}
}