calcit-cli 0.59.1

CLI command handlers, static analysis, diffing, and native FFI host injection for Calcit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
use argh::FromArgs;

pub const CALCIT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(FromArgs, PartialEq, Debug, Clone)]
/// Top-level command.
pub struct ToplevelCalcit {
  #[argh(subcommand)]
  pub subcommand: Option<CalcitCommand>,
  /// enable watch mode for direct run mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
  /// check-only mode: validate without execution or codegen
  #[argh(switch)]
  pub check_only: bool,
  /// reuse a successful entry preprocessing result in check-only mode
  #[argh(switch)]
  pub incremental: bool,
  /// continue check-only validation across independent definitions
  #[argh(switch)]
  pub keep_going: bool,
  /// with --check-only, also check every definition in project namespaces (not only entry-reachable ones); implies --keep-going
  #[argh(switch)]
  pub all_defs: bool,
  /// with --check-only, check every definition in this public namespace for the active entry target; repeat for shared and target-specific namespaces
  #[argh(option)]
  pub ns: Vec<String>,
  /// with --check-only, enforce portable Static Core rules across Browser JS and WASI targets
  #[argh(switch, long = "static-core")]
  pub static_core: bool,
  /// with --check-only --ns, admit selected namespaces loaded from dependencies or calcit.core
  #[argh(switch)]
  pub deps: bool,
  /// with --check-only (--ns, --keep-going, or --all-defs), emit compact summary output without passed definition rows
  #[argh(switch, long = "summary-only")]
  pub summary_only: bool,
  /// check-only report format: human, edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// disable stack trace for errors
  #[argh(switch)]
  pub disable_stack: bool,
  /// skip arity check in js codegen
  #[argh(switch)]
  pub skip_arity_check: bool,
  /// warn on dynamic method calls that cannot be monomorphized
  #[argh(switch)]
  pub warn_dyn_method: bool,
  /// keep strict diagnostics but skip the default assertion-proof audit
  #[argh(switch)]
  pub no_proof_audit: bool,
  /// treat downgraded runtime predicate warnings (W_RUNTIME_TYPE_PREDICATE on `(:open :reflect|:decode)` boundaries) as blocking errors
  #[argh(switch, long = "deny-migration-warnings")]
  pub deny_migration_warnings: bool,
  /// print FFI dylib calls and callbacks for debugging native crashes
  #[argh(switch)]
  pub trace_ffi: bool,
  /// entry file path, defaults to "js-out/"
  #[argh(option, default = "String::from(\"js-out/\")")]
  pub emit_path: String,
  /// specify `init_fn` which is main function
  #[argh(option)]
  pub init_fn: Option<String>,
  /// specify `reload_fn` which is called after hot reload
  #[argh(option)]
  pub reload_fn: Option<String>,
  /// select an entry; defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  #[argh(switch)]
  /// force reloading libs data during code reload
  pub reload_libs: bool,
  #[argh(option)]
  /// specify a path to watch assets changes
  pub watch_dir: Option<String>,
  /// input source file, defaults to "calcit.cirru"; retired compact.cirru inputs receive migration guidance
  #[argh(positional, default = "String::from(calcit_core::DEFAULT_SNAPSHOT_FILE)")]
  pub input: String,
  /// print version only
  #[argh(switch, short = 'v')]
  pub version: bool,
  /// print progress details and timing while loading and compiling
  #[argh(switch)]
  pub verbose: bool,
  /// emit machine-readable macro expansion metrics to stderr on exit
  #[argh(switch)]
  pub macro_metrics: bool,
  /// emit machine-readable native async FFI metrics to stderr on exit
  #[argh(switch)]
  pub ffi_metrics: bool,
  /// maximum seconds for one JS/IR compilation (0 disables the limit)
  #[argh(option, default = "60")]
  pub timeout: u64,
  /// show full tips output in all commands
  #[argh(switch)]
  pub tips: bool,
  /// control tips verbosity: minimal (default), full, none
  #[argh(option)]
  pub tips_level: Option<String>,
  /// cursor feedback after mutating edit/tree commands: none, summary (default), focus
  #[argh(option, default = "String::from(\"summary\")")]
  pub cursor_after: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum CalcitCommand {
  /// emit JavaScript rather than interpreting
  EmitJs(EmitJsCommand),
  /// emit a browser or embedded WebAssembly core module
  EmitWasm(EmitWasmCommand),
  /// emit a WebAssembly command module for a WASI host
  EmitWasi(EmitWasiCommand),
  /// diagnostic: emit compiler IR as Cirru EDN to program-ir.cirru
  EmitIr(EmitIrCommand),
  /// evaluate snippet
  Eval(EvalCommand),
  /// discover and run definition-attached tests
  Test(TestCommand),
  /// preview or apply compiler-guided source migrations
  Fix(FixCommand),
  /// analyze code structure, type-debt views, and helpers (call-graph, program-diff, weak-types, check-examples, verify)
  Analyze(AnalyzeCommand),
  /// query project information (namespaces, definitions, configs)
  Query(QueryCommand),
  /// documentation tools for guidebook, installed module docs, and local markdown docs
  Docs(DocsCommand),
  /// Cirru syntax tools (parse, format)
  Cirru(CirruCommand),
  /// coarse-grained code editing (namespaces, definitions, metadata); for internal expression changes, use `tree` instead
  Edit(EditCommand),
  /// fine-grained tree operations (view and modify AST nodes within definitions)
  Tree(TreeCommand),
  /// maintain a persistent virtual cursor for tree navigation and editing
  Cursor(CursorCommand),
  /// manage project configuration (show, set, modules, add-module, rm-module)
  Config(ConfigCommand),
  /// inspect and export typed FFI interface contracts
  Ffi(FfiCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(
  subcommand,
  name = "fix",
  note = "Project upgrades follow one ordered sequence: run `calcit docs agents 项目升级入口` (embedded in this CLI), then `calcit docs read upgrade.md '当前升级闭环'` from a guidebook checked out at the same release tag."
)]
/// preview or apply compiler-guided migrations or reviewed structural source rewrites
pub struct FixCommand {
  /// write applicable fixes atomically after validation
  #[argh(switch)]
  pub apply: bool,
  /// explicitly request preview mode; preview is also the default
  #[argh(switch, long = "dry-run")]
  pub dry_run: bool,
  /// include definition tests and examples in supported migration rules
  #[argh(switch, long = "include-attached")]
  pub include_attached: bool,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// restrict fixes to one exact project namespace
  #[argh(option)]
  pub ns: Option<String>,
  /// restrict fixes to one definition; requires --ns
  #[argh(option, long = "def")]
  pub definition: Option<String>,
  /// restrict fixes to one stable rule ID
  #[argh(option)]
  pub rule: Option<String>,
  /// select surface-latest-v1, surface-latest-v2, core-api-0.28-v1, or core-api-0.29-v1 migration rules
  #[argh(option)]
  pub preset: Option<String>,
  /// match one exact Cirru source pattern with ?name subtree variables (reviewed syntax only)
  #[argh(option)]
  pub pattern: Option<String>,
  /// replacement Cirru template for --pattern; does not prove semantic equivalence
  #[argh(option, long = "replace")]
  pub replacement: Option<String>,
  /// compose a project workflow; currently supports strict
  #[argh(option)]
  pub workflow: Option<String>,
  /// verify a selected project workflow without mutating the snapshot
  #[argh(switch)]
  pub verify: bool,
  /// show strict verification status and failure locations without the full migration report
  #[argh(switch, long = "summary-only")]
  pub summary_only: bool,
  /// replacement name required by rename-definition-v1 and rename-local-v1
  #[argh(option, long = "to")]
  pub replacement_name: Option<String>,
  /// path of the local binding name for rename-local-v1, such as 3.1.0.0
  #[argh(option)]
  pub at: Option<String>,
  /// require the snapshot content to match this revision before applying
  #[argh(option, long = "expect-revision")]
  pub expect_revision: Option<String>,
  /// allow applying while the Git working tree contains changes
  #[argh(switch, long = "allow-dirty")]
  pub allow_dirty: bool,
  /// allow applying when the project is not inside a Git worktree
  #[argh(switch, long = "allow-no-vcs")]
  pub allow_no_vcs: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ffi")]
/// inspect and export typed FFI interface contracts
pub struct FfiCommand {
  #[argh(subcommand)]
  pub subcommand: FfiSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum FfiSubcommand {
  /// export versioned Interface IR from local definitions with typed schemas and FFI lowering metadata
  Export(FfiExportCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "export")]
/// export versioned Interface IR from local definitions with typed schemas and FFI lowering metadata
pub struct FfiExportCommand {
  /// select native raw bindings or the directional component surface
  #[argh(option, default = "String::from(\"native\")")]
  pub boundary: String,
  /// output format: human, edn, or json; component defaults to edn
  #[argh(option)]
  pub format: Option<String>,
  /// restrict export to one exact local namespace
  #[argh(option)]
  pub ns: Option<String>,
}

/// discover and run definition-attached tests.
///
/// Assert expected results explicitly; a returned false, nil or Unit does not
/// fail a test.
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "test")]
pub struct TestCommand {
  /// optional namespace or namespace/definition scope
  #[argh(positional)]
  pub target: Option<String>,
  /// run only a test with this exact name
  #[argh(option)]
  pub name: Option<String>,
  /// run tests tagged with this tag; repeat to require multiple tags
  #[argh(option)]
  pub tag: Vec<String>,
  /// skip tests tagged with this tag; repeat to exclude any matching tag
  #[argh(option)]
  pub exclude_tag: Vec<String>,
  /// select tests that statically depend on this namespace/definition; repeat for multiple changed definitions
  #[argh(option)]
  pub affected: Vec<String>,
  /// list selected tests without running them
  #[argh(switch)]
  pub list: bool,
  /// stop after the first failed test
  #[argh(switch)]
  pub fail_fast: bool,
  /// fail when the requested scope and filters select no tests
  #[argh(switch)]
  pub require_match: bool,
  /// omit individual test rows; useful for large CI and agent runs
  #[argh(switch)]
  pub summary_only: bool,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

/// emit JavaScript rather than interpreting
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "js")]
pub struct EmitJsCommand {
  /// enable watch mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
  /// check-only mode for JS emit
  #[argh(switch)]
  pub check_only: bool,
}

/// emit a browser or embedded WebAssembly core module
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "wasm")]
pub struct EmitWasmCommand {
  /// input source file, defaults to "calcit.cirru"
  #[argh(positional)]
  pub input: Option<String>,
  /// output directory for program.wasm; defaults to the top-level emit path
  #[argh(option)]
  pub emit_path: Option<String>,
  /// select a configured entry
  #[argh(option)]
  pub entry: Option<String>,
  /// override the configured initialization definition
  #[argh(option)]
  pub init_fn: Option<String>,
  /// override the configured reload definition
  #[argh(option)]
  pub reload_fn: Option<String>,
  /// output ABI boundary: native (default) or component
  #[argh(option, default = "String::from(\"native\")")]
  pub boundary: String,
  /// validate the core module without writing program.wasm
  #[argh(switch)]
  pub check_only: bool,
}

