ignition-cli 1.6.6

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

use std::path::PathBuf;

use clap::{ArgAction, Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(
    name = "ign",
    version,
    propagate_version = true,
    about = "Operate Ignition 8.3+ gateways from the terminal"
)]
pub struct Cli {
    /// Gateway profile to use (default: active profile in config)
    #[arg(long, global = true, value_name = "NAME")]
    pub profile: Option<String>,

    /// Machine-readable JSON output (stable field names)
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub json: bool,

    /// One-line compact JSON (implies --json)
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub compact: bool,

    /// Non-interactive confirmation for destructive operations
    #[arg(long, short = 'y', global = true, action = ArgAction::SetTrue)]
    pub yes: bool,

    /// Increase diagnostics (-vv for HTTP trace) to stderr
    #[arg(long, short = 'v', global = true, action = ArgAction::Count)]
    pub verbose: u8,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Print version information (CLI always; gateway check when a profile resolves)
    Version,

    /// Generate shell completions (bash, zsh, fish, …) — the one stdout exception
    #[command(arg_required_else_help = true)]
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::aot::Shell,
    },

    /// Gateway status: identity, platform, uptime, license (incl. trial countdown)
    Status,

    /// List gateway modules (healthy by default)
    Modules {
        /// Show quarantined modules instead of healthy ones
        #[arg(long)]
        quarantined: bool,
    },

    /// Gateway performance metrics (current gauges + thread counts)
    Metrics {
        /// Include historic chart datapoints
        #[arg(long)]
        history: bool,
    },

    /// List gateway sessions (designers, Perspective, Vision) — or
    /// terminate one via the `terminate` subcommand
    Sessions(SessionsArgs),

    /// List database/OPC connections with healthcheck status as reported
    Connections {
        /// Filter to one connection family (default: both)
        #[arg(long, value_enum)]
        r#type: Option<ConnectionType>,
    },

    /// Query, tail, and download gateway logs; manage logger levels
    Logs(LogsArgs),

    /// Restart the gateway — destructive, refused without --yes;
    /// --wait polls until RUNNING
    Restart {
        /// Wait for the gateway to return to RUNNING (POST, then poll
        /// /StatusPing)
        #[arg(long)]
        wait: bool,
        /// Wait budget in seconds (default 300)
        #[arg(long, value_name = "SECS")]
        timeout: Option<u64>,
        /// Poll interval in seconds (default 2)
        #[arg(long, value_name = "SECS")]
        interval: Option<u64>,
    },

    /// Wait for a gateway state (readiness, restart completion, module)
    #[command(arg_required_else_help = true)]
    Wait(WaitArgs),

    /// Diagnose the gateway setup: URL, liveness, commissioning, auth,
    /// permissions, write, WebDev route, rig — exits 0 whenever the
    /// diagnosis completes (failing checks are data)
    Doctor {
        /// Probe write permission (POST scan/projects — a harmless
        /// project rescan)
        #[arg(long)]
        check_write: bool,
        /// Probe one WebDev route's presence (/system/webdev/<NAME>)
        #[arg(long, value_name = "NAME")]
        webdev_route: Option<String>,
    },

    /// Adopt this profile's gateway: native login → mint an
    /// Administrator-level API key (idempotent by name) → wire the
    /// gateway's permissions → live-probe the key (read and write) →
    /// persist the credential (OS keyring, env-var fallback). Write
    /// access is granted only to the write levels (never a bare
    /// Authenticated, which every API key holds); --read-only mints a
    /// key that is proven refused write; --restrict-write removes the
    /// bare Authenticated write entry an earlier adopt left behind.
    /// Re-run on an adopted gateway is an all-skip no-op. Composition
    /// flags ride the bootstrap: --project deploys the CLI's WebDev
    /// routes, --checkout lands every enabled project locally, --bake
    /// saves a restore-ready gwbk
    Adopt {
        /// Gateway login user for the native OIDC dance
        /// (default: admin)
        #[arg(long, value_name = "NAME")]
        user: Option<String>,

        /// The API-key name — the idempotency key (default: ign-cli)
        #[arg(long, value_name = "NAME")]
        key_name: Option<String>,

        /// The granted security level as a slash path
        /// (default: Authenticated/Roles/Administrator)
        #[arg(long, value_name = "PATH")]
        level: Option<String>,

        /// A level to add to the gateway's write permissions and grant
        /// to the key, as a slash path (repeatable; default:
        /// Authenticated/IgnCliWrite). A bare Authenticated or Public
        /// is refused: every API key would be able to write
        #[arg(long = "write-level", value_name = "PATH")]
        write_level: Vec<String>,

        /// Mint a key at --level that the gateway refuses writes
        /// (a check token). Needs its own --key-name (not the default
        /// ign-cli, the write key). Never touches the write permissions;
        /// refuses before minting when they already admit every key
        #[arg(long, conflicts_with_all = ["write_level", "restrict_write"])]
        read_only: bool,

        /// Remove the bare Authenticated entry from the gateway's write
        /// permissions after the write levels are in place (opt-in;
        /// other API keys that relied on it lose write access)
        #[arg(long)]
        restrict_write: bool,

        /// Deploy the CLI's WebDev routes (scriptExec on) into this
        /// project after the bootstrap
        #[arg(long, value_name = "NAME")]
        project: Option<String>,

        /// Ship the embedded TESTING bundle with the routes (the
        /// Jython framework + testing/run|tags routes + the smoke
        /// sentinel; the step asserts discover ≥1 module and a green
        /// smoke run — the empty-suite trap)
        #[arg(long, requires = "project")]
        testing: bool,

        /// Check out every enabled project into DIR/<project>
        /// (scripts decoded — grep/lint ready); existing targets skip
        #[arg(long, value_name = "DIR")]
        checkout: Option<String>,

        /// Download a roaming gwbk to FILE after everything landed —
        /// a gateway reset restored from it keeps the key and routes
        #[arg(long, value_name = "FILE")]
        bake: Option<String>,
    },

    /// Obtain a live gateway login session (the native OIDC dance) —
    /// returns the session cookie name/value, the CSRF token, the
    /// gateway URL, and a ready-to-use Playwright `storageState`
    /// document. The session material is emitted ONLY under the
    /// global --json flag; the human render prints the cookie name
    /// and the gateway URL and withholds the rest
    #[command(arg_required_else_help = true)]
    Session(SessionArgs),

    /// Manage gateway projects: list with inheritance info, new, copy,
    /// rename, set (reparent), delete, export/import (ZIP)
    #[command(arg_required_else_help = true)]
    Project(ProjectArgs),

    /// Check out a project's resources to a local tree, inspect drift,
    /// push guarded changes — the local edit loop over the
    /// project-export interchange (project RESOURCES only; tag values
    /// never appear in the tree — tags remain `ign tags` verbs)
    #[command(arg_required_else_help = true)]
    Workspace(WorkspaceArgs),

    /// Declared gateway deploy: `render` turns a repo's
    /// `gateways/<name>/` tree into the bytes the gateway holds on
    /// disk for one environment — offline (no profile, no network, no
    /// credentials), deterministic, with a `render_sha256` digest
    #[command(arg_required_else_help = true)]
    Deploy(DeployArgs),

    /// Fetch a gateway resource, edit it in $EDITOR, push back
    /// (guarded) — the kubectl-edit loop over ONE resource:
    /// unchanged saves are clean no-ops (nothing pushed, never
    /// prompted), a gateway changed since fetch refuses (never
    /// force-pushed), a JSON-breaking save refuses fail-closed with
    /// the temp tree kept (path printed). Zero stdout in every mode —
    /// the editor owns the terminal (see README's edit section)
    Edit(EditArgs),

    /// Manage a project's individual resources: list, get, put,
    /// delete — the surgical edit loop (change one view/script
    /// without re-importing everything)
    #[command(arg_required_else_help = true)]
    Resource(ResourceArgs),

    /// Manage the CLI's own WebDev routes on the gateway: deploy the
    /// embedded bundle, verify the version handshake
    #[command(arg_required_else_help = true)]
    Webdev(WebdevArgs),

    /// Tag operations: manage providers (native REST) and browse /
    /// read / write tag values (the deployed WebDev routes — run
    /// `ign webdev deploy` first)
    #[command(arg_required_else_help = true)]
    Tags(TagsArgs),

    /// Manage a Docker compose rig: up/down/reset/status/logs/trial
    /// (snapshot arrives in a later plan) — docker-only, no profile
    /// needed
    #[command(arg_required_else_help = true)]
    Rig(RigArgs),

    /// Manage gateway backups (gwbk) on any profiled gateway:
    /// download (streamed) and restore (guarded)
    #[command(arg_required_else_help = true)]
    Backup(BackupArgs),

    /// EAM task orchestration (Enterprise Administration Module):
    /// history/definitions reads, guarded task create + force —
    /// every verb honestly reports the controller-mode state gate
    #[command(arg_required_else_help = true)]
    Eam(EamArgs),

    /// Run gateway-side Python (Jython) through the secret-gated
    /// scriptExec route — the opt-in is STRUCTURAL (`ign webdev
    /// deploy --with-script-exec` deploys the route + persists its
    /// secret); there is no --yes on this verb by design
    #[command(arg_required_else_help = true)]
    Script(ScriptArgs),

    /// Run the gateway's own Jython test suite through the deployed
    /// testing bundle — the agent/CI verb: a machine verdict without
    /// the Designer (`ign webdev deploy --with-testing` or
    /// `ign adopt --project NAME --testing` installs the bundle)
    #[command(arg_required_else_help = true)]
    Testing(TestingArgs),

    /// JVM profiling — a SPECIAL MODE, not a routine diagnostic:
    /// these verbs ACTIVELY instrument the gateway JVM (stack
    /// sampling burns CPU; flight recordings buffer JVM memory and
    /// dump to gateway disk). NEVER use against a production server
    /// outside an approved change window with a rollback plan. The
    /// intrusive verbs require --i-accept-the-risk — the global
    /// --yes deliberately does NOT satisfy that gate
    #[command(arg_required_else_help = true)]
    Jvm(JvmArgs),

    /// Lint local project files by delegating to ignition-lint (PATH
    /// discovery) — doctor posture: findings are DATA, exit 0
    /// whenever the tool ran; --strict passes the tool's exit code
    /// through for CI
    Lint(LintArgs),

    /// Browser end-to-end testing: diagnose the host + gateway a
    /// Playwright suite needs (`doctor`), and scaffold one that logs
    /// in through `ign session login` and talks to the gateway's
    /// testing routes (`init`). There is no `e2e run` — the
    /// scaffold's own `npm test` is the runner
    #[command(arg_required_else_help = true)]
    E2e(E2eArgs),

    /// Raw passthrough to any gateway REST endpoint — the escape
    /// hatch for the uncurated routes (the envelope's `data` is left
    /// gateway-verbatim; see README's documented contract exception)
    #[command(arg_required_else_help = true)]
    Api(ApiArgs),

    /// License inventory + trial state — the morning-check read
    /// (trial companion merged into one command)
    #[command(arg_required_else_help = true)]
    License(LicenseArgs),

    /// Gateway redundancy status — the morning-check read
    #[command(arg_required_else_help = true)]
    Redundancy(RedundancyArgs),

    /// Gateway Area Network (GAN) overview — the morning-check read
    #[command(arg_required_else_help = true)]
    Gan(GanArgs),

    /// Diagnostics support-bundle operations: generate, check
    /// status, download (streamed), wait — the support-bundle slice
    #[command(arg_required_else_help = true)]
    Diagnostics(DiagnosticsArgs),

    /// Manage gateway profiles
    #[command(arg_required_else_help = true)]
    Profile(ProfileArgs),

    /// Serve the Model Context Protocol over stdio (hidden; for MCP
    /// clients — the newline-delimited JSON-RPC 2.0 stream IS the
    /// stdout product; the routes.rs OutOfBand row lands atomically
    /// with this command, 08-06 contract)
    #[command(hide = true)]
    Mcp(McpArgs),

    /// Serve LSP over stdio (hidden; for ignition-nvim — the
    /// Content-Length-framed LSP stream IS the stdout product; the
    /// routes.rs OutOfBand row lands atomically with this command,
    /// 08-06 contract)
    #[command(hide = true)]
    Lsp,

    /// Interactive TUI cockpit
    #[cfg(feature = "tui")]
    Tui,

    /// Live gateway monitor — htop for Ignition: cpu/heap gauges,
    /// sparkline history, and a sortable/filterable table of the
    /// gateway's live entities (modules, sessions, connections,
    /// providers); terminate a session with `x` (the routes.rs
    /// Dashboard row lands atomically with this command)
    #[cfg(feature = "tui")]
    #[command(alias = "itop")]
    Top,
}