/// emit a WebAssembly command module for a WASI host
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "wasi")]
pub struct EmitWasiCommand {
  /// input source file, defaults to "calcit.cirru"
  #[argh(positional)]
  pub input: Option<String>,
  /// output directory for program.wasm; defaults to the top-level emit path
  #[argh(option)]
  pub emit_path: Option<String>,
  /// select a configured entry
  #[argh(option)]
  pub entry: Option<String>,
  /// override the configured initialization definition; it must take no arguments
  #[argh(option)]
  pub init_fn: Option<String>,
  /// override the configured reload definition
  #[argh(option)]
  pub reload_fn: Option<String>,
  /// output ABI boundary: component (WASI 0.3 default) or native (Preview 1)
  #[argh(option, default = "String::from(\"component\")")]
  pub boundary: String,
  /// target WASI world: command (WASI 0.3 default) or http (WASI 0.2 proxy)
  #[argh(option, default = "String::from(\"command\")")]
  pub world: String,
  /// emit a raw Canonical ABI core module without built-in Component packaging (for external WIT embedding and component composition)
  #[argh(switch)]
  pub emit_core: bool,
  /// validate the WASI component without writing program.wasm
  #[argh(switch)]
  pub check_only: bool,
}

/// diagnostic compiler output; not an application execution target
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ir")]
pub struct EmitIrCommand {
  /// enable watch mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
  /// write only `:meta`, `:configs` and `:sources` (source, docs, types, deps) for program viewers
  #[argh(switch)]
  pub sources_only: bool,
}

/// evaluate snippet
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "eval")]
pub struct EvalCommand {
  /// evaluate a snippet
  #[argh(positional)]
  pub snippet: Option<String>,
  /// read a snippet from stdin instead of a positional argument
  #[argh(switch)]
  pub stdin: bool,
  /// entry file path
  #[argh(option)]
  pub dep: Vec<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Analyze subcommand - code structure analysis
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "analyze")]
/// analyze code structure, type-debt views, and helpers (call-graph, program-diff, weak-types, check-examples, verify)
pub struct AnalyzeCommand {
  #[argh(subcommand)]
  pub subcommand: AnalyzeSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum AnalyzeSubcommand {
  /// analyze call graph structure from entry point; `--counts` counts calls, `--diff <ref>` compares against a Git ref, `--effects` builds the State/Transform/Effect graph
  CallGraph(CallGraphCommand),
  /// compare current snapshot (or one definition) against a Git ref with structured tree diff
  ProgramDiff(ProgramDiffCommand),
  /// check examples in namespace
  CheckExamples(CheckExamplesCommand),
  /// locate weakly-typed hotspots, type coverage, dynamic method dispatch, or deprecated calls (select with --only)
  WeakTypes(WeakTypesCommand),
  /// run a declarative project verification profile
  Verify(VerifyCommand),
}

/// run a declarative project verification profile
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "verify")]
pub struct VerifyCommand {
  /// profile name from snapshot :verification.profiles
  #[argh(option)]
  pub profile: String,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

/// Options of the public-definition check that `--check-only --ns` runs.
#[derive(PartialEq, Debug, Clone)]
pub struct CheckPublicCommand {
  /// exact public namespaces to check, shared and target-specific
  pub ns: Vec<String>,
  /// output format: human, edn, or json
  pub format: String,
  /// allow selected namespaces loaded from dependencies or calcit.core
  pub deps: bool,
  /// emit aggregate counts without per-definition rows
  pub summary_only: bool,
  /// enforce portable Static Core rules without requiring an entry :target
  pub static_core: bool,
}

/// Options of the type-coverage view that `analyze weak-types --only coverage` runs.
#[derive(PartialEq, Debug, Clone)]
pub struct CheckTypesCommand {
  /// exact namespace to analyze
  pub ns: Option<String>,
  /// namespace prefix scope filter
  pub ns_prefix: Option<String>,
  /// coverage levels to include, comma-separated: none,partial,full
  pub only: Option<String>,
  /// output format: human, edn, or json
  pub format: String,
  /// include dependency/core namespaces
  pub deps: bool,
  /// emit aggregate counts without per-definition details
  pub summary_only: bool,
  /// reuse revision-keyed per-definition analysis from .calcit local state
  pub incremental: bool,
}

/// locate weakly-typed hotspots, type coverage, dynamic method dispatch, or deprecated calls
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "weak-types")]
pub struct WeakTypesCommand {
  /// exact namespace to analyze
  #[argh(option)]
  pub ns: Option<String>,
  /// namespace prefix scope filter
  #[argh(option)]
  pub ns_prefix: Option<String>,
  /// match kinds to include, comma-separated: schema-dynamic,schema-open,unresolved-type-slot,code-dynamic,code-nil,unsafe-coerce,data-dynamic (opt-in, not in the default report); or exactly one view: coverage, dynamic-method, deprecated-call, option-nil-roundtrip, inferred-dynamic, legacy-migration
  #[argh(option)]
  pub only: Option<String>,
  /// with --only coverage, coverage levels to include, comma-separated: none,partial,full
  #[argh(option, long = "coverage-level")]
  pub coverage_level: Option<String>,
  /// intent classes to include, comma-separated: unresolved,intentional-js-ffi,js-ffi-non-host,intentional-macro-syntax,intentional-type-slot-dynamic,intentional-decode,intentional-open,explicit-unsafe,declared-unit
  #[argh(option)]
  pub intent: Option<String>,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// include dependency/core namespaces
  #[argh(switch)]
  pub deps: bool,
  /// include review-only JS FFI boundary evidence and migration candidates
  #[argh(switch, long = "ffi-evidence")]
  pub ffi_evidence: bool,
  /// include review-only schema, map-shape, and dispatch candidates
  #[argh(switch, long = "schema-evidence")]
  pub schema_evidence: bool,
  /// emit aggregate counts without per-definition details
  #[argh(switch, long = "summary-only")]
  pub summary_only: bool,
  /// reuse revision-keyed per-definition analysis from .calcit local state
  #[argh(switch)]
  pub incremental: bool,
}

/// options of `analyze weak-types --only dynamic-method`, normalized from `WeakTypesCommand`
#[derive(PartialEq, Debug, Clone)]
pub struct DynamicMethodsCommand {
  /// output format: human (default), edn, or json
  pub format: String,
  /// include dependency namespaces
  pub deps: bool,
  /// emit aggregate counts without individual findings
  pub summary_only: bool,
  /// reuse entry preprocessing findings when its dependency closure is unchanged
  pub incremental: bool,
}

/// options of `analyze weak-types --only deprecated-call`, normalized from `WeakTypesCommand`
#[derive(PartialEq, Debug, Clone)]
pub struct DeprecatedCommand {
  /// exact namespace to analyze
  pub ns: Option<String>,
  /// namespace prefix scope filter
  pub ns_prefix: Option<String>,
  /// output format: human (default), edn, or json
  pub format: String,
  /// include dependency/core namespaces
  pub deps: bool,
  /// emit aggregate counts without per-definition details
  pub summary_only: bool,
}

/// check examples in namespace
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "check-examples")]
pub struct CheckExamplesCommand {
  /// target namespace to check examples
  #[argh(option)]
  pub ns: String,
  /// check only one definition in the namespace
  #[argh(option, long = "def")]
  pub definition: Option<String>,
  /// run examples through JavaScript codegen and Node.js
  #[argh(switch)]
  pub js: bool,
}

/// analyze call tree structure from entry point; `--counts` counts call occurrences, `--diff <ref>` compares against a Git ref, `--effects` builds the State/Transform/Effect graph
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "call-graph")]
pub struct CallGraphCommand {
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses init-fn from config
  #[argh(option)]
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  #[argh(option)]
  pub ns_prefix: Option<String>,
  /// include core/library calls in the output
  #[argh(switch)]
  pub include_core: bool,
  /// maximum depth to traverse (default: 0 = unlimited, or 2 with --effects)
  #[argh(option)]
  pub max_depth: Option<usize>,
  /// show definitions unreachable from the selected entry (may include external entry points)
  #[argh(switch)]
  pub show_unused: bool,
  /// output format: human (default, LLM-friendly; legacy aliases text, tree), edn, or json; `--diff` supports human only
  #[argh(option, default = "String::from(\"text\")")]
  pub format: String,
  /// count call occurrences per definition instead of printing the tree
  #[argh(switch)]
  pub counts: bool,
  /// with --counts, sort by "count" (default, descending) or "name"
  #[argh(option)]
  pub sort: Option<String>,
  /// compare the call graph against a Git ref (e.g. HEAD~1, main, or a commit SHA) and annotate code changes
  #[argh(option)]
  pub diff: Option<String>,
  /// decompose entry into a State / Transform / Effect dependency graph instead of a plain call tree
  #[argh(switch)]
  pub effects: bool,
  /// with --effects, transform compression level: summary (default), full, or minimal
  #[argh(option)]
  pub detail: Option<String>,
  /// with --effects, enable ANSI colors in tree output (default: true; pass false to disable)
  #[argh(option)]
  pub color: Option<bool>,
}

/// options of `analyze call-graph --effects`, normalized from `CallGraphCommand`
#[derive(PartialEq, Debug, Clone)]
pub struct EffectsGraphCommand {
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses init-fn from config
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  pub ns_prefix: Option<String>,
  /// include core/library calls in the output
  pub include_core: bool,
  /// maximum depth to traverse (0 = unlimited, 2 = default)
  pub max_depth: usize,
  /// output format: human (default, State / Transform / Effect tree; legacy alias tree), edn, or json
  pub format: String,
  /// transform compression level: summary, full, or minimal
  pub detail: String,
  /// enable ANSI colors in tree output (default: true; pass false to disable)
  pub color: bool,
}

/// options of `analyze call-graph --diff <ref>`, normalized from `CallGraphCommand`
#[derive(PartialEq, Debug, Clone)]
pub struct CallGraphDiffCommand {
  /// git reference to compare against, e.g. HEAD~1, main, v0.1.0, or a commit SHA
  pub git_ref: String,
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses current config init-fn
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  pub ns_prefix: Option<String>,
  /// include core/library calls in the output
  pub include_core: bool,
  /// maximum depth to traverse (0 = unlimited)
  pub max_depth: usize,
}

/// options of `analyze call-graph --counts`, normalized from `CallGraphCommand`
#[derive(PartialEq, Debug, Clone)]
pub struct CountCallsCommand {
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses init-fn from config
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  pub ns_prefix: Option<String>,
  /// include core/library calls in the count
  pub include_core: bool,
  /// output format: human (default; legacy alias text), edn, or json
  pub format: String,
  /// sort by: "count" (default, descending) or "name"
  pub sort: String,
}

/// compare current snapshot (or one definition) against a Git ref with structured tree diff;
/// use --base to diff two arbitrary refs from git history
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "program-diff")]
pub struct ProgramDiffCommand {
  /// git reference to compare against, e.g. HEAD~1, main, v0.1.0, or a commit SHA
  #[argh(positional)]
  pub git_ref: String,
  /// base git reference for two-ref diff (compare base vs positional ref, both from git history).
  /// When omitted, compares working tree against the positional ref.
  #[argh(option)]
  pub base: Option<String>,
  /// narrow diff to a single definition in format ns/def
  #[argh(option)]
  pub def: Option<String>,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// exit with an error after printing when any definition schema widens a slot (whole Snapshot only; rejected with --def)
  #[argh(switch)]
  pub fail_on_widening: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Query subcommand - project information queries
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "query")]
/// query project and builtin information (namespaces, definitions, configs)
pub struct QueryCommand {
  #[argh(subcommand)]
  pub subcommand: QuerySubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum QuerySubcommand {
  /// list namespaces (or show ns details if namespace provided)
  Ns(QueryNsCommand),
  /// list definitions in a namespace
  Defs(QueryDefsCommand),
  /// read project configs
  Config(QueryConfigCommand),
  /// read .calcit/error.cirru file
  Error(QueryErrorCommand),
  /// read a definition's full code, summary (`--summary`), or examples/tests (`--only`)
  Def(QueryDefCommand),
  /// find symbol across namespaces
  Find(QueryFindCommand),
  /// find usages of a definition
  Usages(QueryUsagesCommand),
  /// search for leaf nodes (strings) in definition
  Search(QuerySearchCommand),
  /// search for structural expressions (Cirru expr or JSON array) in definition
  SearchExpr(QuerySearchExprCommand),
  /// read a definition's schema (type information)
  Schema(QuerySchemaCommand),
  /// inspect a type and its statically available methods
  Type(QueryTypeCommand),
  /// inspect the inferred and expected type at one Snapshot expression path
  TypeAt(QueryTypeAtCommand),
  /// gather bounded semantic context for one definition
  Context(QueryContextCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "schema")]
/// read a definition's schema (type information)
pub struct QuerySchemaCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "type")]
/// inspect a type and list methods available through static dispatch metadata
pub struct QueryTypeCommand {
  /// builtin type annotation (e.g. 'Number or ":: 'List 'Number") or namespace/definition
  #[argh(positional)]
  pub target: String,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "type-at")]
/// inspect static type evidence for an expression at a Snapshot path without running the program
pub struct QueryTypeAtCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// snapshot path, e.g. "code@3.2", "@3.2", or "3.2"
  #[argh(option)]
  pub path: String,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "context")]
/// gather bounded Snapshot metadata, static analysis, dependencies, and usages for one definition
pub struct QueryContextCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// approximate character budget for variable-size content
  #[argh(option, default = "6000")]
  pub budget: usize,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// include references from dependency and core namespaces
  #[argh(switch)]
  pub deps: bool,
  /// maximum number of direct dependencies to include
  #[argh(option, default = "12")]
  pub dependency_limit: usize,
  /// maximum number of usages to include
  #[argh(option, default = "8")]
  pub usage_limit: usize,
  /// maximum number of examples to include
  #[argh(option, default = "3")]
  pub example_limit: usize,
  /// maximum number of definition-attached tests to include
  #[argh(option, default = "3")]
  pub test_limit: usize,
  /// also list core macro/syntax dependencies and the generic Fn methods shared by every function
  #[argh(switch)]
  pub include_core: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ns")]