/// Hidden args for `ign mcp serve` (14-01). `serve` is a RESTRICTED
/// POSITIONAL — not a subcommand — so the clap walk (tui_coverage.rs)
/// yields exactly ONE row-requiring node, `mcp` itself: an `mcp
/// serve` subcommand leaf would need a second routes() row and extend
/// the pinned OutOfBand set past its four-member contract (an orphan
/// row fails the walk by design). clap's `value_parser = ["serve"]`
/// keeps every other spelling (`ign mcp`, `ign mcp bogus`) a
/// usage-class clap error — exit 2 BEFORE any protocol byte is
/// written. Zero stdout-facing behavior here — the mode owns its own
/// I/O entirely (`mcp::serve`).
#[derive(Debug, clap::Args)]
pub struct McpArgs {
    /// Start the stdio MCP server
    #[arg(value_parser = ["serve"], value_name = "SERVE")]
    pub serve: String,
}

/// Wait targets (02-05, HLTH-11). `gateway` and `restart` poll the
/// UNAUTHENTICATED /StatusPing (the dispatch builds a header-less
/// client for them — waiting must work when auth is broken); `module`
/// is an authed read.
#[derive(Debug, clap::Args)]
pub struct WaitArgs {
    #[command(subcommand)]
    pub command: WaitCmd,
}

#[derive(Debug, Subcommand)]
pub enum WaitCmd {
    /// Wait until the gateway reports RUNNING (unauthenticated
    /// StatusPing — works even when auth is broken or absent)
    Gateway {
        /// Poll interval in seconds
        #[arg(long, default_value_t = 2, value_name = "SECS")]
        interval: u64,
        /// Give up after this many seconds
        #[arg(long, default_value_t = 120, value_name = "SECS")]
        timeout: u64,
    },
    /// Wait for a restart to complete — restart-aware: shares
    /// `restart --wait`'s semantics (non-RUNNING observed once →
    /// RUNNING; a 5 s floor guards the all-RUNNING case)
    Restart {
        /// Poll interval in seconds
        #[arg(long, default_value_t = 2, value_name = "SECS")]
        interval: u64,
        /// Give up after this many seconds (default 300)
        #[arg(long, default_value_t = 300, value_name = "SECS")]
        timeout: u64,
    },
    /// Wait until a module reports ACTIVE
    Module {
        /// Module id (see `ign modules`)
        id: String,
        /// Poll interval in seconds
        #[arg(long, default_value_t = 2, value_name = "SECS")]
        interval: u64,
        /// Give up after this many seconds
        #[arg(long, default_value_t = 120, value_name = "SECS")]
        timeout: u64,
    },
}

/// Project subcommands (03-01, PROJ-01/02). `delete` is the family's
/// ONE destructive verb (`--yes`-guarded, exit 2 without); copy/
/// rename/set create or relabel — never destroy — so they carry NO
/// guard (planner decision per research).
#[derive(Debug, clap::Args)]
pub struct ProjectArgs {
    #[command(subcommand)]
    pub command: ProjectCommand,
}

#[derive(Debug, Subcommand)]
pub enum ProjectCommand {
    /// List every runnable project: name, title, enabled, parent,
    /// inheritable (inheritance info from the items themselves)
    List,
    /// Create a project (only provided fields ride the create body)
    New {
        /// Project name
        name: String,
        /// Display title
        #[arg(long, value_name = "TEXT")]
        title: Option<String>,
        /// Long description
        #[arg(long, value_name = "TEXT")]
        description: Option<String>,
        /// Parent project (inheritance)
        #[arg(long, value_name = "NAME")]
        parent: Option<String>,
        /// Mark this project eligible as a parent
        #[arg(long)]
        inheritable: bool,
        /// Create the project disabled
        #[arg(long)]
        disabled: bool,
    },
    /// Copy a project with all its resources
    Copy {
        /// Source project name
        src: String,
        /// Destination name (must not exist)
        dst: String,
    },
    /// Rename a project (native rename, not copy+delete)
    Rename {
        /// Current name
        old_name: String,
        /// New name
        new_name: String,
    },
    /// Set project fields — --parent IS the inheritance move (reparent)
    #[command(group(
        clap::ArgGroup::new("set_fields")
            .required(true)
            .multiple(true)
            .args(&["title", "description", "parent", "set_enabled", "disabled", "inheritable"])
    ))]
    Set {
        /// Project name
        name: String,
        /// Display title
        #[arg(long, value_name = "TEXT")]
        title: Option<String>,
        /// Long description
        #[arg(long, value_name = "TEXT")]
        description: Option<String>,
        /// Parent project (reparent)
        #[arg(long, value_name = "NAME")]
        parent: Option<String>,
        /// Enable the project
        #[arg(long, conflicts_with = "disabled")]
        set_enabled: bool,
        /// Disable the project
        #[arg(long)]
        disabled: bool,
        /// Whether this project may serve as a parent (true/false)
        #[arg(long, value_name = "BOOL")]
        inheritable: Option<bool>,
    },
    /// Delete a project — destructive, refused without --yes
    Delete {
        /// Project name
        name: String,
    },
    /// Export a project as a ZIP archive (streams to disk)
    Export {
        /// Project name
        name: String,
        /// Output file (default: the gateway's Content-Disposition
        /// name, else <name>.zip); with --decode-scripts, the output
        /// DIRECTORY (default <name>-export/)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Also decode embedded JSON scripts (Perspective view.json
        /// etc.) into editable `<member>.<n>.py` sidecars beside a
        /// copied member tree + scripts-manifest.json — the output is
        /// a DIRECTORY (script-python members are already plain .py
        /// and never decode; expressions pass through)
        #[arg(long)]
        decode_scripts: bool,
    },
    /// Import a project from a ZIP archive
    Import {
        /// Project name to import as
        name: String,
        /// ZIP file path, or - to read the archive from stdin; with
        /// --encode-scripts, a decoded export DIRECTORY (re-zipped
        /// with the sidecars spliced back before upload; stdin is
        /// invalid in that mode)
        #[arg(long, value_name = "PATH")]
        file: String,
        /// Collision policy: abort refuses when the name exists
        /// (default); overwrite REPLACES the entire project —
        /// destructive, requires --yes. merge is Designer-only (not a
        /// value; the README documents why)
        #[arg(long, value_enum, default_value_t = CollisionPolicy::Abort)]
        collision_policy: CollisionPolicy,
        /// --file points at a decoded export DIRECTORY (from
        /// `export --decode-scripts`): the sidecars are spliced back
        /// and the manifest stripped before the standard import path
        #[arg(long)]
        encode_scripts: bool,
    },
    /// Compare a project across two gateway profiles — statuses are
    /// B-relative-to-A (`added` = in B only, `removed` = in A only,
    /// `changed` = differing after resource.json normalization)
    Diff {
        /// Baseline profile (A)
        profile_a: String,
        /// Compared profile (B — the diff is B relative to A)
        profile_b: String,
        /// Project name
        #[arg(long, value_name = "NAME")]
        project: String,
    },
    /// Promote selected resources from profile A into profile B
    /// (direction is ALWAYS A→B) — destructive on B: the whole
    /// project is overwrite-imported, refused without --yes
    Sync {
        /// Source profile (A)
        profile_a: String,
        /// Target profile (B)
        profile_b: String,
        /// Project name
        #[arg(long, value_name = "NAME")]
        project: String,
        /// Resource user path to promote (repeatable)
        #[arg(long, value_name = "PATH")]
        resource: Vec<String>,
        /// Promote every resource the diff reports added or changed
        /// (never removed ones — deletion needs --delete)
        #[arg(long)]
        all_changed: bool,
        /// Also remove B's resources the diff reports removed
        /// (default: upsert-only, nothing is ever deleted)
        #[arg(long)]
        delete: bool,
    },
}

/// Workspace subcommands (13-07): the local edit loop. `checkout`
/// writes the mapped tree + records `.ign-workspace.json` (the
/// manifest IS the workspace identity — status/push read it and the
/// user never re-types the project); `status` reports PUSH-RELATIVE
/// drift (every row says what push would do); `push` is the guarded
/// splice of local edits into a FRESH gateway export.
#[derive(Debug, clap::Args)]
pub struct WorkspaceArgs {
    #[command(subcommand)]
    pub command: WorkspaceCommand,
}