/// list namespaces, or show ns details if namespace provided
pub struct QueryNsCommand {
  /// namespace to show details (optional, lists all if omitted)
  #[argh(positional)]
  pub namespace: Option<String>,
  /// include dependency and core namespaces
  #[argh(switch)]
  pub deps: bool,
  /// output format: Markdown-compatible human (default), edn, json, or cirru (the namespace's `%{} 'FileEntry` data as stored in the Snapshot, accepted by `edit ns`; generated namespaces such as `<package>.$meta` are not stored and are rejected)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "defs")]
/// list definitions in a namespace
pub struct QueryDefsCommand {
  /// namespace to query
  #[argh(positional)]
  pub namespace: String,
  /// filter definitions that contain this tag (e.g. macro or :macro)
  #[argh(option)]
  pub tag: Option<String>,
  /// show each definition's signature (schema, or its declaration head when untyped) instead of a [schema] marker
  #[argh(switch)]
  pub signatures: bool,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

// read-ns merged into ns command

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "config")]
/// read project configs (init_fn, reload_fn, version)
pub struct QueryConfigCommand {
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "error")]
/// read .calcit/error.cirru file for error stack traces
pub struct QueryErrorCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "def")]
/// read a definition's full code, summary (`--summary`), examples/tests (`--only`), or builtin metadata
pub struct QueryDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// output format: Markdown-compatible human (default), edn, json, or cirru (`quote $ <definition>` for `edit def --overwrite`, or with `--only examples` one `quote $ <example>` per example without JSON AST for `edit meta --examples`)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// show compact signature/doc/schema/cases/counts preview without full body
  #[argh(switch)]
  pub summary: bool,
  /// show only one section of the definition: examples or tests
  #[argh(option)]
  pub only: Option<String>,
  /// preferred nodes per display fragment when large expressions are chunked
  #[argh(option, default = "56")]
  pub chunk_target_nodes: usize,
  /// stop recursive chunk splitting once fragments fall below this node count
  #[argh(option, default = "68")]
  pub chunk_max_nodes: usize,
  /// only enable chunked display when total expression nodes reach this threshold
  #[argh(option, default = "88")]
  pub chunk_trigger_nodes: usize,
  /// only enable chunked display when the formatted definition reaches this many bytes
  #[argh(option, default = "2048")]
  pub chunk_trigger_bytes: usize,
  /// non-chunked Markdown output; use --format cirru for source that can be written back
  #[argh(switch)]
  pub raw: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "find")]
/// find symbol across namespaces (fuzzy match by default; use --exact for precise match)
pub struct QueryFindCommand {
  /// symbol name or pattern to search for (fuzzy match by default)
  #[argh(positional)]
  pub symbol: String,
  /// include dependency namespaces in search
  #[argh(switch)]
  pub deps: bool,
  /// exact match: only match definitions with this exact name
  #[argh(switch)]
  pub exact: bool,
  /// maximum number of results (default 20)
  #[argh(option, default = "20")]
  pub limit: usize,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "usages")]
/// find usages of a definition across the project
pub struct QueryUsagesCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// include dependency namespaces in search
  #[argh(switch)]
  pub deps: bool,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search for leaf nodes across selected sources or a specific namespace/definition (fuzzy match by default)
pub struct QuerySearchCommand {
  /// string pattern to search for in leaf nodes
  #[argh(positional)]
  pub pattern: String,
  /// filter search to specific namespace or namespace/definition (optional)
  #[argh(option, long = "filter")]
  pub filter: Option<String>,
  /// exact match: only match nodes equal to the pattern (default is contains-match)
  #[argh(switch)]
  pub exact: bool,
  /// regex match: treat pattern as a regular expression for leaf node matching
  #[argh(switch, long = "regex")]
  pub regex: bool,
  /// maximum search depth (0 = unlimited)
  #[argh(option, default = "0")]
  pub max_depth: usize,
  /// start search from specific path (dot-separated indices preferred, e.g. "@2.1.0")
  #[argh(option, long = "start-path")]
  pub start_path: Option<String>,
  /// include modules configured for a specific entry in `entries`
  #[argh(option, long = "entry")]
  pub entry: Option<String>,
  /// source scope: project, core, deps, or all (default)
  #[argh(option, default = "String::from(\"all\")")]
  pub source: String,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
  /// also print parent path for each match (strip trailing index for editable node)
  #[argh(switch, long = "parent-path")]
  pub parent_path: bool,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// set the persistent cursor to this zero-based global match index
  #[argh(option, long = "set-cursor")]
  pub set_cursor: Option<usize>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search-expr")]
/// search for structural expressions (Cirru expr or JSON array) across project or in specific namespace/definition (fuzzy match by default)
pub struct QuerySearchExprCommand {
  /// pattern to search for (Cirru one-liner or JSON array with --json)
  #[argh(positional)]
  pub pattern: String,
  /// filter search to specific namespace or namespace/definition (optional)
  #[argh(option, long = "filter")]
  pub filter: Option<String>,
  /// exact match: only match structurally identical expressions (default is prefix/contains match)
  #[argh(switch)]
  pub exact: bool,
  /// maximum search depth (0 = unlimited)
  #[argh(option, default = "0")]
  pub max_depth: usize,
  /// start search from a concrete path or the active cursor
  #[argh(option, long = "start-path")]
  pub start_path: Option<String>,
  /// treat pattern as JSON array instead of Cirru expr
  #[argh(switch)]
  pub json: bool,
  /// include modules configured for a specific entry in `entries`
  #[argh(option, long = "entry")]
  pub entry: Option<String>,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
  /// output format: Markdown-compatible human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// set the persistent cursor to this zero-based global match index
  #[argh(option, long = "set-cursor")]
  pub set_cursor: Option<usize>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Docs subcommand - documentation tools
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "docs")]
/// documentation tools for calcit guidebook and installed module docs
pub struct DocsCommand {
  #[argh(subcommand)]
  pub subcommand: DocsSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum DocsSubcommand {
  /// list available doc scopes (calcit and installed modules)
  Scopes(DocsScopesCommand),
  /// browse remote library registry and read remote library docs
  RemoteLibs(DocsRemoteLibsCommand),
  /// search calcit guidebook or installed module docs by keyword
  Search(DocsSearchCommand),
  /// list available files in calcit guidebook or one installed module
  List(DocsListCommand),
  /// list markdown section headings in one file
  Sections(DocsSectionsCommand),
  /// read markdown content from calcit guidebook or one installed module
  Read(DocsReadCommand),
  /// read the embedded Agents guide or compact mutation contract
  Agents(DocsAgentsCommand),
  /// check ```cirru code blocks in a markdown file via eval
  CheckMd(DocsCheckMdCommand),
  /// format fenced ```cirru code blocks in a markdown file
  FormatMd(DocsFormatMdCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "scopes")]
/// list available doc scopes (calcit and installed modules)
pub struct DocsScopesCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "remote-libs")]
/// browse remote library registry and read remote library docs
pub struct DocsRemoteLibsCommand {
  #[argh(subcommand)]
  pub subcommand: Option<LibsSubcommand>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search calcit guidebook by default, or switch to one installed module with --module
pub struct DocsSearchCommand {
  /// keyword to search
  #[argh(positional)]
  pub keyword: String,
  /// number of context lines to show before and after match (default: 5)
  #[argh(option, default = "5")]
  pub context: usize,
  /// filter by filename (optional)
  #[argh(option)]
  pub filename: Option<String>,
  /// search docs for a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
  /// show only document title and summary (no content snippets)
  #[argh(switch, long = "summary")]
  pub summary: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "list")]
/// list available files in calcit guidebook or one installed module
pub struct DocsListCommand {
  /// limit listing to one installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "sections")]
/// list markdown section headings in one file
pub struct DocsSectionsCommand {
  /// filename to inspect (e.g., "intro.md")
  #[argh(positional)]
  pub filename: String,
  /// read docs from a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
  /// show line numbers in section titles
  #[argh(switch)]
  pub with_lines: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "read")]
/// read markdown content from calcit guidebook by default, or from one installed module with --module
pub struct DocsReadCommand {
  /// filename to read (e.g., "syntax.md")
  #[argh(positional)]
  pub filename: String,
  /// optional section heading keyword(s) for fuzzy match, can pass multiple; omit to read full file
  #[argh(positional)]
  pub headings: Vec<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
  /// read docs from a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
  /// read a line range that skips this many lines (default 0 when --lines is given)
  #[argh(option)]
  pub start: Option<usize>,
  /// number of lines in a line range (default 80 when --start is given)
  #[argh(option)]
  pub lines: Option<usize>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "agents")]
/// read the embedded Agents guide, compact mutation contract, or refreshed remote guide
pub struct DocsAgentsCommand {
  /// heading keyword(s) for fuzzy match, can pass multiple; if omitted, list all markdown headings
  #[argh(positional)]
  pub headings: Vec<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show the compact versioned mutation contract
  #[argh(switch)]
  pub contract: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
  /// force refresh from remote and ignore cache age
  #[argh(switch)]
  pub refresh: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "check-md")]
/// check ```cirru code blocks in a markdown file via eval
pub struct DocsCheckMdCommand {
  /// path to the markdown file to check
  #[argh(positional)]
  pub file: String,
  /// snapshot .cirru file for eval context (default: calcit.cirru)
  #[argh(option, default = "String::from(\"calcit.cirru\")")]
  pub snapshot: String,
  /// retired spelling for --snapshot; --entry selects a named entry elsewhere
  #[argh(option, long = "entry")]
  pub legacy_entry: Option<String>,
  /// extra dependency module path for eval context, can be provided multiple times; defaults to modules from entries.default.modules; paths ending with '/' resolve calcit.cirru and reject retired compact.cirru modules
  #[argh(option)]
  pub dep: Vec<String>,
  /// suppress successful block logs; still prints failures and summary on error
  #[argh(switch)]
  pub quiet: bool,
  /// only display failed blocks and summary; implies --quiet
  #[argh(switch, long = "failures-only")]
  pub failures_only: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "format-md")]
/// format fenced ```cirru code blocks in a markdown file
pub struct DocsFormatMdCommand {
  /// path to the markdown file to format
  #[argh(positional)]
  pub file: String,
  /// report non-canonical blocks without writing the file
  #[argh(switch)]
  pub check: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Cirru subcommand - syntax tools
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "cirru")]
/// Cirru syntax tools (parse, format, edn)
pub struct CirruCommand {
  #[argh(subcommand)]
  pub subcommand: CirruSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum CirruSubcommand {
  /// parse Cirru code to JSON
  Parse(CirruParseCommand),
  /// format JSON to Cirru code
  Format(CirruFormatCommand),
  /// parse Cirru EDN to JSON
  ParseEdn(CirruParseEdnCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "parse")]
/// parse Cirru code to JSON
pub struct CirruParseCommand {
  /// cirru code to parse
  #[argh(positional)]
  pub code: String,
  /// parse input as a single-line Cirru expression (one-liner parser, default is multi-line)
  #[argh(switch, short = 'e', long = "expr-one")]
  pub expr_one_liner: bool,
  /// perform basic syntax validation after parsing (checks keywords, strings, numbers)
  #[argh(switch, long = "validate")]
  pub validate: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "format")]
/// format JSON to Cirru code
pub struct CirruFormatCommand {
  /// JSON data to format (as string)
  #[argh(positional)]
  pub json: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "parse-edn")]
/// parse Cirru EDN to JSON
pub struct CirruParseEdnCommand {
  /// cirru EDN to parse; use --file - to read stdin
  #[argh(positional)]
  pub edn: Option<String>,
  /// read cirru EDN from a file; use - to read stdin
  #[argh(option)]
  pub file: Option<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Remote library subcommands
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum LibsSubcommand {
  /// show README of a library
  Readme(LibsReadmeCommand),
  /// search libraries by keyword
  Search(LibsSearchCommand),
  /// scan markdown files in a module directory
  ScanMd(LibsScanMdCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "readme")]
/// show README of a library from local ~/.config/calcit/modules or GitHub
pub struct LibsReadmeCommand {
  /// package name to look up
  #[argh(positional)]
  pub package: String,
  /// heading keyword(s) for fuzzy match, can pass multiple; if omitted, list markdown headings
  #[argh(positional)]
  pub headings: Vec<String>,
  /// optional file path relative to package directory (e.g., "Skills.md")
  #[argh(option)]
  pub file: Option<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search libraries by keyword in name or description
pub struct LibsSearchCommand {
  /// keyword to search
  #[argh(positional)]
  pub keyword: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "scan-md")]
/// scan markdown files in a module directory
pub struct LibsScanMdCommand {
  /// module name to scan
  #[argh(positional, default = "String::new()")]
  pub module: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Edit subcommand - code editing operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Transport format used when a mutation command receives one syntax node.
#[derive(PartialEq, Eq, Debug, Clone, Copy, Default)]
pub enum SyntaxInputFormat {
  /// Preserve the historical JSON-array/Cirru-quote content detection path.
  #[default]
  Auto,
  /// Cirru EDN whose payload crosses the code/data boundary through `quote`.
  Cirru,
  /// A serialized Cirru AST represented by JSON strings and arrays.
  JsonAst,
}

impl std::fmt::Display for SyntaxInputFormat {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(match self {
      Self::Auto => "auto",
      Self::Cirru => "cirru",
      Self::JsonAst => "json-ast",
    })
  }
}

impl std::str::FromStr for SyntaxInputFormat {
  type Err = String;

  fn from_str(raw: &str) -> Result<Self, Self::Err> {
    match raw {
      "auto" => Ok(Self::Auto),
      "cirru" | "cirru-edn" => Ok(Self::Cirru),
      "json-ast" | "json" => Ok(Self::JsonAst),
      other => Err(format!(
        "Unknown syntax input format `{other}`. Expected `cirru`, `json-ast`, or compatibility mode `auto`."
      )),
    }
  }
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "edit")]
/// coarse-grained code editing (namespaces, definitions, metadata). For internal structural changes within definitions, use the `tree` command.
pub struct EditCommand {
  #[argh(subcommand)]
  pub subcommand: EditSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum EditSubcommand {
  /// rewrite snapshot file in canonical format without semantic changes
  Format(EditFormatCommand),
  /// three-way merge another Snapshot version into this one per definition (Git merge driver)
  Merge(EditMergeCommand),
  /// apply multiple existing edit/tree/config commands against one staged snapshot
  Transaction(EditTransactionCommand),
  /// validate a definition-graph architecture plan and preview scaffold work
  Scaffold(EditScaffoldCommand),
  /// add or update a definition
  Def(EditDefCommand),
  /// move a definition to another namespace
  MvDef(EditMvDefCommand),
  /// delete a definition
  RmDef(EditRmDefCommand),
  /// update definition metadata (doc, tags, examples, test removals)
  Meta(EditMetaCommand),
  /// update definition schema payload (inside quote)
  Schema(EditSchemaCommand),
  /// set or clear host FFI metadata on a definition
  Ffi(EditFfiCommand),
  /// add a named test to a definition
  AddTest(EditAddTestCommand),
  /// add a new namespace
  AddNs(EditAddNsCommand),
  /// delete a namespace
  RmNs(EditRmNsCommand),
  /// write back a namespace's `FileEntry` data from `query ns --format cirru`, updating only changed definitions
  Ns(EditNsCommand),
  /// update namespace imports (replace all)
  Imports(EditImportsCommand),
  /// add a single import rule to namespace
  AddImport(EditAddImportCommand),
  /// remove an import rule from namespace
  RmImport(EditRmImportCommand),
  /// rename a definition within its namespace (no overwrite)
  Rename(EditRenameCommand),
  /// extract a sub-expression into a new definition and replace in-place with the new name
  SplitDef(EditSplitDefCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "format")]
/// rewrite target snapshot file in canonical format
pub struct EditFormatCommand {
  /// remove a reviewed unknown legacy entry field before migrating, as `<entry>.<field>`
  /// (repeatable); each dropped value is reported
  #[argh(option, long = "drop-legacy-entry-field")]
  pub drop_legacy_entry_fields: Vec<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "merge")]
/// three-way merge another Snapshot version into this one per namespace and definition; for Git use
/// `merge.calcit.driver = calcit %A edit merge --base %O --theirs %B`
pub struct EditMergeCommand {
  /// common ancestor Snapshot file
  #[argh(option)]
  pub base: String,
  /// the other side's Snapshot file to merge in
  #[argh(option)]
  pub theirs: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "transaction")]
/// apply multiple existing mutating commands atomically (input via --file, --code, or stdin)
pub struct EditTransactionCommand {
  /// read transaction operations from a Cirru EDN file (JSON is also accepted)
  #[argh(option)]
  pub file: Option<String>,
  /// transaction operations as inline Cirru EDN (JSON is also accepted)
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// require the snapshot content to match this revision before applying
  #[argh(option, long = "expect-revision")]
  pub expect_revision: Option<String>,
  /// validate and preview the transaction without replacing the snapshot
  #[argh(switch, long = "dry-run")]
  pub dry_run: bool,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "scaffold")]