#[derive(Debug, Subcommand)]
pub enum WorkspaceCommand {
    /// Check out a project's resources to a local tree — mapped
    /// paths + the recorded `.ign-workspace.json` manifest + an
    /// idempotent `.gitignore` (manifest committed; codec artifacts
    /// ignored). Read-only on the wire: one export GET, zero imports.
    Checkout {
        /// Project name to check out
        project: String,
        /// Target directory for the workspace tree (created if
        /// absent; an unrelated non-empty directory refuses — never
        /// clobbered)
        target: PathBuf,
        /// Decode embedded JSON scripts to editable .py sidecars
        /// (nvim-editable; encodes back cleanly — an unedited
        /// re-encode is byte-exact; `scripts-manifest.json` keys the
        /// splice)
        #[arg(long)]
        decode_scripts: bool,
    },
    /// Report workspace drift against the gateway — states are
    /// PUSH-RELATIVE (each row names what push would do: write /
    /// leave / refuse); the project comes from the workspace
    /// manifest, never re-typed. Read-only: one export GET.
    Status {
        /// Workspace root (default: the current directory)
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Push local edits to the gateway — guarded (refused without
    /// --yes; the refusal message IS the blast-radius preview);
    /// conflicts refuse EVEN WITH --yes (manual reconciliation);
    /// deletions need --delete (default: reported, skipped);
    /// untracked files are never imported; an empty selection
    /// writes nothing.
    Push {
        /// Workspace root (default: the current directory)
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Also delete gateway members removed locally (default:
        /// reported, skipped)
        #[arg(long)]
        delete: bool,
    },
}

/// `ign deploy` args (21-04): the declared gateway deploy family.
#[derive(Debug, clap::Args)]
pub struct DeployArgs {
    #[command(subcommand)]
    pub command: DeployCommand,
}

#[derive(Debug, Subcommand)]
pub enum DeployCommand {
    /// Render `gateways/<name>/` for one environment into the bytes
    /// the gateway holds on disk — offline (no profile, no network,
    /// no credentials). Reports file and byte counts and the
    /// `render_sha256` digest; refuses an invalid tree with
    /// `deploy_tree_invalid`
    Render {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// Also write the rendered tree and a `render.json` marker to
        /// this directory: absent, empty, or a previous render of the
        /// same gateway and environment. Never deletes; anything else
        /// is refused (`invalid_input`) before any write
        #[arg(long, value_name = "DIR")]
        out: Option<PathBuf>,
    },
    /// Plan one environment: compare the rendered tree with the master
    /// node's live `config/resources/` files and report each unit as
    /// added, changed, removed, same or unmanaged. Read-only; exits 0
    /// whether or not anything changed. Reads the host through the
    /// master's `ssh` or `local` block; resolves no gateway session
    Plan {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// A directory written by `deploy render --out`: a previous render
        /// of this gateway, environment and mode. It is re-hashed, never
        /// trusted; a base that is modified, incomplete or of another
        /// gateway is refused (`invalid_input`). Each entry then carries
        /// `drift`: true when a live file differs from both the base and
        /// the desired tree
        #[arg(long, value_name = "DIR")]
        base: Option<PathBuf>,
        /// Add a unified text diff (live against desired, 3 lines of
        /// context, at most 65536 bytes per unit) to added, changed and
        /// removed entries. Members that hold, or may hold, a secret are
        /// withheld and print only their sha256 values; non-JSON members
        /// print only that they differ
        #[arg(long)]
        diff: bool,
    },
    /// Bootstrap `gateways/<name>/` from the master node's live tree.
    /// Read-only against the gateway: it reads the host through the
    /// master's `ssh` or `local` block and writes only the local repo.
    /// `core` files go to `resources/` and `tags/`, the target mode
    /// collection's files to `modes/<ENV>/`. Units that hold a secret or
    /// that render would not reproduce byte for byte are skipped and listed
    /// with a reason; the next `plan` reports them as unmanaged. Replacing a
    /// non-empty `resources/`, `tags/` or `modes/<ENV>/` needs the global
    /// `--yes`; `manifest.yaml` and other environments are never touched
    Pull {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
    },
    /// Verify that the master gateway runs what the target declares:
    /// no scan running, the target's deployment mode, every declared
    /// resource read back equal over REST, tag-unit files byte-equal on the
    /// host, no `will not be loaded` WARN for a declared resource, and the
    /// manifest's tag probes reading Good. Read-only: no scan is triggered,
    /// no lock is taken, nothing is written. Resolves the master's profile
    /// through the normal secret chain. Prints a verdict: exit 0 when green,
    /// exit 6 with `data.slug` `deploy_verify_failed` when red
    Verify {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// The project hosting the WebDev `tags` route used for the tag
        /// probes
        #[arg(long, value_name = "NAME", default_value = "ign-cli")]
        project: String,
        /// Which node to verify: `master` (the default) runs the six master
        /// checks; `backup` runs only the backup node's checks (redundancy
        /// linked, mode, REST read-back, files against the master's live
        /// copy, and the secret names the render references); `both` runs
        /// the master's checks, then the backup's. Needs `nodes.backup` for
        /// `backup` and `both`. Verify never waits, never resyncs and never
        /// writes
        #[arg(long, value_enum, value_name = "NODE", default_value = "master")]
        node: VerifyNodeArg,
    },
    /// Apply one environment: write the declared tree into the master
    /// node's mode collection under the gateway scan-lock, scan, then verify
    /// it; a red verify restores the pre-apply snapshot automatically
    /// (`data.outcome` `rolled_back`, `data.slug` `deploy_rolled_back`, exit
    /// 6). When the target has `nodes.backup`, the apply then waits for the
    /// backup node to converge (`--backup-timeout`), sends at most one resync
    /// to the master, and reports `data.backup`; a backup that cannot be
    /// proven ends `data.outcome` `applied_backup_unsynced`, `data.slug`
    /// `deploy_backup_unsynced`, exit 6, with the master left applied.
    /// Guarded: without the global `--yes` it exits 2
    /// `confirmation_required` and the message IS the plan (the changing
    /// entries, the delete-set count and `plan_sha256`). `--plan-sha256`
    /// binds the apply to the plan that was reviewed: a changed plan exits 6
    /// `plan_stale`, and with `--json` or without a terminal the flag is
    /// required. Takes a `.gwbk` backup first (`--skip-gwbk` records that it
    /// did not). One fixed lock hold serves every target; a change of 1,528 or
    /// more files (writes plus deletes) is refused by the `hold_budget`
    /// preflight. There is no flag that skips the plan hash, the verify or
    /// the rollback. Staging a large tree is silent on the wire and can take
    /// minutes; in human mode progress lines go to stderr
    Apply {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// A directory written by `deploy render --out`: a previous render
        /// of this gateway, environment and mode. Enables the drift gate: a
        /// live file that differs from both the base and the desired tree
        /// refuses the apply (`destructive_change_refused`, exit 2) unless
        /// `--allow-drift` gives a reason. An entry that a `core` copy
        /// shadows is refused whatever the flags (`deploy_blocked`, exit 6)
        #[arg(long, value_name = "DIR")]
        base: Option<PathBuf>,
        /// The project hosting the WebDev `tags` route the post-apply verify
        /// uses for the tag probes, as in `deploy verify`
        #[arg(long, value_name = "NAME", default_value = "ign-cli")]
        project: String,
        /// The `plan_sha256` of the plan that was reviewed. A different
        /// current plan refuses the apply (`plan_stale`, exit 6). Required
        /// with `--json` or when stdin or stdout is not a terminal
        #[arg(long, value_name = "HASH")]
        plan_sha256: Option<String>,
        /// Allow a plan that deletes or replaces something destructive; the
        /// plan lists each such entry. Without it the apply is refused
        /// (`destructive_change_refused`, exit 2)
        #[arg(long)]
        allow_destructive: bool,
        /// Go ahead over drifted entries (live changed since the `--base`
        /// render) and record this reason in the run record (at most 500
        /// characters)
        #[arg(long, value_name = "REASON")]
        allow_drift: Option<String>,
        /// What to do about open Designer sessions: `fail` refuses while any
        /// is open, `wait` polls until none is or `--designers-timeout`
        /// passes, `proceed` goes ahead and records the sessions
        #[arg(long, value_enum, value_name = "MODE", default_value = "fail")]
        designers: DesignersArg,
        /// Seconds `--designers wait` polls before it refuses
        #[arg(
            long,
            value_name = "SECS",
            default_value_t = 600,
            value_parser = clap::value_parser!(u64).range(1..=86400)
        )]
        designers_timeout: u64,
        /// Take no `.gwbk` backup; the run record states that none was taken
        #[arg(long)]
        skip_gwbk: bool,
        /// Seconds to wait for the backup node to converge after the master
        /// is verified; then one resync is sent to the master and the wait
        /// repeats once. Only used when the target has nodes.backup
        #[arg(
            long,
            value_name = "SECS",
            default_value_t = 300,
            value_parser = clap::value_parser!(u64).range(1..=86400)
        )]
        backup_timeout: u64,
    },
    /// Roll back one past run by id, from a fresh process: restore the
    /// on-box snapshot the run took into the master node's mode collection,
    /// delete the files the run created, scan, and record the rollback (a
    /// run directory of its own, `kind: rollback`). The run id is
    /// `data.run_id` of the `deploy apply` that made it, or its run
    /// directory's name. Also recovers an interrupted run: a refusal that
    /// prints `ign deploy rollback --run <id> --env <env>` names the id to
    /// pass. Guarded: without the global `--yes` it exits 2
    /// `confirmation_required` and the message names the run, the gateway,
    /// the mode and how many files it would restore and delete. A file
    /// changed since the run refuses (`deploy_live_changed`, exit 6) unless
    /// `--discard-live-changes`. One fixed lock hold (176 s) serves the
    /// rollback. Not in the MCP catalog. In human mode progress lines go to
    /// stderr
    Rollback {
        /// Environment name; selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// Declared repo root (default: the current directory). Only the
        /// target file is read; the tree is not rendered
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// Directory holding `targets/<ENV>.yaml` and the target's
        /// known_hosts files (default: --repo)
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// The run to roll back: the `run_id` that `deploy apply` printed
        /// (or its directory below `.ign/deploy/<gateway>/`)
        #[arg(long, value_name = "ID")]
        run: String,
        /// Overwrite files changed after that run and record which. Without
        /// it a changed file refuses the rollback (`deploy_live_changed`,
        /// exit 6)
        #[arg(long)]
        discard_live_changes: bool,
        /// What to do about open Designer sessions: `fail` refuses while any
        /// is open, `wait` polls until none is or `--designers-timeout`
        /// passes, `proceed` goes ahead and records the sessions
        #[arg(long, value_enum, value_name = "MODE", default_value = "fail")]
        designers: DesignersArg,
        /// Seconds `--designers wait` polls before it refuses
        #[arg(
            long,
            value_name = "SECS",
            default_value_t = 600,
            value_parser = clap::value_parser!(u64).range(1..=86400)
        )]
        designers_timeout: u64,
    },
    /// Deploy one Ignition project from its own repo to a gateway. Reads
    /// `deploy/project.yaml` (the gateway project name and the environments
    /// it deploys to) and the root `project.json`, reads `targets/<ENV>.yaml`,
    /// builds the artifact from the checkout and compares it with the live
    /// project. `--check` reports `artifact_sha256`, `live_sha256`, the action
    /// (`create` for a project absent from the gateway, `skip` when the live
    /// project equals the artifact and this release is recorded, `record` when
    /// it equals the artifact but no record names this release, `import`
    /// otherwise), the member counts and the live members an overwrite would
    /// delete, over GET requests only; it writes nothing and creates no
    /// `.ign/` directory. Without `--check` the deploy asks for confirmation
    /// (`--yes`), requires `--artifact-sha256` (the hash the check reported)
    /// for an unattended run, saves the live project under `.ign/deploy/`,
    /// imports the artifact, reads the project back to compare it by
    /// canonical hash and records the release on the gateway host. Other
    /// projects on the gateway are listed by name and never read or changed.
    /// Not in the MCP catalog
    Projects {
        /// Environment name; must be listed in `deploy/project.yaml` and
        /// selects `targets/<ENV>.yaml`
        #[arg(long, value_name = "ENV")]
        env: String,
        /// The release tag being deployed: semver after one optional leading
        /// `v` (for example v1.4.0). A pre-release is older than its release
        #[arg(long, value_name = "TAG")]
        release: String,
        /// The project repo root (default: the current directory)
        #[arg(long, value_name = "DIR", default_value = ".")]
        repo: PathBuf,
        /// A root holding `targets/<ENV>.yaml` (default: `--repo`). Gateway
        /// targets may live in another repository than the project
        #[arg(long, value_name = "DIR")]
        targets: Option<PathBuf>,
        /// Report what would change and write nothing; no confirmation and
        /// no `--artifact-sha256` needed
        #[arg(long)]
        check: bool,
        /// The `artifact_sha256` that `--check --json` reported for this
        /// checkout (64 lowercase hex characters). Required without `--check`
        /// with `--json`, `--compact` or a stdin or stdout that is not a
        /// terminal; a different artifact is refused before anything is
        /// uploaded
        #[arg(long, value_name = "HASH")]
        artifact_sha256: Option<String>,
        /// Let a release older than the one the gateway last received from
        /// this tool replace it. Without it that is refused as a downgrade
        #[arg(long)]
        allow_downgrade: bool,
        /// Let the first deploy of a project by this tool change what the
        /// gateway runs, with a reason of 1 to 500 characters. Without it the
        /// release must equal the live project
        #[arg(long, value_name = "REASON")]
        allow_first_change: Option<String>,
        /// What to do about open Designer sessions before an import: `fail`
        /// refuses while any is open, `wait` polls until none is or
        /// `--designers-timeout` passes, `proceed` goes ahead and records
        /// the sessions. A release-record-only run skips the check
        #[arg(long, value_enum, value_name = "MODE", default_value = "fail")]
        designers: DesignersArg,
        /// Seconds `--designers wait` polls before it refuses
        #[arg(
            long,
            value_name = "SECS",
            default_value_t = 600,
            value_parser = clap::value_parser!(u64).range(1..=86400)
        )]
        designers_timeout: u64,
    },
}

/// The `--node` words of `deploy verify` (D-12).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum VerifyNodeArg {
    /// The six master checks (the default)
    Master,
    /// Only the backup node's checks
    Backup,
    /// The master's checks, then the backup's
    Both,
}

/// The `--designers` words of `deploy apply`, `deploy rollback` and
/// `deploy projects` (D-14, D-15).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum DesignersArg {
    /// Refuse while any Designer session is open (the default)
    Fail,
    /// Poll until none is open or the timeout passes, then refuse
    Wait,
    /// Go ahead, and record the open sessions
    Proceed,
}