/// preview or atomically create a definition-graph architecture scaffold
pub struct EditScaffoldCommand {
  /// read architecture Cirru EDN from file
  #[argh(option)]
  pub file: Option<String>,
  /// architecture Cirru EDN as inline text
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// require the snapshot content to match this revision before planning
  #[argh(option, long = "expect-revision")]
  pub expect_revision: Option<String>,
  /// validate and preview the scaffold without replacing the snapshot
  #[argh(switch, long = "dry-run")]
  pub dry_run: bool,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

// --- Definition operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "def")]
/// add a new definition (input via --file, --code, or pipe via stdin)
pub struct EditDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// overwrite existing definition if it already exists
  #[argh(switch, long = "overwrite")]
  pub overwrite: bool,
  /// allow an unrecognized definition head; shape and name checks still apply
  #[argh(switch, long = "allow-unknown-head")]
  pub allow_unknown_head: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "mv-def")]
/// move a definition to another namespace or rename it
pub struct EditMvDefCommand {
  /// source in format "namespace/definition"
  #[argh(positional)]
  pub source: String,
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-def")]
/// delete a definition
pub struct EditRmDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "meta")]
/// update definition metadata (`doc`, `tags`, `examples`, `tests` removals)
pub struct EditMetaCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// set definition documentation text verbatim
  #[argh(option)]
  pub doc: Option<String>,
  /// replace tags with a comma-separated list (pass "" to clear)
  #[argh(option)]
  pub tags: Option<String>,
  /// add a tag (repeatable)
  #[argh(option, long = "add-tag")]
  pub add_tags: Vec<String>,
  /// remove a tag (repeatable)
  #[argh(option, long = "rm-tag")]
  pub rm_tags: Vec<String>,
  /// clear all tags
  #[argh(switch, long = "clear-tags")]
  pub clear_tags: bool,
  /// replace all examples from --file, --code, or stdin (one top-level quote per example)
  #[argh(switch, long = "examples")]
  pub examples: bool,
  /// append or insert one example from --file, --code, or stdin
  #[argh(switch, long = "add-example")]
  pub add_example: bool,
  /// insertion index for --add-example (default: append to end)
  #[argh(option, long = "at")]
  pub at: Option<usize>,
  /// clear all examples
  #[argh(switch, long = "clear-examples")]
  pub clear_examples: bool,
  /// read example payload from file (used with --examples or --add-example)
  #[argh(option)]
  pub file: Option<String>,
  /// inline example payload (used with --examples or --add-example)
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format for --add-example: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// remove a named test from the definition (repeatable)
  #[argh(option, long = "rm-test")]
  pub rm_tests: Vec<String>,
  /// require snapshot content to match this revision before writing
  #[argh(option, long = "expect-revision")]
  pub expect_revision: Option<String>,
  /// preview metadata changes without writing the snapshot
  #[argh(switch, long = "dry-run")]
  pub dry_run: bool,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "schema")]
/// update definition schema (input via --file, --code, or pipe via stdin; validates structure before writing)
pub struct EditSchemaCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read one quoted Cirru type node from file
  #[argh(option)]
  pub file: Option<String>,
  /// one quoted Cirru type node; core Option/Result may be short, project nominal types must be qualified
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// remove the schema declaration; does not declare Dynamic or bypass strict checking
  #[argh(switch, long = "clear")]
  pub clear: bool,
  /// add a feature (js-ffi, erased-cache, state or io) to an existing structured Fn schema without replacing its signature
  #[argh(option, long = "add-feature")]
  pub add_feature: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ffi")]
/// update optional host FFI metadata stored on a CodeEntry
pub struct EditFfiCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read a Cirru EDN map from file
  #[argh(option)]
  pub file: Option<String>,
  /// FFI metadata as Cirru EDN map
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// clear FFI metadata
  #[argh(switch, long = "clear")]
  pub clear: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-test")]
/// add a named test to a definition (input via --file, --code, or pipe via stdin)
pub struct EditAddTestCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// stable test name, unique within the definition
  #[argh(positional)]
  pub name: String,
  /// comma-separated test tags
  #[argh(option)]
  pub tags: Option<String>,
  /// read test expression from file
  #[argh(option)]
  pub file: Option<String>,
  /// test expression as inline text
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// replace an existing test with the same name
  #[argh(switch, long = "overwrite")]
  pub overwrite: bool,
}

// --- Namespace operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-ns")]
/// add a new namespace (optional ns syntax via --file, --code, or stdin)
pub struct EditAddNsCommand {
  /// namespace name to create
  #[argh(positional)]
  pub namespace: String,
  /// read ns syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// ns syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-ns")]
/// delete a namespace
pub struct EditRmNsCommand {
  /// namespace to delete
  #[argh(positional)]
  pub namespace: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ns")]
/// write back the `%{} 'FileEntry` data from `query ns <ns> --format cirru`: validate it with the Snapshot loader, compare per
/// definition, and write only added or changed definitions (input via --file, --code, or pipe via stdin)
pub struct EditNsCommand {
  /// namespace whose `:files` entry the data replaces
  #[argh(positional)]
  pub namespace: String,
  /// read the namespace data from file
  #[argh(option)]
  pub file: Option<String>,
  /// namespace data as inline text
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// require the snapshot content (or a scoped revision from a dry-run) to match before writing
  #[argh(option, long = "expect-revision")]
  pub expect_revision: Option<String>,
  /// compare and validate without replacing the snapshot
  #[argh(switch, long = "dry-run")]
  pub dry_run: bool,
  /// delete definitions that are missing from the data
  #[argh(switch, long = "allow-remove")]
  pub allow_remove: bool,
  /// allow unrecognized definition heads in changed or added definitions; shape and name checks still apply
  #[argh(switch, long = "allow-unknown-head")]
  pub allow_unknown_head: bool,
  /// output format: human (default), edn (primary structured data), or json (interoperability)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "imports")]
/// update namespace imports — replaces all (input via --file, --code, or pipe via stdin)
pub struct EditImportsCommand {
  /// namespace to update
  #[argh(positional)]
  pub namespace: String,
  /// read one imports-vector syntax node from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// one imports-vector syntax node as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-import")]
/// add a single import rule to namespace (input via --file, --code, or pipe via stdin)
pub struct EditAddImportCommand {
  /// namespace to add import rule to
  #[argh(positional)]
  pub namespace: String,
  /// read one import-rule node from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// one import-rule node as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// overwrite existing rule for the same source namespace
  #[argh(switch, long = "overwrite")]
  pub overwrite: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-import")]
/// remove an import rule from namespace
pub struct EditRmImportCommand {
  /// namespace to remove import rule from
  #[argh(positional)]
  pub namespace: String,
  /// source namespace to remove (e.g. "calcit.core")
  #[argh(positional)]
  pub source_ns: String,
}

// ========================================================================
// Code command - fine-grained code tree operations
// ========================================================================

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "tree")]
/// fine-grained code tree operations (view and modify AST nodes)
pub struct TreeCommand {
  #[argh(subcommand)]
  pub subcommand: TreeSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum TreeSubcommand {
  Show(TreeShowCommand),
  Replace(TreeReplaceCommand),
  ReplaceLeaf(TreeReplaceLeafCommand),
  Delete(TreeDeleteCommand),
  Insert(TreeInsertCommand),
  Swap(TreeSwapCommand),
  Unwrap(TreeUnwrapCommand),
  Raise(TreeRaiseCommand),
  Wrap(TreeWrapCommand),
  SearchReplace(TreeSearchReplaceCommand),
  Rewrite(TreeStructuralCommand),
}

/// view tree node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "show")]
pub struct TreeShowCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated preferred; e.g. "@2.1.0"); omit to show from root
  #[argh(option)]
  pub path: Option<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
  /// output format: Markdown-compatible human (default), edn, or json (the selected node as a JSON AST document)
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// preferred nodes per display fragment when large expressions are chunked
  #[argh(option, default = "56")]
  pub chunk_target_nodes: usize,
  /// stop recursive chunk splitting once fragments fall below this node count
  #[argh(option, default = "68")]
  pub chunk_max_nodes: usize,
  /// only enable chunked display when total expression nodes reach this threshold
  #[argh(option, default = "88")]
  pub chunk_trigger_nodes: usize,
  /// nested chunk layers to expand beyond ROOT (default 1 shows ROOT + direct chunks only)
  #[argh(option, default = "1")]
  pub chunk_expand_depth: usize,
  /// force raw subtree display without chunking
  #[argh(switch)]
  pub raw: bool,
  /// annotate each nested list with its path index
  #[argh(switch)]
  pub path_annotations: bool,
}

/// rename a definition within its namespace (no overwrite)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rename")]
pub struct EditRenameCommand {
  /// source in format "namespace/definition"
  #[argh(positional)]
  pub source: String,
  /// new definition name (within same namespace)
  #[argh(positional)]
  pub new_name: String,
}

/// extract a sub-expression into a new definition and replace the original location with the new name
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "split-def")]
pub struct EditSplitDefCommand {
  /// source definition in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to extract (dot-separated coordinates, e.g. "@3.2.1")
  #[argh(option, long = "path")]
  pub path: String,
  /// name for the new extracted definition (within the same namespace)
  #[argh(option, long = "name")]
  pub new_name: String,
}