/// `ign edit` args (13-08): the kubectl-edit loop over ONE resource.
/// The resource path scopes what $EDITOR opens (the whole tree still
/// decodes for encode-back context); the push rides the
/// project-import wire behind the ONE confirmation gate. `--yes` is
/// the GLOBAL flag (globals-once) — never redeclared here.
#[derive(Debug, clap::Args)]
pub struct EditArgs {
    /// Project containing the resource
    pub project: String,
    /// Resource user path to open in $EDITOR (e.g.
    /// `ignition/script-python/e2e/scratch` — `ign resource list`
    /// names the valid members)
    pub resource_path: String,
}

/// Resource subcommands (03-03, PROJ-05). `delete` is the family's
/// destructive verb (`--yes`-guarded, exit 2 without — the
/// sessions-terminate shape); `put` is an upsert (create-or-replace
/// ONE resource with explicit content) and stays friction-free per
/// the planner decision — agents pass exactly what they want written.
#[derive(Debug, clap::Args)]
pub struct ResourceArgs {
    #[command(subcommand)]
    pub command: ResourceCommand,
}

#[derive(Debug, Subcommand)]
pub enum ResourceCommand {
    /// List a project's resources (one path per line in human mode)
    List {
        /// Project name
        project: String,
        /// Only paths under this prefix (rides the wire as the
        /// server-side `path` filter)
        #[arg(long, value_name = "PREFIX")]
        prefix: Option<String>,
    },
    /// Read one resource: JSON pretty-printed, text raw — binary
    /// (data.bin-class) resources refuse with exit 6
    Get {
        /// Project name
        project: String,
        /// Resource path, slashes kept (e.g.
        /// `ignition/script-python/e2e/scratch`)
        path: String,
    },
    /// Write one resource (upsert: created if absent, replaced if
    /// present) — JSON if parseable (application/json), else UTF-8
    /// text (text/plain); binary-looking input refuses
    Put {
        /// Project name
        project: String,
        /// Resource path
        path: String,
        /// File to read the content from, or `-` for stdin
        #[arg(long, value_name = "PATH")]
        file: String,
    },
    /// Delete one resource — destructive, refused without --yes
    Delete {
        /// Project name
        project: String,
        /// Resource path
        path: String,
    },
}

/// Webdev subcommands (05-03, WEB-01/02). Deploy is deliberately NOT
/// `--yes`-guarded: the dedicated project (default `ign-cli`) is
/// CLI-OWNED — born from the first deploy zip and overwrite-replaced
/// on every deploy (replace-not-merge is the CONTRACT here; user
/// projects are never touched — README documents). scriptExec rides
/// only on explicit request, gated by a deploy-time generated shared
/// secret stored in the profile config at 0600.
#[derive(Debug, clap::Args)]
pub struct WebdevArgs {
    #[command(subcommand)]
    pub command: WebdevCommand,
}

#[derive(Debug, Subcommand)]
pub enum WebdevCommand {
    /// Deploy the embedded route bundle into the dedicated project
    /// (overwrite-replace — the CLI owns that project wholesale)
    Deploy {
        /// Target project (default ign-cli; the CLI owns it wholesale)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
        /// Also deploy the secret-gated scriptExec route (a fresh
        /// secret is generated and stored at 0600 when none exists)
        #[arg(long)]
        with_script_exec: bool,
        /// Generate a FRESH scriptExec secret before deploying (any
        /// route deployed with the old secret starts refusing)
        #[arg(long, requires = "with_script_exec")]
        rotate_secret: bool,
        /// Also deploy the embedded TESTING bundle — the Jython test
        /// framework (testing.runner & co., with the permanent
        /// testing.__tests__ smoke sentinel) and the testing/run +
        /// testing/tags WebDev routes
        #[arg(long)]
        with_testing: bool,
    },
    /// Probe every route's version handshake — a READ: exit 0
    /// whenever the sweep completes, per-route degradation is data
    Status {
        /// Target project (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// Tags args (05-04, TAGS-01..04) — the grouped-subfamily pattern:
/// `tags provider …` nests one level deeper (the family's native
/// REST half), browse/read/write ride the TOP level. The
/// webdev-dependent arms carry `--project` (default `ign-cli`, the
/// same default as deploy — the deployed routes live in that
/// project).
#[derive(Debug, clap::Args)]
pub struct TagsArgs {
    #[command(subcommand)]
    pub command: TagsCommand,
}

#[derive(Debug, Subcommand)]
pub enum TagsCommand {
    /// Manage tag providers (native config-resource REST — no
    /// deployed routes involved): list with tag counts + health,
    /// create a STANDARD provider, delete (guarded)
    #[command(subcommand)]
    Provider(TagsProviderCommand),

    /// Browse tags as a tree (Property children filtered by
    /// default) — providers appear at the root; needs the deployed
    /// routes (`ign webdev deploy`) — or run fully OFFLINE against
    /// an export via --from-export
    Browse {
        /// Tag path to browse from (default: the root — providers)
        path: Option<String>,
        /// Case-insensitive substring filter on name and full path
        #[arg(long, value_name = "SUBSTR")]
        filter: Option<String>,
        /// Include Property children (filtered out by default)
        #[arg(long)]
        include_properties: bool,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
        /// Browse an OFFLINE tag export instead of the gateway (no
        /// profile, no credential, no routes): the CLI's own `tags
        /// export` JSON, a legacy `<provider>.json` whole tree, or a
        /// git-module tags/ directory — mutually exclusive with the
        /// positional browse path
        #[arg(long, value_name = "PATH", conflicts_with_all = ["path"])]
        from_export: Option<PathBuf>,
    },
    /// Read one or more tag values (quality and timestamp included)
    /// — needs the deployed routes
    Read {
        /// Tag paths to read, e.g. `[default]T1` (one or more)
        #[arg(value_name = "PATH", required = true)]
        paths: Vec<String>,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Write a value to a tag — the value is parsed as a JSON
    /// scalar (number/bool/null); anything unparseable is sent as a
    /// string; arrays/objects refuse — needs the deployed routes
    Write {
        /// Tag path to write, e.g. `[default]T1`
        path: String,
        /// Value to write: JSON scalar (42, 1.5, true), else the raw
        /// text is sent as a string
        #[arg(long, value_name = "V")]
        value: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Tag CONFIGURATION CRUD (the surgical edit loop — JSON in,
    /// JSON out): get/create/edit/delete tag configs through the
    /// deployed tagConfig route; stringified values are re-parsed so
    /// agents see real JSON
    #[command(subcommand)]
    Config(TagsConfigCommand),
    /// UDT types and definitions (recursive: parameters + nested
    /// children) — needs the deployed routes
    #[command(subcommand)]
    Udt(TagsUdtCommand),
    /// Alarm operations: active status (with filters), journal
    /// history, acknowledge — needs the deployed routes
    #[command(subcommand)]
    Alarms(TagsAlarmsCommand),
    /// Tag history queries (historian-backed values) — needs the
    /// deployed routes; structurally safe on any rig (data requires
    /// a provisioned historian)
    #[command(subcommand)]
    History(TagsHistoryCommand),
    /// Export tag subtrees — json writes the gateway's native JSON
    /// interchange (the lossless round-trip); xml passes the
    /// gateway's own XML through byte-for-byte; csv is CLI-GENERATED
    /// and LOSSY (no alarms, legacy 48-column set, numeric enums —
    /// the gateway cannot export CSV)
    Export {
        /// Tag paths to export, e.g. `[default]P5` (one or more)
        #[arg(value_name = "PATH", required = true)]
        paths: Vec<String>,
        /// Output file (`-` = stdout — the raw payload, no envelope;
        /// default: `<last-path-segment>.<ext>` in the cwd, ext per
        /// format)
        #[arg(short = 'o', long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Payload format: json (the gateway's native interchange —
        /// default), xml (raw gateway bytes), or csv (CLI-generated
        /// and LOSSY: no alarms, legacy columns only, numeric enum
        /// coercion — what was dropped prints on stderr)
        #[arg(long, value_enum, default_value_t = TransferFormat::Json, value_name = "FORMAT")]
        format: TransferFormat,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Import a tag export into a target provider — json is the
    /// native interchange; xml/csv ride the gateway's importTags
    /// passthrough. A loss scan reports what xml/csv would drop or
    /// coerce BEFORE the import and refuses exit 2 unless --yes.
    /// Collision behavior: abort (default) refuses on collisions;
    /// overwrite replaces them (destructive: requires --yes)
    Import {
        /// The export file to import (`-` = stdin)
        #[arg(long, value_name = "FILE")]
        file: PathBuf,
        /// Target tag provider (must exist — `ign tags provider
        /// create NAME` first)
        #[arg(long, value_name = "NAME")]
        provider: String,
        /// Payload format: json (the gateway's native interchange —
        /// default), xml (gateway XML), or csv (legacy CSV — alarms
        /// never arrive; the loss scan reports the gap)
        #[arg(long, value_enum, default_value_t = TransferFormat::Json, value_name = "FORMAT")]
        format: TransferFormat,
        /// Collision policy: abort refuses when tags already exist
        /// (default); overwrite replaces them (destructive:
        /// requires --yes). merge is Designer-only (not a value)
        #[arg(long, value_enum, default_value_t = CollisionPolicy::Abort)]
        collision_policy: CollisionPolicy,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// The bulk-transfer payload format (11-05) — the clap surface for
/// core's `ExportFormat`/`ImportFormat` (core keeps plain enums; the
/// From impls live beside this one, the CollisionPolicy precedent).
/// json is the default so every pre-11-05 invocation parses and
/// behaves byte-identically.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum TransferFormat {
    /// The gateway's JSON interchange (default — lossless)
    #[default]
    Json,
    /// Gateway XML — RAW-BYTE passthrough both directions (no
    /// parse/normalize in the transfer path)
    Xml,
    /// Legacy CSV — import: gateway passthrough (alarms never
    /// arrive); export: CLI-GENERATED and LOSSY (the gateway cannot
    /// export CSV)
    Csv,
}

impl std::fmt::Display for TransferFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let label = match self {
            Self::Json => "json",
            Self::Xml => "xml",
            Self::Csv => "csv",
        };
        f.write_str(label)
    }
}

/// `tags config …` — the configuration CRUD subfamily (05-05,
/// TAGS-05): the get→edit-file→write-back surgical loop. Definition
/// files are the configure shape (README's traps table: tagType
/// discriminator, nested children, alarms-as-LIST).
#[derive(Debug, Subcommand)]
pub enum TagsConfigCommand {
    /// Get a tag's configuration as (pretty) JSON — stringified
    /// value/defaultValue sub-dicts re-parsed into real JSON
    Get {
        /// Tag path, e.g. `[default]P5/T1`
        path: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Create a tag from a JSON definition file (`-` = stdin) —
    /// aborts on an existing node (collision policy 'a')
    Create {
        /// Tag path to create, e.g. `[default]P5/T1`
        path: String,
        /// JSON definition file (`-` = stdin): `{tagType, value,
        /// alarms, …}` — see the README configure-shape table
        #[arg(long, value_name = "FILE")]
        file: PathBuf,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Edit a tag's configuration from a JSON definition file (`-` =
    /// stdin) — overwrites that single node (collision policy 'o')
    Edit {
        /// Tag path to edit, e.g. `[default]P5/T1`
        path: String,
        /// JSON definition file (`-` = stdin)
        #[arg(long, value_name = "FILE")]
        file: PathBuf,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Delete tag configurations — destructive, refused without
    /// --yes (the guard fires before ANY resolution: zero network
    /// work)
    Delete {
        /// Tag paths to delete (one or more)
        #[arg(value_name = "PATH", required = true)]
        paths: Vec<String>,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// `tags udt …` — the UDT subfamily (05-05, TAGS-06).
#[derive(Debug, Subcommand)]
pub enum TagsUdtCommand {
    /// List the provider's UDT types
    Types {
        /// Tag provider whose `_types_` folder to browse (default
        /// `default`)
        #[arg(long, default_value = "default", value_name = "NAME")]
        provider: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Get a UDT definition (parameters + nested children, recursive)
    Def {
        /// UDT type name, e.g. `Motor`
        name: String,
        /// Tag provider (default `default`)
        #[arg(long, default_value = "default", value_name = "NAME")]
        provider: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

#[derive(Debug, Subcommand)]
pub enum TagsProviderCommand {
    /// List the gateway's tag providers (tag counts + health)
    List,
    /// Create a STANDARD tag provider (DB-backed providers are out
    /// of scope at MVP)
    Create {
        /// Provider name to create
        name: String,
    },
    /// Delete a tag provider — destructive, refused without --yes
    Delete {
        /// Provider name to delete
        name: String,
    },
}

/// `tags alarms …` — the alarm subfamily (05-06, TAGS-07). History
/// needs a JOURNAL-PROVISIONED gateway (database connection +
/// alarm-journal profile + general-alarm-settings — default rigs
/// refuse exit 6 with the provisioning hint); acknowledge is the
/// gateway-scope 3-arg form, so `--username` is REQUIRED (no
/// default-guessing) and ack is deliberately NOT `--yes`-guarded
/// (acknowledging never un-acknowledges anything — a state-advancing
/// read-adjacent verb).
#[derive(Debug, Subcommand)]
pub enum TagsAlarmsCommand {
    /// List active alarms — eventId/source/state/priority/name
    Active {
        /// Filter by alarm source (e.g. `prov:default`)
        #[arg(long, value_name = "SOURCE")]
        source: Option<String>,
        /// Filter by priority (e.g. `High`)
        #[arg(long, value_name = "PRIORITY")]
        priority: Option<String>,
        /// Filter by state (e.g. `Active, Unacknowledged`)
        #[arg(long, value_name = "STATE")]
        state: Option<String>,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Query alarm history — requires a journal-provisioned gateway
    /// (default rigs refuse with the provisioning hint naming the
    /// missing chain)
    History {
        /// Window start: RFC3339 timestamp or epoch-ms
        #[arg(long, value_name = "T")]
        start: String,
        /// Window end: RFC3339 timestamp or epoch-ms
        #[arg(long, value_name = "T")]
        end: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Acknowledge alarms (explicit --username: the 3-arg wire form
    /// needs it). NOT --yes-guarded — acknowledging never
    /// un-acknowledges anything
    Ack {
        /// Alarm event ids to acknowledge (from `alarms active`)
        #[arg(value_name = "ID", required = true)]
        ids: Vec<String>,
        /// Acknowledgement note (default: empty)
        #[arg(long, value_name = "NOTE")]
        note: Option<String>,
        /// The username acknowledging (REQUIRED — the 3-arg wire
        /// form needs it; the CLI never guesses one)
        #[arg(long, value_name = "NAME")]
        username: String,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// `tags history …` — the historian subfamily (05-06, TAGS-08).
#[derive(Debug, Subcommand)]
pub enum TagsHistoryCommand {
    /// Query historical tag values — t_stamp + one column per tag;
    /// structurally safe anywhere (data requires a provisioned
    /// historian)
    Query {
        /// Tag paths to query, e.g. `[default]T1` (one or more)
        #[arg(value_name = "PATH", required = true)]
        paths: Vec<String>,
        /// Window start: RFC3339 timestamp or epoch-ms
        #[arg(long, value_name = "T")]
        start: String,
        /// Window end: RFC3339 timestamp or epoch-ms
        #[arg(long, value_name = "T")]
        end: String,
        /// Maximum rows returned
        #[arg(long, value_name = "N")]
        return_size: Option<i64>,
        /// Aggregation mode (e.g. `LastValue`, `Average`, `MinMax`);
        /// default is the route's LastValue
        #[arg(long, value_name = "MODE")]
        aggregation: Option<String>,
        /// Project holding the deployed routes (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// Rig args (04-01, RIG-01): `--rig` rides the TOP level (the
/// SessionsArgs `--type` precedent) so every rig verb shares it. The
/// command enum carries ONLY the wired verbs — later plans extend it
/// one variant at a time (the established extend-per-plan chore; no
/// `unimplemented!()` stubs, every commit compiles clippy-clean).
#[derive(Debug, clap::Args)]
pub struct RigArgs {
    /// Rig to operate on (default: IGNITION_RIG, then [rig].default,
    /// then the cwd/convention scan)
    #[arg(long, value_name = "NAME")]
    pub rig: Option<String>,

    #[command(subcommand)]
    pub command: RigCommand,
}

#[derive(Debug, Subcommand)]
pub enum RigCommand {
    /// Bring the rig up (compose up -d --wait) and wait for the
    /// gateway: RUNNING, or uncommissioned-as-data (exit 0 + wizard
    /// hint in warnings)
    Up {
        /// Wait budget in seconds — BOTH compose's --wait-timeout and
        /// the commissioned probe deadline (default 300)
        #[arg(long, default_value_t = 300, value_name = "SECS")]
        timeout: u64,

        /// Provision a third-party module for THIS invocation only
        /// (repeatable): `ID@VERSION`, e.g. `git@2.3.4`. ADDITIVE to
        /// any `[rigs.NAME.modules.*]` declared in config — a flag
        /// naming an id config already declares OVERRIDES that id's
        /// version for this run; there is NO subtractive form (a
        /// config-declared module cannot be omitted via this flag —
        /// remove it from config instead)
        #[arg(long, value_name = "ID@VERSION")]
        with_module: Vec<String>,

        /// Re-verify every already-cached module version against its
        /// release feed before trusting it: an unchanged digest reuses
        /// the cache, a changed one REFUSES (exit 6) naming both
        /// digests — never silently accepted. Mutually exclusive with
        /// --accept-upstream-change (never implied by it)
        #[arg(long, conflicts_with = "accept_upstream_change")]
        refresh: bool,

        /// Accept a changed digest the feed now reports for an
        /// already-cached module version — the deliberate, explicit
        /// way to accept a re-released artifact (downloads and
        /// verifies the NEW bytes, cached alongside the old entry,
        /// never over it). Mutually exclusive with --refresh
        #[arg(long, conflicts_with = "refresh")]
        accept_upstream_change: bool,
    },
    /// Stop the rig (compose down --remove-orphans; volumes KEPT —
    /// `reset` owns the teardown half)
    Down,
    /// Tear the rig down AND remove its volumes (down -v
    /// --remove-orphans), then bring it back up fresh — destructive,
    /// refused without --yes; no stale project/trial state survives
    Reset {
        /// Wait budget in seconds — BOTH compose's --wait-timeout and
        /// the commissioned probe deadline (default 300)
        #[arg(long, default_value_t = 300, value_name = "SECS")]
        timeout: u64,

        /// Provision a third-party module for THIS invocation only
        /// (repeatable): `ID@VERSION`, e.g. `git@2.3.4`. Same
        /// additive/flag-wins/no-subtractive-form contract as `rig up
        /// --with-module` (`reset` runs the same up-half internally)
        #[arg(long, value_name = "ID@VERSION")]
        with_module: Vec<String>,

        /// Re-verify every already-cached module version against its
        /// release feed before trusting it (see `rig up --refresh`).
        /// Mutually exclusive with --accept-upstream-change
        #[arg(long, conflicts_with = "accept_upstream_change")]
        refresh: bool,

        /// Accept a changed digest the feed now reports for an
        /// already-cached module version (see `rig up
        /// --accept-upstream-change`). Mutually exclusive with --refresh
        #[arg(long, conflicts_with = "refresh")]
        accept_upstream_change: bool,
    },
    /// Structured status: services, ports, volumes (allowlist JSON;
    /// a down rig is exit-0 data)
    Status,
    /// Stream the rig's container logs (compose logs passthrough —
    /// raw lines, no envelope in any mode; the third streaming
    /// exception, README-documented)
    Logs {
        /// Lines to show from the end of each service's logs
        #[arg(long, default_value_t = 200, value_name = "N")]
        tail: u32,
        /// Follow: stream new lines as they occur (Ctrl-C stops —
        /// default process kill, no envelope)
        #[arg(short = 'f', long)]
        follow: bool,
        /// One service's logs only (see `ign rig status` for names)
        service: Option<String>,
    },
    /// Trial-license state: status is credential-free truth; reset
    /// (guarded) restarts an EXPIRED trial via the mechanism ladder
    /// (token-auth POST, else native gateway login)
    Trial(TrialArgs),
    /// Third-party module lifecycle beyond declaration: `uninstall`
    /// removes a module from the gateway entirely — guarded, and NOT
    /// undone by re-declaring it (Phase 19)
    Module(ModuleArgs),
    /// Snapshot the rig's gateway: native gwbk (roaming backup,
    /// streamed) + per-project exports + manifest.json, composed in a
    /// timestamped directory — repeatable state
    Snapshot {
        /// Output directory (default:
        /// ./ign-rig-snapshots/<rig>-<yyyyMMdd-HHmmss>/)
        #[arg(short = 'o', long, value_name = "DIR")]
        output: Option<PathBuf>,
    },
    /// Restore a gwbk onto the rig's gateway — destructive, refused
    /// without --yes; synchronous restore + restart, then a witnessed
    /// RUNNING wait
    Restore {
        /// The gwbk file to restore (from `ign rig snapshot`)
        #[arg(long, value_name = "PATH")]
        file: PathBuf,
        /// Post-restore RUNNING wait budget in seconds (floored at
        /// 300 — the gateway restarts after a restore)
        #[arg(long, default_value_t = 300, value_name = "SECS")]
        timeout: u64,
    },
}

/// Trial subcommands (04-03, RIG-02/03). `status` reads the
/// unauthenticated trial endpoint + banners cross-check. `reset` is
/// the family's destructive verb (`--yes`-guarded, exit 2 without —
/// the reset precedent); the password NEVER rides a flag (env/secret
/// only — redaction discipline).
#[derive(Debug, clap::Args)]
pub struct TrialArgs {
    #[command(subcommand)]
    pub command: TrialCommand,
}

#[derive(Debug, Clone, Subcommand)]
pub enum TrialCommand {
    /// Show the trial state: licenseMode, trialState, seconds left,
    /// expired — plus the banners cross-check. No credential needed
    /// (the endpoints answer unauthenticated — fresh-rig friendly)
    Status,
    /// Reset an EXPIRED trial to a fresh window — destructive,
    /// refused without --yes. Mechanism ladder: API-token POST
    /// (IGNITION_TOKEN) → native gateway login (--user /
    /// IGNITION_USER + IGNITION_PASSWORD). Non-expired trials refuse
    /// (trial_not_expired)
    Reset {
        /// Gateway admin username for the login rung (password comes
        /// from IGNITION_PASSWORD — never a flag)
        #[arg(long, value_name = "NAME")]
        user: Option<String>,
    },
}

/// Module subcommands (Phase 19) — `uninstall` is the family's ONE
/// destructive verb: guarded (`--yes`-refused, the `rig reset`
/// precedent), and, unlike every other guarded verb in this codebase,
/// NOT undone by re-declaring the module afterward (recovery today
/// means `ign rig reset`, which destroys the rig's data volume).
#[derive(Debug, clap::Args)]
pub struct ModuleArgs {
    #[command(subcommand)]
    pub command: ModuleCommand,
}

#[derive(Debug, Clone, Subcommand)]
pub enum ModuleCommand {
    /// Remove a module from the gateway entirely — destructive, refused
    /// without `--yes`. `ID` is a REGISTRY id (the same one `rig up
    /// --with-module` takes; see `ign rig up --with-module`), never a
    /// raw gateway module id — a hand-installed module cannot be named
    /// here. Needs `IGNITION_TOKEN`. The gateway refuses while the
    /// `.modl` is still mounted: undeclare the module and run `ign rig
    /// up` first. A successful uninstall is NOT reversible by
    /// re-declaring — recovery today means `ign rig reset --yes`,
    /// which destroys the rig's data volume.
    Uninstall {
        /// The registry id to uninstall (e.g. `git`).
        id: String,
    },
}

/// Backup subcommands (07-02, BKUP-01) — the standalone surface of
/// the Phase 4 gwbk wire. `restore` is the family's destructive verb
/// (the 8th `--yes`-guarded set member: it REPLACES this gateway's
/// state); `download` is a streamed read, unguarded.
#[derive(Debug, clap::Args)]
pub struct BackupArgs {
    #[command(subcommand)]
    pub command: BackupCommand,
}

#[derive(Debug, Subcommand)]
pub enum BackupCommand {
    /// Download a gwbk backup (streamed to disk)
    Download {
        /// Output file (default: the gateway's Content-Disposition
        /// name, else <profile>-backup.gwbk)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Backup type: roaming = portable across gateways (default);
        /// all includes gateway-specific state
        #[arg(long, value_enum, default_value_t = CliBackupType::Roaming)]
        r#type: CliBackupType,
    },
    /// Restore a gwbk onto THIS gateway — destructive, refused
    /// without --yes; the gateway restarts and blocks for minutes
    /// after the restore
    Restore {
        /// The gwbk file to restore (from `ign backup download` or
        /// `ign rig snapshot`)
        file: PathBuf,
    },
}

/// CLI value-enum mirror of the core `BackupType` (ignition-core
/// stays clap-free; `From` converts at the dispatch seam).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum CliBackupType {
    /// Portable backup (cross-gateway)
    Roaming,
    /// Includes gateway-specific state
    All,
}

impl From<CliBackupType> for ignition_core::client::backup::BackupType {
    fn from(value: CliBackupType) -> Self {
        match value {
            CliBackupType::Roaming => Self::Roaming,
            CliBackupType::All => Self::All,
        }
    }
}

/// EAM subcommands (07-02, BKUP-02) — the read-heavy surface with
/// guarded writes. Every runtime verb honestly reports the
/// controller-mode state gate (`eam_not_controller` on a stock
/// gateway — the README documents the manual flip).
#[derive(Debug, clap::Args)]
pub struct EamArgs {
    #[command(subcommand)]
    pub command: EamCommand,
}

#[derive(Debug, Subcommand)]
pub enum EamCommand {
    /// EAM task run history (the gateway's own newest-first order)
    History {
        /// Max entries (default 200 — ALWAYS sent explicitly; the
        /// server default is unlimited)
        #[arg(long, value_name = "N")]
        limit: Option<u32>,
        /// Substring search over task names
        #[arg(long, value_name = "TEXT")]
        search: Option<String>,
    },
    /// Task definitions: bare `ign eam tasks` lists; with a name
    /// shows one definition + its scheduled state
    Tasks {
        /// One task definition's detail (omit to list all)
        name: Option<String>,
    },
    /// Task definition writes (create; force-dispatch) — `eam task`
    /// requires a subcommand (the `rig trial` shape)
    #[command(subcommand)]
    Task(EamTaskCommand),
}

/// `eam task …` — the guarded writes (07-02 Task 3; the five
/// lifecycle/mutation verbs arrive 10-04). `new` carries the typed
/// guard ladder (backup+OnDemand unguarded; mutating types and any
/// non-OnDemand schedule need --yes; restore/install/upgrade types
/// refuse outright — see README); `force` dispatches NOW, always
/// guarded; `suspend`/`resume`/`cancel`/`modify`/`delete` are the
/// two-tier guarded verbs (pure precheck → blast-radius preview
/// fetch → confirm-with-preview → action — the refusal message IS
/// the blast radius).
#[derive(Debug, Subcommand)]
pub enum EamTaskCommand {
    /// Create a task definition (scheduleMode defaults to OnDemand —
    /// never auto-fires)
    New {
        /// Task definition name (any resource name — e.g. nightly-backup)
        name: String,
        /// Task type — the openapi taxonomy, three classes with different guard consequences:
        ///
        /// - benign (no --yes with the default OnDemand schedule): eam_backup
        ///
        /// - mutating (need --yes — they act on their agent targets when dispatched):
        ///   eam_restart, eam_sendProject, eam_sendResource, eam_sendTags,
        ///   eam_activateLicense, eam_updateLicense, eam_unactivateLicense
        ///
        /// - refused (exit 6 eam_task_type_refused — fleet-destructive; run from the EAM console):
        ///   eam_restoreBackup, eam_installModules, eam_remoteUpgrade
        ///
        /// Any OTHER type fails safe to the --yes rung (unknown future
        /// types stay accepted, never silently unguarded).
        ///
        /// Example: ign eam task new nightly-backup eam_backup --target gw-a
        r#type: String,
        /// Target gateway name (repeatable; the GNET agent id)
        #[arg(long, value_name = "NAME")]
        target: Vec<String>,
        /// Setting as K=V with scalar auto-typing — bool/int ride
        /// typed, anything else stays a string (repeatable;
        /// arrays/objects need --definition)
        #[arg(long, value_name = "K=V")]
        setting: Vec<String>,
        /// Full-JSON settings file deep-merged over the composed
        /// `config.settings` (the typed/array settings path)
        #[arg(long, value_name = "PATH", conflicts_with = "setting")]
        definition: Option<PathBuf>,
        /// Schedule mode (default OnDemand — never auto-fires;
        /// Immediate/Scheduled/AtTime/AtDelay require --yes)
        #[arg(long, value_enum, default_value_t = ScheduleMode::OnDemand)]
        schedule_mode: ScheduleMode,
    },
    /// Force-dispatch a task NOW — destructive, refused without
    /// --yes (it dispatches to the agent targets immediately). The
    /// confirmation prompt (and every refusal) carries the
    /// blast-radius preview line.
    Force {
        /// Task definition name to dispatch
        name: String,
    },
    /// Suspend a task definition's scheduled dispatches — TASK-scoped
    /// runtime verb (there is NO agent-level suspend on the wire; an
    /// "agent" is suspended by suspending its tasks). Refused exit 2
    /// without --yes, the blast-radius preview in the refusal
    /// message; on a stock gateway the runtime seam honestly refuses
    /// `eam_not_controller` (exit 6).
    Suspend {
        /// Task definition name to suspend
        name: String,
    },
    /// Resume a suspended task definition — the suspend inverse
    /// (TASK-scoped, like suspend). Refused exit 2 without --yes
    /// with the blast-radius preview in the message.
    Resume {
        /// Task definition name to resume
        name: String,
    },
    /// Cancel a task's PENDING execution (TASK-scoped). Refused exit
    /// 2 without --yes with the blast-radius preview in the message;
    /// nothing pending is an honest no-op (`fired: false`), a
    /// `canCancel: false` row reports the gateway's own refusal.
    Cancel {
        /// Task definition whose pending execution to cancel
        name: String,
    },
    /// Rewrite targeted keys of a task definition — the full-record
    /// read-modify-write (every key the gateway answered rides back;
    /// only the targeted keys change). Rename is deliberately
    /// ABSENT (the wire answers PUT-rename with 404 — see README's
    /// create-new + delete-old composite). Refused exit 2 without
    /// --yes with the blast-radius preview in the message.
    ///
    /// Example: ign eam task modify nightly-backup --enable
    Modify {
        /// Task definition to modify
        name: String,
        /// Flip the definition's `enabled` key to true
        #[arg(long)]
        enable: bool,
        /// Flip the definition's `enabled` key to false
        /// (conflicts with --enable)
        #[arg(long, conflicts_with = "enable")]
        disable: bool,
        /// Rewrite `config.profile.scheduleMode` (e.g. OnDemand,
        /// Scheduled — the scheduleDetails string itself is out of
        /// scope; the read-back shows the landed pairing)
        #[arg(long, value_name = "MODE")]
        schedule_mode: Option<String>,
        /// Deep-merge a settings entry over the found
        /// `config.settings` (K=V with scalar auto-typing;
        /// repeatable — objects merge recursively, arrays/scalars
        /// replace)
        #[arg(long, value_name = "K=V")]
        setting: Vec<String>,
        /// Rewrite the definition's `description`
        #[arg(long, value_name = "TEXT")]
        description: Option<String>,
    },
    /// Delete a task definition — signature-keyed (the gateway
    /// refuses a stale signature), behind the same --yes guard.
    /// Refused exit 2 without --yes with the blast-radius preview
    /// in the message.
    Delete {
        /// Task definition to delete
        name: String,
    },
}

/// Schedule modes (the openapi taxonomy's user-facing subset —
/// SuspendedByFailover is system-owned, not a CLI value).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ScheduleMode {
    /// Never fires on its own (force dispatches it)
    OnDemand,
    /// Fires immediately on create (requires --yes)
    Immediate,
    /// Fires on a schedule (requires --yes)
    Scheduled,
    /// Fires at an absolute time (requires --yes)
    AtTime,
    /// Fires after a delay (requires --yes)
    AtDelay,
}

impl ScheduleMode {
    /// The wire token.
    pub fn wire(self) -> &'static str {
        match self {
            Self::OnDemand => "OnDemand",
            Self::Immediate => "Immediate",
            Self::Scheduled => "Scheduled",
            Self::AtTime => "AtTime",
            Self::AtDelay => "AtDelay",
        }
    }
}

/// Script subcommands (07-03, SCRPT-01) — the smallest family: ONE
/// verb over the already-shipped, already-secured scriptExec route.
/// `script` requires a subcommand (the `rig trial` shape — no bare
/// row); the opt-in is STRUCTURAL (the route deploys only via
/// `ign webdev deploy --with-script-exec`, which persists the
/// secret at 0600), so `run` carries NO `--yes` guard by design —
/// the deploy flag IS the opt-in and agents need the verb
/// non-interactive (the research-adopted decision).
#[derive(Debug, clap::Args)]
pub struct ScriptArgs {
    #[command(subcommand)]
    pub command: ScriptCommand,
}

/// Testing subcommands (QUICK-p0g) — the standalone wrapper over the
/// gateway testing bundle's `testing/run` route. `testing` requires a
/// subcommand (the `script` shape — no bare row); there is no `--yes`
/// guard: running a test suite is a read-shaped operation from the
/// CLI's side and agents need the verb non-interactive.
#[derive(Debug, clap::Args)]
pub struct TestingArgs {
    #[command(subcommand)]
    pub command: TestingCommand,
}

/// `ign e2e` args (QUICK-tg4) — the browser-E2E pair.
#[derive(Debug, clap::Args)]
pub struct E2eArgs {
    #[command(subcommand)]
    pub command: E2eCmd,
}

#[derive(Debug, Subcommand)]
pub enum E2eCmd {
    /// Diagnose the browser-E2E setup: node (≥20), npm,
    /// @playwright/test in the scaffold, a downloaded chromium, the
    /// gateway's testing bundle, and the gateway's trial state.
    /// Read-only and offline-safe — **exits 0 whenever the diagnosis
    /// completes**, so every finding is a `checks[]` row rather than
    /// an exit code. The two gateway rows report `skip` when no
    /// profile resolves or no --project is given
    Doctor {
        /// The scaffold directory to inspect (default: ./e2e)
        #[arg(value_name = "DIR")]
        dir: Option<PathBuf>,
        /// The gateway project whose testing bundle is probed. No
        /// default — without it the bundle row honestly skips
        #[arg(long, value_name = "NAME")]
        project: Option<String>,
    },

    /// Scaffold a Playwright E2E suite into DIR (default ./e2e): a
    /// runner config, a global setup that logs in through `ign
    /// session login` and gates on `ign testing run`, gateway tag/
    /// script helpers, an example suite, a .gitignore, and a README —
    /// then `npm install`. **Idempotent**: an existing file is
    /// reported `skipped` and never overwritten. Requires the global
    /// --yes; without it the verb writes nothing, spawns nothing, and
    /// refuses exit 2 after previewing every file and both commands
    Init {
        /// Where the scaffold lands (default: ./e2e)
        #[arg(value_name = "DIR")]
        dir: Option<PathBuf>,
        /// The project whose WebDev testing routes the helpers call
        /// (default: ign-cli)
        #[arg(long, value_name = "NAME")]
        project: Option<String>,
        /// The Perspective project the browser test navigates to
        /// (default: the effective --project)
        #[arg(long, value_name = "NAME")]
        run_project: Option<String>,
        /// Also download the Chromium build after installing
        #[arg(long)]
        browsers: bool,
    },
}

/// `ign session` args (QUICK-tg4) — the SINGULAR verb family: one
/// gateway login session for this CLI to hand to a browser harness.
///
/// The plural `ign sessions` family (`SessionsArgs` / `SessionsCommand`)
/// is a different thing entirely: it LISTS the gateway's connected
/// designer/Perspective/Vision sessions. The names are deliberately
/// kept apart here so a future reader never merges them.
#[derive(Debug, clap::Args)]
pub struct SessionArgs {
    #[command(subcommand)]
    pub command: SessionCmd,
}

#[derive(Debug, Subcommand)]
pub enum SessionCmd {
    /// Log in to the gateway and return the live session: the
    /// `webui-sid-*` cookie name and value, the CSRF token for
    /// `X-CSRF-Token`, the gateway URL, and `storage_state` — a
    /// Playwright `storageState` document ready to write straight to
    /// disk and point `use.storageState` at. The password is env-only
    /// (`IGNITION_PASSWORD`; missing exits 3, rejected exits 5). The
    /// cookie value and CSRF token are exposed ONLY under the global
    /// --json flag
    Login {
        /// Gateway login user (default: $IGNITION_USER, else admin)
        #[arg(long, value_name = "NAME")]
        user: Option<String>,
    },
}

/// The CLI-side `--format` enum (QUICK-p0g) — the clap `ValueEnum`
/// mirror of core's plain `TestingFormat`, the `TransferFormat`
/// precedent (core keeps framework-free enums; the `From` impl lives
/// beside this one). `get_possible_values()` is what feeds the MCP
/// tool schema a real enum instead of a free string.
///
/// EVERY value produces the SAME verdict and exit code: the route is
/// always asked for json and the junit/text reports are rendered
/// client-side, because the route's own junit/text answers stay HTTP
/// 200 and carry no counts — a passthrough would exit 0 on a red
/// suite.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum TestingFormatArg {
    /// Structured results only (default) — `data.report` stays empty
    #[default]
    Json,
    /// JUnit XML in `data.report`, for a CI test reporter
    Junit,
    /// Console-style text in `data.report`, for a human reading logs
    Text,
}

impl From<TestingFormatArg> for ignition_core::actions::testing::TestingFormat {
    fn from(value: TestingFormatArg) -> Self {
        match value {
            TestingFormatArg::Json => Self::Json,
            TestingFormatArg::Junit => Self::Junit,
            TestingFormatArg::Text => Self::Text,
        }
    }
}

#[derive(Debug, Subcommand)]
pub enum TestingCommand {
    /// Run the gateway-side Jython test suite and return the machine
    /// verdict (exit 0 green, exit 6 red with the FULL results still
    /// in the envelope)
    Run {
        /// The project whose testing bundle runs. REQUIRED — the
        /// bundle deploys per project and running a suite executes
        /// that project's gateway-side code, so there is
        /// deliberately no `ign-cli` default here
        #[arg(long, value_name = "NAME", required = true)]
        project: String,
        /// List the gateway's discovered test modules instead of
        /// running them
        #[arg(long, conflicts_with_all = ["module", "package"])]
        discover: bool,
        /// Run ONE dotted module (`proj.foo_test`); mutually
        /// exclusive with --package and --discover
        #[arg(long, value_name = "DOTTED", conflicts_with = "package")]
        module: Option<String>,
        /// Run every module under a package prefix (`proj.`);
        /// mutually exclusive with --module and --discover
        #[arg(long, value_name = "PREFIX")]
        package: Option<String>,
        /// Report rendered into `data.report`. The verdict and exit
        /// code are IDENTICAL in every format — the structured
        /// results always ride under `data.results`
        #[arg(long, value_name = "FORMAT", default_value = "json")]
        format: TestingFormatArg,
    },
}

/// `ign lint` args (07-04, INTR-02) — the ignition-lint delegation:
/// PATHS map to `--target <path>` pairs on the child's arg vector;
/// `--` passthrough args ride verbatim after them (power users:
/// `--profile`, `--checks`, `--fail-on`, …).
#[derive(Debug, clap::Args)]
pub struct LintArgs {
    /// Paths to lint (one --target pair each)
    #[arg(value_name = "PATH", required = true)]
    pub paths: Vec<String>,
    /// Exit with the linter's own exit code (CI mode). Default is
    /// the doctor posture: findings + child_exit_code + the parsed
    /// report ride as data and the command exits 0 whenever the
    /// tool RAN
    #[arg(long)]
    pub strict: bool,
    /// Extra args passed to ignition-lint verbatim (after --)
    #[arg(last = true, value_name = "ARGS")]
    pub passthrough: Vec<String>,
}

#[derive(Debug, Subcommand)]
pub enum ScriptCommand {
    /// Execute gateway-side Python (Jython) — non-interactive, the
    /// route's entire purpose
    Run {
        /// Inline Python source (a one-liner's best form)
        #[arg(long, value_name = "PY")]
        code: Option<String>,
        /// Python source file (`-` reads stdin — the agent pipe
        /// path); giving both --code and --file refuses
        /// `invalid_input` (exit 2) pre-resolution
        #[arg(long, value_name = "PATH")]
        file: Option<String>,
        /// The deployed routes' project (default ign-cli — where
        /// `ign webdev deploy` put scriptExec)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// `ign api` args (09-03, EXT-01) — the raw-passthrough family. One
/// verb today (`call`); the escape hatch for the 80+ gateway endpoint
/// families no curated command covers.
#[derive(Debug, clap::Args)]
pub struct ApiArgs {
    #[command(subcommand)]
    pub command: ApiCommand,
}

#[derive(Debug, Subcommand)]
pub enum ApiCommand {
    /// Call any gateway REST endpoint raw: `--method`/`--path` are the
    /// request, `--data`/`--header`/`--query` shape it, and the
    /// envelope's `data.result.data` is the gateway's JSON VERBATIM
    /// (no field dropped, no value coerced, key order preserved — the
    /// README's documented contract exception). Auth-pattern headers
    /// (`Authorization`, `X-Ignition-API-Token`, `Cookie`) are
    /// refused pre-I/O — credentials come from the profile.
    Call(ApiCallArgs),
}

/// `ign api call` args (09-03, EXT-01). Arbitrary verbs accepted —
/// reqwest's `Method` parser validates (usage-class refusal for
/// garbage); `--data` is RAW TEXT on ANY method (GET/DELETE bodies
/// allowed — curl parity; the gateway's answer classifies); ONE query
/// mechanism (repeatable `--query k=v`, never `?` in `--path`).
#[derive(Debug, clap::Args)]
pub struct ApiCallArgs {
    /// HTTP method (GET, POST, PUT, DELETE, PATCH, HEAD, …)
    #[arg(long, value_name = "METHOD")]
    pub method: String,
    /// Absolute path on the gateway (must start with `/`; no `?`, no host)
    #[arg(long, value_name = "PATH")]
    pub path: String,
    /// Raw body text passthrough (rides ANY method — curl parity)
    #[arg(long, value_name = "TEXT")]
    pub data: Option<String>,
    /// Extra request header `Name: Value` (repeatable; split on the
    /// FIRST `:`; auth-pattern names are refused pre-I/O)
    #[arg(long, value_name = "NAME: VALUE")]
    pub header: Vec<String>,
    /// Query pair `k=v` (repeatable; split on the FIRST `=` — the
    /// ONE query mechanism)
    #[arg(long, value_name = "K=V")]
    pub query: Vec<String>,
}

/// `ign license` args (09-04, EXT-02) — the license morning-check
/// family. One verb today; room to grow (the uniform-leaf shape).
#[derive(Debug, clap::Args)]
pub struct LicenseArgs {
    #[command(subcommand)]
    pub command: LicenseCommand,
}

#[derive(Debug, Subcommand)]
pub enum LicenseCommand {
    /// License inventory + trial state in ONE command: the
    /// hardware-key item rows and effective stamp ride the
    /// `/licenses` read, the license mode + countdown ride the trial
    /// companion (the mode is NOT on the licenses payload — capture
    /// fact)
    Status,
}

/// `ign redundancy` args (09-04, EXT-02) — the redundancy
/// morning-check family.
#[derive(Debug, clap::Args)]
pub struct RedundancyArgs {
    #[command(subcommand)]
    pub command: RedundancyCommand,
}

#[derive(Debug, Subcommand)]
pub enum RedundancyCommand {
    /// The flat redundancy status: role, project state, peer
    /// connection, config access, sync/failover pending, uptime
    /// (ms since gateway start — capture-proven) and last-sync (the
    /// `-1` never-synced sentinel on fresh rigs)
    Status {
        /// Also read a second node through PROFILE and name the active
        /// node (activity level decides, never role)
        #[arg(long, value_name = "PROFILE")]
        peer: Option<String>,
    },
}

/// `ign gan` args (09-04, EXT-02) — the Gateway Area Network
/// morning-check family.
#[derive(Debug, clap::Args)]
pub struct GanArgs {
    #[command(subcommand)]
    pub command: GanCommand,
}

#[derive(Debug, Subcommand)]
pub enum GanCommand {
    /// The GAN overview: total/running connections, in/out byte
    /// rates, remote gateways — all zeros are healthy data on a
    /// non-GAN gateway (the capture IS the canonical shape)
    Status,
}

/// `ign diagnostics` args (09-05, EXT-02) — the support-bundle
/// family: `bundle` nests one level (the `tags provider` grouped-
/// subfamily pattern).
#[derive(Debug, clap::Args)]
pub struct DiagnosticsArgs {
    #[command(subcommand)]
    pub command: DiagnosticsCommand,
}

#[derive(Debug, Subcommand)]
pub enum DiagnosticsCommand {
    /// Support-bundle operations (generate / status / download /
    /// wait) — the state machine is ENCODED FROM LIVE CAPTURES:
    /// observed states are exactly `Generating` (mid-generation) and
    /// `Valid` (terminal/ready), PascalCase, both rigs
    #[command(subcommand)]
    Bundle(BundleCommand),
}

/// The four bundle verbs (09-05). Nothing here is destructive:
/// generate creates a support bundle, download writes a local file,
/// wait polls — none carry `--yes` (the backup-download posture).
#[derive(Debug, Subcommand)]
pub enum BundleCommand {
    /// Start bundle generation (POST, no body) — the 200 answer IS
    /// the fresh status (live capture: `{"state":"Generating"}`);
    /// generation takes ~2–6 s on a fresh rig, so pair with `wait`
    Generate,
    /// The bundle status: `state` rides the CAPTURED vocabulary
    /// (`Generating` / `Valid` — unknown future states pass through
    /// verbatim, never refused); `fileSize` (bytes) appears only
    /// when `Valid`
    Status,
    /// Download the bundle ZIP (streamed to disk; the request rides
    /// a 300 s per-request timeout — the 30 s client default would
    /// truncate MB-sized bundles)
    Download {
        /// Output file (default: the gateway's Content-Disposition
        /// name, else ignition-diagnostics-bundle-<unix_ts>.zip)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
    },
    /// Poll the status until a terminal captured state (`Valid`)
    /// — an UNKNOWN state (outside the captured vocabulary) keeps
    /// polling honestly until the deadline; deadline expiry is
    /// exit 4 `network_error` (the restart-wait convention, no new
    /// slug) with the last observed state in the message
    Wait {
        /// Poll interval in seconds
        #[arg(long, default_value_t = 2, value_name = "SECS")]
        interval: u64,
        /// Give up after this many seconds (default 300 — mirrors
        /// restart --wait)
        #[arg(long, default_value_t = 300, value_name = "SECS")]
        timeout: u64,
    },
}

/// `ign jvm` args — the SPECIAL-MODE profiling family. Every leaf
/// carries `--project` (the deployed scriptExec route's home, the
/// `script run` default) and the intrusive leaves carry the family's
/// own gate flag: `--i-accept-the-risk` is deliberately NOT the
/// global `--yes` — a generic "confirm destructive ops" blanket must
/// never silently cover ACTIVE JVM instrumentation.
#[derive(Debug, clap::Args)]
pub struct JvmArgs {
    #[command(subcommand)]
    pub command: JvmCommand,
}

#[derive(Debug, Subcommand)]
pub enum JvmCommand {
    /// Sample every JVM thread's stack for a capped window and rank
    /// the hottest methods and stacks (the folded output is
    /// flamegraph-ready). ACTIVE instrumentation: CPU overhead grows
    /// with thread count x frequency — refused without
    /// --i-accept-the-risk; duration is HARD-CAPPED at 120s
    Sample {
        /// Seconds to sample per window (default 30 — 10 with
        /// --follow; 5–120, the cap is not configurable)
        #[arg(long, value_name = "SECS")]
        duration_secs: Option<u64>,
        /// Milliseconds between thread dumps (default 20 — 50 with
        /// --follow; 5–1000 — below 5ms the sampler thread itself
        /// skews the JVM)
        #[arg(long, value_name = "MS")]
        interval_ms: Option<u64>,
        /// Hot-method rows to report (default 25; cap 100)
        #[arg(long, default_value_t = 25, value_name = "N")]
        top: u64,
        /// Also write the folded stacks to this file (flamegraph.pl /
        /// speedscope input; one-shot only — refused with --follow)
        #[arg(long, value_name = "PATH")]
        folded_out: Option<PathBuf>,
        /// CONTINUOUS MODE: repeat bounded sampling windows
        /// back-to-back, streaming each window's rollup as it lands
        /// (NDJSON envelopes under --json/--compact, the `logs -f`
        /// precedent), until Ctrl-C. Continuous sampling IS
        /// continuous gateway overhead — watch it, then stop it
        #[arg(long, action = ArgAction::SetTrue)]
        follow: bool,
        /// REQUIRED acknowledgment that this actively instruments the
        /// gateway JVM and must not run on production casually —
        /// --yes does NOT satisfy this gate
        #[arg(long, action = ArgAction::SetTrue)]
        i_accept_the_risk: bool,
        /// The deployed routes' project (default ign-cli — where
        /// `ign webdev deploy` put scriptExec)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Java Flight Recorder operations — `start` is gated active
    /// instrumentation; `status` and `stop` are ungated (checking and
    /// cleaning up must always be cheap to reach)
    #[command(arg_required_else_help = true)]
    Jfr(JvmJfrArgs),
}

/// `ign jvm jfr` args (the `tags provider` grouped-subfamily pattern).
#[derive(Debug, clap::Args)]
pub struct JvmJfrArgs {
    #[command(subcommand)]
    pub command: JvmJfrCommand,
}

#[derive(Debug, Subcommand)]
pub enum JvmJfrCommand {
    /// Start a flight recording named `ign-cli` — memory-buffered
    /// (nothing touches gateway disk until `stop` dumps) and
    /// duration-capped so it auto-stops even if you forget. Refused
    /// without --i-accept-the-risk; duration HARD-CAPPED at 300s
    Start {
        /// Recording duration in seconds — the auto-stop deadline
        /// (default 60; 10–300, the cap is not configurable)
        #[arg(long, default_value_t = 60, value_name = "SECS")]
        duration_secs: u64,
        /// The JDK's bundled settings: `default` (lower overhead) or
        /// `profile` (deeper, heavier)
        #[arg(long, value_enum, default_value_t = JfrSettingsArg::Default, value_name = "NAME")]
        settings: JfrSettingsArg,
        /// REQUIRED acknowledgment that this actively instruments the
        /// gateway JVM and must not run on production casually —
        /// --yes does NOT satisfy this gate
        #[arg(long, action = ArgAction::SetTrue)]
        i_accept_the_risk: bool,
        /// The deployed routes' project (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// List the JVM's flight recordings verbatim (READ-only — not
    /// gated; this is how you confirm a recording is really gone)
    Status {
        /// The deployed routes' project (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
    /// Stop the `ign-cli` recording, dump it, fetch the .jfr, and
    /// delete the gateway-side file (cleanup — NOT gated: stopping
    /// reduces risk and must never be refused). Dumps over 32 MiB
    /// are left on the gateway with the remote path reported
    Stop {
        /// Local output file (default: ign-cli-<unix_ts>.jfr)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// The deployed routes' project (default ign-cli)
        #[arg(long, default_value = "ign-cli", value_name = "NAME")]
        project: String,
    },
}

/// The JFR settings whitelist as a clap ValueEnum (free text never
/// reaches the MBean invocation).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum JfrSettingsArg {
    /// `settings=default` — the lower-overhead bundled config
    Default,
    /// `settings=profile` — the deeper, heavier bundled config
    Profile,
}

/// Profile subcommands (nested: a struct wrapper carrying the subcommand
/// enum, so `Commands::Profile` gets an `Args` payload).
#[derive(Debug, clap::Args)]
pub struct ProfileArgs {
    #[command(subcommand)]
    pub command: ProfileCmd,
}

/// Sessions args: the family filter rides the TOP level so bare
/// `ign sessions [--type X]` lists (must-have truth #1) while
/// `ign sessions terminate …` carries the destructive half.
#[derive(Debug, clap::Args)]
pub struct SessionsArgs {
    /// Filter to one session family (default: all three merged)
    #[arg(long, value_enum)]
    pub r#type: Option<SessionType>,

    #[command(subcommand)]
    pub command: Option<SessionsCmd>,
}

#[derive(Debug, Subcommand)]
pub enum SessionsCmd {
    /// Terminate (designer: prune / vision: close) a session —
    /// destructive, refused without --yes
    Terminate {
        /// Session family holding the id
        #[arg(long, value_enum)]
        r#type: SessionType,
        /// Session/client id to terminate (see `ign sessions`)
        #[arg(long)]
        id: String,
        /// Message shown to the session's user (Perspective only)
        #[arg(long)]
        message: Option<String>,
    },
}

/// Logs args: the query filters ride the TOP level so bare
/// `ign logs [-f]` lists/tails (must-have truth #1) while `download`
/// and the `loggers` subtree hang off the optional subcommand — the
/// SessionsArgs precedent.
#[derive(Debug, clap::Args)]
pub struct LogsArgs {
    /// Only entries from this logger (name prefix)
    #[arg(long, value_name = "NAME")]
    pub logger: Option<String>,
    /// Minimum level to include (server-side filter)
    #[arg(long, value_enum, value_name = "LEVEL")]
    pub min_level: Option<LogLevel>,
    /// Start from an absolute EPOCH-MS or a relative span (500ms, 30s,
    /// 5min, 2h) — parsed to epoch-ms at arg-parse time
    #[arg(
        long,
        value_name = "EPOCH_MS|Nms|Ns|Nmin|Nh",
        value_parser = parse_since_arg
    )]
    pub since: Option<i64>,
    /// Max entries — the server default is UNLIMITED, never used here
    #[arg(long, default_value_t = 200)]
    pub limit: i64,
    /// Follow: stream new entries as they occur (poll-based)
    #[arg(short = 'f', long)]
    pub follow: bool,
    /// Poll interval in seconds (follow mode)
    #[arg(long, default_value_t = 2, value_name = "SECS")]
    pub interval: u64,
    /// Stop after this many seconds (follow mode; default: until Ctrl-C)
    #[arg(long, value_name = "SECS")]
    pub timeout: Option<u64>,
    #[command(subcommand)]
    pub command: Option<LogsCmd>,
}

#[derive(Debug, Subcommand)]
pub enum LogsCmd {
    /// Download the log archive — a SQLite .idb, never a zip
    Download {
        /// Output file (default: the gateway's Content-Disposition
        /// name, else <profile>-logs-<ts>.idb)
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,
    },
    /// List loggers / manage logger levels
    Loggers(LoggersArgs),
}

#[derive(Debug, clap::Args)]
pub struct LoggersArgs {
    /// Substring search over logger names
    #[arg(long, value_name = "TEXT")]
    pub search: Option<String>,
    #[command(subcommand)]
    pub command: Option<LoggersCmd>,
}

#[derive(Debug, Subcommand)]
pub enum LoggersCmd {
    /// Set one logger's level — a mutation, refused without --yes
    Set {
        /// Logger name (see `ign logs loggers`)
        name: String,
        /// Level to set
        #[arg(value_enum)]
        level: LogLevel,
    },
    /// Reset ALL logger levels to defaults — refused without --yes
    Reset,
}

/// The seven spec-documented log levels (TRACE..OFF), value-enum form
/// for clap; [`LogLevel::wire`] yields the uppercase wire token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum LogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
    Fatal,
    Off,
}

impl LogLevel {
    /// The uppercase wire token the gateway expects.
    pub fn wire(self) -> &'static str {
        match self {
            Self::Trace => "TRACE",
            Self::Debug => "DEBUG",
            Self::Info => "INFO",
            Self::Warn => "WARN",
            Self::Error => "ERROR",
            Self::Fatal => "FATAL",
            Self::Off => "OFF",
        }
    }
}

/// clap value parser delegating to the core `--since` grammar against
/// the current time (a relative span resolves at parse time) — invalid
/// specs are clap usage errors (exit 2) like any bad flag value.
fn parse_since_arg(spec: &str) -> Result<i64, String> {
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("system clock is after the unix epoch")
        .as_millis() as i64;
    ignition_core::actions::logs::parse_since(spec, now_ms)
}

/// CLI value-enum mirrors of the core action enums (ignition-core stays
/// clap-free; `From` converts at the dispatch seam).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SessionType {
    /// Designer sessions
    Designer,
    /// Perspective browser sessions
    Perspective,
    /// Vision clients
    Vision,
}

impl From<SessionType> for ignition_core::actions::sessions::SessionType {
    fn from(value: SessionType) -> Self {
        match value {
            SessionType::Designer => Self::Designer,
            SessionType::Perspective => Self::Perspective,
            SessionType::Vision => Self::Vision,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ConnectionType {
    /// Database connections
    Database,
    /// OPC connections
    Opc,
}

impl From<ConnectionType> for ignition_core::actions::connections::ConnectionType {
    fn from(value: ConnectionType) -> Self {
        match value {
            ConnectionType::Database => Self::Database,
            ConnectionType::Opc => Self::Opc,
        }
    }
}

/// Import collision policy (03-02). Exactly the two values REST
/// exposes — `merge` is the Designer import popup's vocabulary and is
/// NOT a value: clap's invalid-value error lists the two real
/// choices, and the README documents merge as Designer-only (the
/// sanctioned rejection-with-hint shape).
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum CollisionPolicy {
    /// Refuse when the project already exists (default)
    Abort,
    /// Replace the ENTIRE project (resources absent from the ZIP are
    /// deleted) — destructive, requires --yes
    Overwrite,
}

impl From<CollisionPolicy> for ignition_core::actions::projects::CollisionPolicy {
    fn from(value: CollisionPolicy) -> Self {
        match value {
            CollisionPolicy::Abort => Self::Abort,
            CollisionPolicy::Overwrite => Self::Overwrite,
        }
    }
}

#[derive(Debug, Subcommand)]
#[command(arg_required_else_help = true)]
pub enum ProfileCmd {
    /// Add (or overwrite) a gateway profile
    Add {
        /// Profile name
        name: String,
        /// Gateway base URL (e.g. http://localhost:9088)
        url: String,
        /// Optional display label
        #[arg(long, value_name = "TEXT")]
        label: Option<String>,
        /// Name of the env var holding the auth token
        #[arg(long, value_name = "VAR")]
        token_env: Option<String>,
        /// Keyring user string for the token (service is always ignition-cli)
        #[arg(long, value_name = "USER")]
        keyring: Option<String>,
        /// Name of the env var holding the basic-auth user (with --password-env)
        #[arg(long, value_name = "VAR")]
        user_env: Option<String>,
        /// Name of the env var holding the basic-auth password (with --user-env)
        #[arg(long, value_name = "VAR")]
        password_env: Option<String>,
        /// Make this profile the active one
        #[arg(long)]
        active: bool,
    },
    /// List configured profiles
    List,
    /// Switch the active profile
    Use {
        /// Profile name to activate
        name: String,
    },
}