/// rewrite node using references; requires `--with name=path` (use `replace` if no references)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rewrite")]
pub struct TreeStructuralCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// bind placeholder to original-node path: `--with self=.` , `--with rhs=2`
  #[argh(option, long = "with")]
  pub with: Vec<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// find unique leaf node and replace it; if multiple found, returns error with helpful hints
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search-replace")]
pub struct TreeSearchReplaceCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// pattern to search for (exact match on leaf nodes by default; use --regex for regex matching)
  #[argh(option, long = "pattern")]
  pub pattern: String,
  /// treat pattern as a regular expression for matching leaf nodes
  #[argh(switch, long = "regex")]
  pub regex: bool,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
  /// pick the Nth candidate (0-based) when multiple matches are found
  #[argh(option, long = "pick")]
  pub pick: Option<usize>,
  /// semantic path expression to narrow search scope
  /// e.g. "path heading def {} :name |add nth 2 heading let nth 0"
  #[argh(option, long = "selector")]
  pub selector: Option<String>,
}

/// replace node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "replace")]
pub struct TreeReplaceCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// require the current node to equal this quoted Cirru node before replacing
  #[argh(option)]
  pub expect: Option<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// find and replace all matching leaf nodes in definition (no path needed)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "replace-leaf")]
pub struct TreeReplaceLeafCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// pattern to search for (exact match on leaf nodes by default; use --regex for regex matching)
  #[argh(option, long = "pattern")]
  pub pattern: String,
  /// treat pattern as a regular expression for matching leaf nodes
  #[argh(switch, long = "regex")]
  pub regex: bool,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// delete node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "delete")]
pub struct TreeDeleteCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// require the node at path to equal this quoted Cirru node before deleting
  #[argh(option)]
  pub expect: Option<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// insert node relative to the target at a path: --at before, after, prepend-child, or append-child
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "insert")]
pub struct TreeInsertCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the anchor node (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// insert position relative to the anchor: before, after, prepend-child, or append-child
  #[argh(option)]
  pub at: String,
  /// read syntax_tree from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax_tree as inline text; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// require the anchor node to equal this quoted Cirru node before inserting
  #[argh(option)]
  pub expect: Option<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// swap node with a sibling: --with next or prev
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "swap")]
pub struct TreeSwapCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// sibling to swap with: next or prev
  #[argh(option, long = "with")]
  pub with: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// splice all children of a node into its parent (inverse of wrap/rewrite)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "unwrap")]
pub struct TreeUnwrapCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to unwrap (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// replace the parent node with this child node (Paredit raise-sexp)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "raise")]
pub struct TreeRaiseCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the child node to raise (must have at least one element; its parent will be replaced)
  #[argh(option)]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

/// wrap the node at path inside a new expression, using `self` as placeholder for the original node
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "wrap")]
pub struct TreeWrapCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to wrap (dot-separated coordinates, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
  /// wrapping expression with `self` as placeholder for the original node (e.g. 'println self')
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// read wrapping expression from file; select its transport with --input-format
  #[argh(option)]
  pub file: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, default = "2")]
  pub depth: usize,
}

// ========================================================================
// Cursor command - persistent virtual tree selection
// ========================================================================

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "cursor")]
/// maintain the project-local virtual tree cursor
pub struct CursorCommand {
  #[argh(subcommand)]
  pub subcommand: CursorSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum CursorSubcommand {
  Set(CursorSetCommand),
  Show(CursorShowCommand),
  Clear(CursorClearCommand),
  Move(CursorMoveCommand),
  Apply(CursorApplyCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "set")]
/// set the virtual cursor to a definition tree path
pub struct CursorSetCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the selected node (dot-separated, e.g. "@2.1.0")
  #[argh(option)]
  pub path: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "show")]
/// validate and display the current virtual cursor
pub struct CursorShowCommand {
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
  /// preview view: focus (default), node, or full
  #[argh(option, default = "String::from(\"focus\")")]
  pub view: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "clear")]
/// remove the current virtual cursor
pub struct CursorClearCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "move")]
/// move the virtual cursor: parent, child [INDEX] [--last], next, prev, forward, backward, or back
pub struct CursorMoveCommand {
  /// direction: parent, child, next, prev, forward, backward, or back
  #[argh(positional)]
  pub direction: String,
  /// zero-based child index for `child` (defaults to the first child)
  #[argh(positional)]
  pub index: Option<usize>,
  /// enter the last child (only with `child`)
  #[argh(switch)]
  pub last: bool,
  /// steps for next, prev, forward, backward, or back (default 1)
  #[argh(option)]
  pub count: Option<usize>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "apply")]
/// apply a structural tree operation to the active cursor without repeating target or path
pub struct CursorApplyCommand {
  /// operation: delete, swap-next, swap-prev, unwrap (alias splice), raise, replace, wrap, insert-before, insert-after, insert-child, append-child, slurp-next, slurp-prev, barf-last, barf-first, duplicate
  #[argh(positional)]
  pub operation: String,
  /// read the replacement, wrapper, or inserted expression from a file
  #[argh(option)]
  pub file: Option<String>,
  /// replacement, wrapper, or inserted syntax; select its transport with --input-format
  #[argh(option, long = "code")]
  pub code: Option<String>,
  /// syntax-node transport format: cirru, json-ast, or compatibility mode auto
  #[argh(option, long = "input-format", default = "SyntaxInputFormat::Auto")]
  pub input_format: SyntaxInputFormat,
  /// max depth for the underlying tree command result preview
  #[argh(option, default = "2")]
  pub depth: usize,
  /// position of the new copy for `duplicate`: before or after (default)
  #[argh(option)]
  pub at: Option<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Config command — top-level shortcut for configuration management
// ═══════════════════════════════════════════════════════════════════════════════

/// manage project configuration
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "config")]
pub struct ConfigCommand {
  #[argh(subcommand)]
  pub subcommand: ConfigSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum ConfigSubcommand {
  /// show project configuration values and entries
  Show(ConfigShowCommand),
  /// list modules included in the project
  Modules(ConfigModulesCommand),
  /// list entry-level type-slot bindings
  TypeSlots(ConfigTypeSlotsCommand),
  /// set a configuration key to a value (package, mode, target, init-fn, reload-fn, description, feature-policy.<name>); use caps version for project versions
  Set(ConfigSetCommand),
  /// unset target, or remove a named entry with an explicit --entry
  Unset(ConfigUnsetCommand),
  /// create a named entry with a complete configuration, or clone one with --from
  AddEntry(ConfigAddEntryCommand),
  /// add a module path to an entry's modules
  AddModule(ConfigAddModuleCommand),
  /// remove a module path from an entry's modules
  RmModule(ConfigRmModuleCommand),
  /// bind a type slot to a full namespace/definition path
  SetTypeSlot(ConfigSetTypeSlotCommand),
  /// remove an entry-level type-slot binding
  RmTypeSlot(ConfigRmTypeSlotCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "show")]
/// show project configuration values and entries
pub struct ConfigShowCommand {
  /// show a named entry (e.g. "test"); defaults to showing all entries
  #[argh(option)]
  pub entry: Option<String>,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "modules")]
/// list modules included in the project
pub struct ConfigModulesCommand {
  /// list modules for a named entry (e.g. "test"); defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "type-slots")]
/// list entry-level type-slot bindings
pub struct ConfigTypeSlotsCommand {
  /// list bindings for a named entry; defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// output format: human (default), edn, or json
  #[argh(option, default = "String::from(\"human\")")]
  pub format: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "set")]
/// set a configuration key (package, mode, target, init-fn, reload-fn, description, feature-policy.<name>); use caps version for project versions
pub struct ConfigSetCommand {
  /// apply to a named entry (e.g. "test"); defaults to "default"; package is project-level and rejects --entry
  #[argh(option)]
  pub entry: Option<String>,
  /// config key: package, mode, target, init-fn, reload-fn, description, feature-policy.<name>; project versions use caps version
  #[argh(positional)]
  pub key: String,
  /// config value; package is a namespace prefix; target accepts browser|node|native|wasm
  #[argh(positional)]
  pub value: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "unset")]
/// unset target, or remove a named entry with an explicit --entry
pub struct ConfigUnsetCommand {
  /// entry to change; defaults to "default" for target, required and non-default for entry removal
  #[argh(option)]
  pub entry: Option<String>,
  /// config key to unset: target or entry; entry removes the entire named configuration
  #[argh(positional)]
  pub key: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-entry")]
/// create a named entry; without --from, --mode, --init-fn and --reload-fn are required
pub struct ConfigAddEntryCommand {
  /// name of the new entry; must not exist yet
  #[argh(positional)]
  pub name: String,
  /// copy every field (modules, type slots, feature policy included) from an existing entry
  #[argh(option)]
  pub from: Option<String>,
  /// run mode: native or js
  #[argh(option)]
  pub mode: Option<String>,
  /// host target: browser, node, native or wasm
  #[argh(option)]
  pub target: Option<String>,
  /// init function as a full namespace/definition path
  #[argh(option)]
  pub init_fn: Option<String>,
  /// reload function as a full namespace/definition path
  #[argh(option)]
  pub reload_fn: Option<String>,
  /// human-readable purpose of the entry
  #[argh(option)]
  pub description: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-module")]
/// add a module path to an entry
pub struct ConfigAddModuleCommand {
  /// add to a named entry (e.g. "test"); defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// module path to add (e.g. "calcit-test/")
  #[argh(positional)]
  pub module_path: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-module")]
/// remove a module path from an entry
pub struct ConfigRmModuleCommand {
  /// remove from a named entry (e.g. "test"); defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// module path to remove
  #[argh(positional)]
  pub module_path: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "set-type-slot")]
/// bind a type slot to a full namespace/definition path
pub struct ConfigSetTypeSlotCommand {
  /// apply to a named entry; defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// slot name, with or without a leading colon
  #[argh(positional)]
  pub slot: String,
  /// full namespace/definition type path, or :dynamic
  #[argh(positional)]
  pub type_path: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-type-slot")]
/// remove an entry-level type-slot binding
pub struct ConfigRmTypeSlotCommand {
  /// remove from a named entry; defaults to "default"
  #[argh(option)]
  pub entry: Option<String>,
  /// slot name, with or without a leading colon
  #[argh(positional)]
  pub slot: String,
}

#[cfg(test)]
mod wasm_command_tests {
  use super::*;

  #[test]
  fn parses_config_unset_target() {
    let parsed = ToplevelCalcit::from_args(&["calcit"], &["config", "unset", "target"]).expect("parse config unset");
    let Some(CalcitCommand::Config(cmd)) = parsed.subcommand else {
      panic!("expected config subcommand");
    };
    let ConfigSubcommand::Unset(opts) = cmd.subcommand else {
      panic!("expected config unset subcommand");
    };
    assert_eq!(opts.entry, None);
    assert_eq!(opts.key, "target");

    let named = ToplevelCalcit::from_args(&["calcit"], &["config", "unset", "--entry", "server", "target"]).expect("parse named unset");
    let Some(CalcitCommand::Config(cmd)) = named.subcommand else {
      panic!("expected config subcommand");
    };
    let ConfigSubcommand::Unset(opts) = cmd.subcommand else {
      panic!("expected config unset subcommand");
    };
    assert_eq!(opts.entry.as_deref(), Some("server"));
  }

  #[test]
  fn parses_public_wasm_commands_with_distinct_targets() {
    let wasm = ToplevelCalcit::from_args(&["calcit"], &["wasm", "app.cirru", "--emit-path", "target/core", "--check-only"])
      .expect("parse calcit wasm");
    let Some(CalcitCommand::EmitWasm(options)) = wasm.subcommand else {
      panic!("expected wasm subcommand");
    };
    assert_eq!(options.input.as_deref(), Some("app.cirru"));
    assert_eq!(options.emit_path.as_deref(), Some("target/core"));
    assert_eq!(options.boundary, "native");
    assert!(options.check_only);

    let component =
      ToplevelCalcit::from_args(&["calcit"], &["wasm", "app.cirru", "--boundary", "component"]).expect("parse component boundary");
    let Some(CalcitCommand::EmitWasm(options)) = component.subcommand else {
      panic!("expected wasm subcommand");
    };
    assert_eq!(options.boundary, "component");

    let wasi =
      ToplevelCalcit::from_args(&["calcit"], &["wasi", "command.cirru", "--init-fn", "app.main/main!"]).expect("parse calcit wasi");
    let Some(CalcitCommand::EmitWasi(options)) = wasi.subcommand else {
      panic!("expected wasi subcommand");
    };
    assert_eq!(options.input.as_deref(), Some("command.cirru"));
    assert_eq!(options.init_fn.as_deref(), Some("app.main/main!"));
    assert_eq!(options.boundary, "component");
    assert_eq!(options.world, "command");
    assert!(!options.check_only);

    let http = ToplevelCalcit::from_args(&["calcit"], &["wasi", "http.cirru", "--world", "http"]).expect("parse WASI HTTP proxy world");
    let Some(CalcitCommand::EmitWasi(options)) = http.subcommand else {
      panic!("expected wasi subcommand");
    };
    assert_eq!(options.boundary, "component");
    assert_eq!(options.world, "http");
    assert!(!options.emit_core);

    let emit_core_http = ToplevelCalcit::from_args(&["calcit"], &["wasi", "http.cirru", "--world", "http", "--emit-core"])
      .expect("parse WASI HTTP emit-core flag");
    let Some(CalcitCommand::EmitWasi(options)) = emit_core_http.subcommand else {
      panic!("expected wasi subcommand");
    };
    assert_eq!(options.world, "http");
    assert!(options.emit_core);

    let emit_core_cmd =
      ToplevelCalcit::from_args(&["calcit"], &["wasi", "command.cirru", "--emit-core"]).expect("parse WASI command emit-core flag");
    let Some(CalcitCommand::EmitWasi(options)) = emit_core_cmd.subcommand else {
      panic!("expected wasi subcommand");
    };
    assert_eq!(options.world, "command");
    assert!(options.emit_core);

    let preview1 = ToplevelCalcit::from_args(&["calcit"], &["wasi", "command.cirru", "--boundary", "native"])
      .expect("parse WASI Preview 1 command boundary");
    let Some(CalcitCommand::EmitWasi(options)) = preview1.subcommand else {
      panic!("expected wasi subcommand");
    };
    assert_eq!(options.boundary, "native");
  }

  #[test]
  fn parses_keep_going_check_report_options() {
    let command = ToplevelCalcit::from_args(&["calcit"], &["app.cirru", "--check-only", "--keep-going", "--format", "edn"])
      .expect("parse keep-going strict check");
    assert_eq!(command.input, "app.cirru");
    assert!(command.check_only);
    assert!(command.keep_going);
    assert_eq!(command.format, "edn");
  }

  #[test]
  fn parses_incremental_check_only_option() {
    let command =
      ToplevelCalcit::from_args(&["calcit"], &["app.cirru", "--check-only", "--incremental"]).expect("parse incremental strict check");
    assert_eq!(command.input, "app.cirru");
    assert!(command.check_only);
    assert!(command.incremental);
    assert!(!command.keep_going);
  }

  #[test]
  fn parses_all_defs_check_only_option() {
    let command = ToplevelCalcit::from_args(&["calcit"], &["app.cirru", "--check-only", "--all-defs", "--format", "edn"])
      .expect("parse all-definitions strict check");
    assert!(command.check_only);
    assert!(command.all_defs);
    assert!(!command.summary_only);
    assert_eq!(command.format, "edn");
  }

  #[test]
  fn parses_all_defs_summary_only_check_only_option() {
    let command = ToplevelCalcit::from_args(
      &["calcit"],
      &["app.cirru", "--check-only", "--all-defs", "--summary-only", "--format", "edn"],
    )
    .expect("parse all-definitions summary-only strict check");
    assert!(command.check_only);
    assert!(command.all_defs);
    assert!(command.summary_only);
    assert_eq!(command.format, "edn");
  }
}