shardline 1.0.0

Self-hosted Shardline CAS server and operator CLI for Git/Xet storage workflows.
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
use std::{ffi::OsString, fmt, num::NonZeroUsize, path::PathBuf};

use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum, error::ErrorKind};
use shardline_protocol::{RepositoryProvider, TokenScope};
use shardline_server::{
    DEFAULT_LOCAL_GC_RETENTION_SECONDS, DEFAULT_WEBHOOK_DELIVERY_RETENTION_SECONDS,
    DatabaseMigrationCommand, ObjectStorageAdapter, ServerFrontend, ServerRole,
};
use thiserror::Error;

use crate::bench::{BenchDeploymentTarget, BenchScenario};

/// Wrapper that redacts sensitive database URLs in Debug output.
#[derive(Clone, PartialEq, Eq)]
pub struct RedactedDbUrl(String);

impl RedactedDbUrl {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for RedactedDbUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("***")
    }
}

const CLI_AFTER_LONG_HELP: &str = "\
Examples:
  shardline providerless setup
  shardline serve --role all
  shardline config check
  shardline gc --mark --sweep --retention-seconds 86400
  shardline gc schedule install --env-file /etc/shardline/shardline.env --user shardline --group shardline
  shardline storage migrate --from local --from-root /srv/assets/.shardline/data --to s3 --prefix xorbs/default/
  shardline bench --mode ingest --iterations 5 --concurrency 16
  shardline completion bash > /usr/share/bash-completion/completions/shardline
  shardline manpage --output ./shardline.1";

const GC_INSTALL_AFTER_LONG_HELP: &str = "\
Examples:
  shardline gc schedule install --output-dir ./systemd --env-file /etc/shardline/shardline.env --user shardline --group shardline
  shardline gc schedule install --calendar 'hourly' --retention-seconds 600 --binary-path /usr/local/bin/shardline";

const BENCH_AFTER_LONG_HELP: &str = "\
Examples:
  shardline bench --storage-dir /var/lib/shardline-bench
  shardline bench --storage-dir /var/lib/shardline-bench --deployment-target configured
  shardline bench --storage-dir /var/lib/shardline-bench --scenario cross-repository-upload --iterations 5
  shardline bench --mode ingest --iterations 10 --concurrency 32 --chunk-size-bytes 1048576";

const COMPLETION_AFTER_HELP: &str = "\
Examples:
  shardline completion bash
  shardline completion zsh --output ./_shardline
  shardline completion fish --output ~/.config/fish/completions/shardline.fish";

const MANPAGE_AFTER_HELP: &str = "\
Examples:
  shardline manpage
  shardline manpage --output ./shardline.1";

/// Supported Shardline CLI commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CliCommand {
    /// Bootstrap a providerless local source-checkout deployment.
    ProviderlessSetup,
    /// Run the server.
    Serve {
        /// Optional role override for the current process.
        role: Option<ServerRole>,
        /// Optional protocol frontend override for the current process.
        frontends: Option<Vec<ServerFrontend>>,
    },
    /// Validate configuration.
    ConfigCheck,
    /// Manage the Postgres metadata schema.
    DbMigrate {
        /// Optional explicit Postgres metadata URL override.
        database_url: Option<RedactedDbUrl>,
        /// Requested migration action.
        command: DatabaseMigrationCommand,
    },
    /// Manage local administrative tokens.
    AdminToken {
        /// Issuer embedded in the signed token.
        issuer: String,
        /// Subject embedded in the signed token.
        subject: String,
        /// Granted CAS scope.
        scope: TokenScope,
        /// Repository hosting provider.
        provider: RepositoryProvider,
        /// Repository owner or namespace.
        owner: String,
        /// Repository name.
        repo: String,
        /// Scoped revision when one is required.
        revision: Option<String>,
        /// Token lifetime in seconds.
        ttl_seconds: u64,
        /// Local signing-key file path.
        key_file: Option<PathBuf>,
        /// Environment variable that stores the signing key.
        key_env: Option<String>,
    },
    /// Verify object and index integrity.
    Fsck {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
    },
    /// Rebuild latest-record state from immutable version records.
    IndexRebuild {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
    },
    /// Run garbage collection.
    Gc {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Persist currently orphaned chunks into durable quarantine state.
        mark: bool,
        /// Delete orphan chunks after reporting them.
        sweep: bool,
        /// Retention window applied to newly quarantined chunks.
        retention_seconds: u64,
        /// Optional JSON file that receives active quarantine state after the run.
        retention_report: Option<PathBuf>,
        /// Optional JSON file that receives current orphan inventory after the run.
        orphan_inventory: Option<PathBuf>,
    },
    /// Install scheduled garbage-collection systemd units.
    GcScheduleInstall {
        /// Directory that receives the generated systemd units.
        output_dir: PathBuf,
        /// Unit basename without `.service` or `.timer`.
        unit_prefix: String,
        /// `systemd.timer` calendar expression.
        calendar: String,
        /// Retention window passed to the scheduled collector.
        retention_seconds: u64,
        /// Path to the `shardline` binary in the generated unit.
        binary_path: PathBuf,
        /// Environment file referenced by the generated unit.
        env_file: PathBuf,
        /// Working directory and writable state path.
        working_directory: PathBuf,
        /// Service user.
        user: String,
        /// Service group.
        group: String,
    },
    /// Remove scheduled garbage-collection systemd units.
    GcScheduleUninstall {
        /// Directory that contains the generated systemd units.
        output_dir: PathBuf,
        /// Unit basename without `.service` or `.timer`.
        unit_prefix: String,
    },
    /// Repair stale lifecycle metadata.
    Repair {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Retention applied to processed webhook delivery claims.
        webhook_retention_seconds: u64,
    },
    /// Repair stale lifecycle metadata.
    RepairLifecycle {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Retention applied to processed webhook delivery claims.
        webhook_retention_seconds: u64,
    },
    /// Export an adapter-neutral backup manifest.
    BackupManifest {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// JSON manifest output path.
        output: PathBuf,
    },
    /// Copy immutable payload objects between object-storage adapters.
    StorageMigrate {
        /// Source object-storage adapter.
        from: ObjectStorageAdapter,
        /// Optional source local state root.
        from_root: Option<PathBuf>,
        /// Destination object-storage adapter.
        to: ObjectStorageAdapter,
        /// Optional destination local state root.
        to_root: Option<PathBuf>,
        /// Object-key prefix to migrate.
        prefix: String,
        /// Whether to inventory without writing destination objects.
        dry_run: bool,
    },
    /// Create or update a retention hold.
    HoldSet {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Object-store key protected by the hold.
        object_key: String,
        /// Operator-supplied hold reason.
        reason: String,
        /// Optional time-to-live in seconds.
        ttl_seconds: Option<u64>,
    },
    /// List retention holds.
    HoldList {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Whether to exclude expired holds.
        active_only: bool,
    },
    /// Release one retention hold.
    HoldRelease {
        /// Optional deployment-root override for the active Shardline config.
        root: Option<PathBuf>,
        /// Object-store key released from protection.
        object_key: String,
    },
    /// Run storage and protocol benchmarks.
    Bench {
        /// Benchmark mode.
        mode: BenchMode,
        /// End-to-end benchmark deployment target.
        deployment_target: BenchDeploymentTarget,
        /// Focused benchmark scenario.
        scenario: BenchScenario,
        /// Root directory used to create isolated benchmark iteration stores.
        storage_dir: Option<PathBuf>,
        /// Number of benchmark iterations to run.
        iterations: u32,
        /// Number of concurrent workers used for concurrent sub-scenarios.
        concurrency: u32,
        /// Maximum upload chunks processed in parallel per upload.
        upload_max_in_flight_chunks: usize,
        /// Chunk size in bytes used by the local benchmark backend.
        chunk_size_bytes: usize,
        /// Logical size of the benchmark asset in bytes.
        base_bytes: usize,
        /// Number of bytes changed in the sparse-update benchmark step.
        mutated_bytes: usize,
        /// Whether to emit the full report as JSON.
        json: bool,
    },
    /// Check server health.
    Health {
        /// Shardline server base URL.
        server_url: String,
    },
    /// Generate shell-completion scripts.
    Completion {
        /// Target shell.
        shell: CompletionShell,
        /// Optional output path. Defaults to stdout.
        output: Option<PathBuf>,
    },
    /// Generate one manpage for the CLI.
    Manpage {
        /// Optional output path. Defaults to stdout.
        output: Option<PathBuf>,
    },
}

/// Supported benchmark modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum BenchMode {
    /// Run the full end-to-end storage benchmark suite.
    #[value(name = "e2e")]
    EndToEnd,
    /// Run the zero-storage upload-ingest benchmark suite.
    #[value(name = "ingest")]
    Ingest,
}

#[derive(Debug, Parser)]
#[command(
    name = "shardline",
    about = "Content-addressed storage server and operations CLI.",
    long_about = "Shardline serves CAS protocol frontends, provider integration, storage maintenance, and operational workflows from one CLI.\n\nThe current frontend set in this repository is Xet, Git LFS, Bazel HTTP remote cache, and OCI Distribution.\n\nUse `shardline help <command>` to inspect a command in detail.",
    after_help = CLI_AFTER_LONG_HELP,
    arg_required_else_help = true,
    next_line_help = true
)]
struct CliDefinition {
    #[command(subcommand)]
    command: CliDefinitionCommand,
}

#[derive(Debug, Subcommand)]
enum CliDefinitionCommand {
    /// Bootstrap a local providerless source-checkout deployment.
    Providerless(ProviderlessCommandArgs),
    /// Run the Shardline server.
    Serve(ServeArgs),
    /// Validate the effective runtime configuration.
    Config(ConfigCommandArgs),
    /// Manage the Postgres metadata schema.
    Db(DbCommandArgs),
    /// Mint a local administrative token.
    Admin(AdminCommandArgs),
    /// Verify object-store and metadata integrity.
    Fsck(RootArgs),
    /// Rebuild mutable indexes from immutable version state.
    Index(IndexCommandArgs),
    /// Repair lifecycle metadata and webhook delivery state.
    Repair(RepairCommandArgs),
    /// Export recovery artifacts.
    Backup(BackupCommandArgs),
    /// Copy immutable objects between storage adapters.
    Storage(StorageCommandArgs),
    /// Run garbage collection or install a schedule.
    Gc(GcCommandArgs),
    /// Manage retention holds.
    Hold(HoldCommandArgs),
    /// Run performance benchmarks.
    Bench(BenchArgs),
    /// Probe server health.
    Health(HealthArgs),
    /// Generate shell-completion scripts for supported shells.
    Completion(CompletionArgs),
    /// Generate a manpage for packaged or self-hosted deployments.
    Manpage(ManpageArgs),
}

#[derive(Debug, Args)]
#[command(
    about = "Bootstrap a local providerless source-checkout deployment.",
    long_about = "Create the `.shardline` local state directory, generate a signing key, and write a providerless environment file for a source checkout.\n\nThis command only prepares local state. `shardline serve` and `shardline config check` also auto-bootstrap the same layout when they run from a fresh source checkout."
)]
struct ProviderlessCommandArgs {
    #[command(subcommand)]
    command: ProviderlessSubcommand,
}

#[derive(Debug, Subcommand)]
enum ProviderlessSubcommand {
    /// Create `.shardline/`, `.shardline/data`, the signing key, and `providerless.env`.
    Setup,
}

#[derive(Debug, Args)]
#[command(
    about = "Run the Shardline server.",
    long_about = "Start the Shardline process for single-node deployments or for one split-role process.\n\nThe active environment still supplies the adapter and provider wiring. `--role` only selects which server surface this process exposes. `--frontend` selects which protocol frontends this process serves."
)]
struct ServeArgs {
    /// Pin the process to `all`, `api`, or `transfer`.
    #[arg(long, value_enum)]
    role: Option<CliServerRole>,
    /// Enable one or more protocol frontends. Repeat the flag or pass a comma-separated list.
    #[arg(long = "frontend", value_enum, value_delimiter = ',', action = clap::ArgAction::Append, num_args = 1..)]
    frontends: Vec<CliServerFrontend>,
}

#[derive(Debug, Args)]
#[command(
    about = "Validate the effective runtime configuration.",
    long_about = "Load the active Shardline environment, resolve adapters, and report the effective runtime profile without starting the server."
)]
struct ConfigCommandArgs {
    #[command(subcommand)]
    command: ConfigSubcommand,
}

#[derive(Debug, Subcommand)]
enum ConfigSubcommand {
    /// Validate the active environment and adapter wiring.
    Check,
}

#[derive(Debug, Args)]
#[command(
    about = "Manage the Postgres metadata schema.",
    long_about = "Apply, revert, or inspect the Shardline metadata schema used by Postgres-backed index state."
)]
struct DbCommandArgs {
    #[command(subcommand)]
    command: DbSubcommand,
}

#[derive(Debug, Subcommand)]
enum DbSubcommand {
    /// Apply, revert, or inspect metadata migrations.
    Migrate(DbMigrateCommandArgs),
}

#[derive(Debug, Args)]
struct DbMigrateCommandArgs {
    #[command(subcommand)]
    command: DbMigrateSubcommand,
}

#[derive(Debug, Subcommand)]
enum DbMigrateSubcommand {
    /// Apply pending migrations.
    Up(DbMigrateUpArgs),
    /// Revert applied migrations.
    Down(DbMigrateDownArgs),
    /// Show applied and pending migrations.
    Status(DbMigrateStatusArgs),
}

#[derive(Debug, Args)]
struct DbMigrateUpArgs {
    /// Override the configured Postgres metadata URL.
    #[arg(long)]
    database_url: Option<String>,
    /// Limit the number of migrations to apply.
    #[arg(long, value_parser = parse_positive_usize)]
    steps: Option<NonZeroUsize>,
}

#[derive(Debug, Args)]
struct DbMigrateDownArgs {
    /// Override the configured Postgres metadata URL.
    #[arg(long)]
    database_url: Option<String>,
    /// Limit the number of migrations to revert.
    #[arg(long, value_parser = parse_positive_usize)]
    steps: Option<NonZeroUsize>,
}

#[derive(Debug, Args)]
struct DbMigrateStatusArgs {
    /// Override the configured Postgres metadata URL.
    #[arg(long)]
    database_url: Option<String>,
}

#[derive(Debug, Args)]
#[command(
    about = "Mint a local administrative token.",
    long_about = "Create a signed bearer token for self-hosted operations, provider mediation, or debugging workflows."
)]
struct AdminCommandArgs {
    #[command(subcommand)]
    command: AdminSubcommand,
}

#[derive(Debug, Subcommand)]
enum AdminSubcommand {
    /// Mint a local bearer token for self-hosted operation and testing.
    Token(AdminTokenArgs),
}

#[derive(Debug, Args)]
struct AdminTokenArgs {
    /// Token issuer identifier.
    #[arg(long)]
    issuer: String,
    /// Token subject identifier.
    #[arg(long)]
    subject: String,
    /// Granted repository scope.
    #[arg(long, value_enum)]
    scope: CliTokenScope,
    /// Repository hosting provider.
    #[arg(long, value_enum)]
    provider: CliRepositoryProvider,
    /// Repository owner or namespace.
    #[arg(long)]
    owner: String,
    /// Repository name.
    #[arg(long)]
    repo: String,
    /// Scoped revision when one is required.
    #[arg(long)]
    revision: Option<String>,
    /// Token lifetime in seconds.
    #[arg(long, default_value_t = 3_600_u64)]
    ttl_seconds: u64,
    /// Local signing-key file path.
    #[arg(long, conflicts_with = "key_env", required_unless_present = "key_env")]
    key_file: Option<PathBuf>,
    /// Environment variable that stores the signing key.
    #[arg(
        long,
        conflicts_with = "key_file",
        required_unless_present = "key_file"
    )]
    key_env: Option<String>,
}

#[derive(Debug, Args)]
struct IndexCommandArgs {
    #[command(subcommand)]
    command: IndexSubcommand,
}

#[derive(Debug, Subcommand)]
enum IndexSubcommand {
    /// Rebuild latest-file and dedupe indexes from immutable history.
    Rebuild(RootArgs),
}

#[derive(Debug, Args)]
#[command(
    about = "Repair lifecycle metadata and webhook delivery state.",
    long_about = "Run the repair orchestrator for local or Postgres-backed metadata.\n\n`repair` runs the full repair flow. `repair lifecycle` limits the run to lifecycle-specific reconciliation."
)]
struct RepairCommandArgs {
    #[command(subcommand)]
    command: Option<RepairSubcommand>,
    #[command(flatten)]
    options: RepairOptionsArgs,
}

#[derive(Debug, Subcommand)]
enum RepairSubcommand {
    /// Repair lifecycle state only.
    Lifecycle(RepairOptionsArgs),
}

#[derive(Debug, Clone, Args)]
struct RepairOptionsArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Retention window for processed webhook-delivery claims.
    #[arg(
        long,
        default_value_t = DEFAULT_WEBHOOK_DELIVERY_RETENTION_SECONDS
    )]
    webhook_retention_seconds: u64,
}

#[derive(Debug, Args)]
#[command(
    about = "Export recovery artifacts.",
    long_about = "Generate recovery data that can be used to audit or rebuild Shardline metadata state."
)]
struct BackupCommandArgs {
    #[command(subcommand)]
    command: BackupSubcommand,
}

#[derive(Debug, Subcommand)]
enum BackupSubcommand {
    /// Export an adapter-neutral backup manifest.
    Manifest(BackupManifestArgs),
}

#[derive(Debug, Args)]
struct BackupManifestArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Manifest output path.
    #[arg(long)]
    output: PathBuf,
}

#[derive(Debug, Args)]
#[command(
    about = "Copy immutable objects between storage adapters.",
    long_about = "Inventory immutable payload objects under one object-storage adapter and copy them into another adapter.\n\nThis is intended for storage migrations, dry runs, and object namespace moves."
)]
struct StorageCommandArgs {
    #[command(subcommand)]
    command: StorageSubcommand,
}

#[derive(Debug, Subcommand)]
enum StorageSubcommand {
    /// Copy immutable payload objects between object-storage adapters.
    Migrate(StorageMigrateArgs),
}

#[derive(Debug, Args)]
struct StorageMigrateArgs {
    /// Source object-storage adapter.
    #[arg(long, value_enum)]
    from: CliObjectStorageAdapter,
    /// Local state root when the source adapter is `local`.
    #[arg(long)]
    from_root: Option<PathBuf>,
    /// Destination object-storage adapter.
    #[arg(long, value_enum)]
    to: CliObjectStorageAdapter,
    /// Local state root when the destination adapter is `local`.
    #[arg(long)]
    to_root: Option<PathBuf>,
    /// Object-key prefix to migrate.
    #[arg(long, default_value_t = String::new())]
    prefix: String,
    /// Inventory objects without writing destination payloads.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
#[command(
    about = "Run garbage collection or install a schedule.",
    long_about = "Run mark, sweep, or dry-run garbage collection against the active metadata and object adapters.\n\nUse `gc schedule` to generate validated systemd units for recurring collector runs."
)]
struct GcCommandArgs {
    #[command(subcommand)]
    command: Option<GcSubcommand>,
    #[command(flatten)]
    options: GcOptionsArgs,
}

#[derive(Debug, Subcommand)]
enum GcSubcommand {
    /// Install or remove a systemd timer for garbage collection.
    Schedule(GcScheduleCommandArgs),
}

#[derive(Debug, Args)]
#[command(
    about = "Install or remove a systemd timer for garbage collection.",
    long_about = "Generate or remove a systemd `.service` and `.timer` pair for scheduled garbage collection.\n\nThe install workflow validates the target binary, environment file, user, group, and referenced secret/config files before writing units."
)]
struct GcScheduleCommandArgs {
    #[command(subcommand)]
    command: GcScheduleSubcommand,
}

#[derive(Debug, Subcommand)]
enum GcScheduleSubcommand {
    /// Generate validated systemd units for scheduled garbage collection.
    Install(GcScheduleInstallArgs),
    /// Remove generated garbage-collection systemd units.
    Uninstall(GcScheduleUninstallArgs),
}

#[derive(Debug, Clone, Args)]
struct GcOptionsArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Persist currently orphaned chunks into quarantine.
    #[arg(long)]
    mark: bool,
    /// Delete eligible orphaned chunks after reporting them.
    #[arg(long)]
    sweep: bool,
    /// Retention window for newly quarantined chunks.
    #[arg(long, default_value_t = DEFAULT_LOCAL_GC_RETENTION_SECONDS)]
    retention_seconds: u64,
    /// Write active quarantine state to a JSON report.
    #[arg(long)]
    retention_report: Option<PathBuf>,
    /// Write the current orphan inventory to a JSON report.
    #[arg(long)]
    orphan_inventory: Option<PathBuf>,
}

#[derive(Debug, Args)]
#[command(
    about = "Generate validated systemd units for scheduled garbage collection.",
    long_about = "Write a `systemd` service and timer for `shardline gc`.\n\nThe installer resolves the active Shardline binary when the default path is left in place, requires the environment file to exist, honors `SHARDLINE_ROOT_DIR`, and validates referenced secret/config files plus the selected service user and group.",
    after_help = GC_INSTALL_AFTER_LONG_HELP
)]
struct GcScheduleInstallArgs {
    /// Directory that receives the generated systemd units.
    #[arg(long, default_value = "/etc/systemd/system")]
    output_dir: PathBuf,
    /// Unit basename without `.service` or `.timer`.
    #[arg(long, default_value = "shardline-gc")]
    unit_prefix: String,
    /// `systemd.timer` calendar expression.
    #[arg(long, default_value = "*-*-* 03:17:00")]
    calendar: String,
    /// Retention window passed to the scheduled collector.
    #[arg(long, default_value_t = 86_400_u64)]
    retention_seconds: u64,
    /// Path to the `shardline` binary embedded in the unit.
    #[arg(long, default_value = "/usr/local/bin/shardline")]
    binary_path: PathBuf,
    /// Environment file referenced by the generated service.
    #[arg(long, default_value = "/etc/shardline/shardline.env")]
    env_file: PathBuf,
    /// Working directory and writable state path.
    #[arg(long, default_value = "/var/lib/shardline")]
    working_directory: PathBuf,
    /// Service user.
    #[arg(long, default_value = "shardline")]
    user: String,
    /// Service group.
    #[arg(long, default_value = "shardline")]
    group: String,
}

#[derive(Debug, Args)]
struct GcScheduleUninstallArgs {
    /// Directory that contains the generated systemd units.
    #[arg(long, default_value = "/etc/systemd/system")]
    output_dir: PathBuf,
    /// Unit basename without `.service` or `.timer`.
    #[arg(long, default_value = "shardline-gc")]
    unit_prefix: String,
}

#[derive(Debug, Args)]
#[command(
    about = "Manage retention holds.",
    long_about = "Create, list, and release retention holds that protect object keys from garbage collection."
)]
struct HoldCommandArgs {
    #[command(subcommand)]
    command: HoldSubcommand,
}

#[derive(Debug, Subcommand)]
enum HoldSubcommand {
    /// Create or update a retention hold.
    Set(HoldSetArgs),
    /// List retention holds.
    List(HoldListArgs),
    /// Release one retention hold.
    Release(HoldReleaseArgs),
}

#[derive(Debug, Args)]
struct HoldSetArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Object-store key protected by the hold.
    #[arg(long)]
    object_key: String,
    /// Human-readable hold reason.
    #[arg(long)]
    reason: String,
    /// Optional hold time-to-live in seconds.
    #[arg(long)]
    ttl_seconds: Option<u64>,
}

#[derive(Debug, Args)]
struct HoldListArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Exclude expired holds.
    #[arg(long)]
    active_only: bool,
}

#[derive(Debug, Args)]
struct HoldReleaseArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
    /// Object-store key released from protection.
    #[arg(long)]
    object_key: String,
}

#[derive(Debug, Args)]
#[command(
    about = "Run performance benchmarks.",
    long_about = "Measure upload, download, reconstruction, and concurrency behavior.\n\n`e2e` mode can run either an isolated local SQLite plus filesystem deployment or the active configured runtime backend, and requires `--storage-dir`. `ingest` mode measures upload ingestion without storing payloads.",
    after_help = BENCH_AFTER_LONG_HELP
)]
struct BenchArgs {
    /// Benchmark mode.
    #[arg(long, value_enum, default_value_t = BenchMode::EndToEnd)]
    mode: BenchMode,
    /// End-to-end benchmark deployment target.
    #[arg(long, value_enum, default_value_t = BenchDeploymentTarget::IsolatedLocal)]
    deployment_target: BenchDeploymentTarget,
    /// Focus one benchmark scenario instead of running all steps.
    #[arg(long, value_enum, default_value_t = BenchScenario::Full)]
    scenario: BenchScenario,
    /// Root directory used to create isolated benchmark iteration stores.
    #[arg(long)]
    storage_dir: Option<PathBuf>,
    /// Number of benchmark iterations to run.
    #[arg(long, default_value_t = 1_u32)]
    iterations: u32,
    /// Number of concurrent workers used for concurrent sub-scenarios.
    #[arg(long, default_value_t = 4_u32)]
    concurrency: u32,
    /// Maximum upload chunks processed in parallel per upload.
    #[arg(long, default_value_t = 64_usize)]
    upload_max_in_flight_chunks: usize,
    /// Chunk size in bytes used by the local benchmark backend.
    #[arg(long, default_value_t = 65_536_usize)]
    chunk_size_bytes: usize,
    /// Logical size of the benchmark asset in bytes.
    #[arg(long, default_value_t = 1_048_576_usize)]
    base_bytes: usize,
    /// Number of bytes changed in the sparse-update benchmark step.
    #[arg(long, default_value_t = 4_096_usize)]
    mutated_bytes: usize,
    /// Emit the full report as JSON.
    #[arg(long)]
    json: bool,
}

#[derive(Debug, Args)]
#[command(
    about = "Probe server health.",
    long_about = "Send a health probe to a running Shardline server and fail when the server does not answer successfully."
)]
struct HealthArgs {
    /// Base URL of the Shardline server to probe.
    #[arg(long = "server")]
    server_url: String,
}

#[derive(Debug, Args)]
#[command(
    about = "Generate shell-completion scripts for supported shells.",
    long_about = "Render a completion script from the live Shardline CLI definition.\n\nThis keeps shell completions aligned with the real command surface instead of shipping a handwritten static script.",
    after_help = COMPLETION_AFTER_HELP
)]
struct CompletionArgs {
    /// Target shell.
    #[arg(value_enum)]
    shell: CompletionShell,
    /// Write the generated script to one file instead of stdout.
    #[arg(long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Args)]
#[command(
    about = "Generate a manpage for packaged or self-hosted deployments.",
    long_about = "Render a manpage from the live Shardline CLI definition.\n\nThis is intended for packaging, system installations, and offline operator documentation.",
    after_help = MANPAGE_AFTER_HELP
)]
struct ManpageArgs {
    /// Write the generated manpage to one file instead of stdout.
    #[arg(long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Default, Args)]
struct RootArgs {
    /// Override the deployment root for local metadata state.
    #[arg(long)]
    root: Option<PathBuf>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliServerRole {
    /// Serve both control-plane and transfer routes from one process.
    All,
    /// Serve control-plane and metadata routes only.
    Api,
    /// Serve upload and download routes only.
    Transfer,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliServerFrontend {
    /// Serve the validated Xet-compatible CAS frontend.
    Xet,
    /// Serve the Git LFS batch and object-transfer frontend.
    Lfs,
    /// Serve the Bazel-compatible HTTP remote-cache frontend.
    #[value(name = "bazel-http")]
    BazelHttp,
    /// Serve the OCI Distribution frontend.
    Oci,
    /// Serve the HuggingFace Hub API compatibility frontend.
    Hub,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliTokenScope {
    /// Allow read-only access.
    Read,
    /// Allow writes and uploads.
    Write,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliRepositoryProvider {
    /// GitHub repository hosting.
    #[value(name = "github")]
    GitHub,
    /// Gitea repository hosting.
    #[value(name = "gitea")]
    Gitea,
    /// GitLab repository hosting.
    #[value(name = "gitlab")]
    GitLab,
    /// Codeberg (Gitea-based) repository hosting.
    #[value(name = "codeberg")]
    Codeberg,
    /// Generic Git provider integration.
    #[value(name = "generic")]
    Generic,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CliObjectStorageAdapter {
    /// Local filesystem-backed object storage.
    Local,
    /// S3-compatible object storage.
    S3,
}

/// Supported completion targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum CompletionShell {
    /// Bash completion script.
    Bash,
    /// Elvish completion script.
    Elvish,
    /// Fish completion script.
    Fish,
    /// PowerShell completion script.
    #[value(name = "powershell")]
    PowerShell,
    /// Zsh completion script.
    Zsh,
}

impl CliCommand {
    /// Parses a command from process arguments.
    ///
    /// # Errors
    ///
    /// Returns [`CliParseError`] when the argument vector is invalid or help/version
    /// output was requested.
    pub fn parse<I, T>(args: I) -> Result<Self, CliParseError>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut args = args.into_iter().map(Into::into).collect::<Vec<OsString>>();
        if args.is_empty() {
            args.push(OsString::from("shardline"));
        }

        let definition = CliDefinition::try_parse_from(args).map_err(CliParseError::from)?;
        Self::try_from(definition)
    }

    /// Returns top-level help text.
    #[must_use]
    pub fn help_text() -> String {
        cli_definition_command().render_long_help().to_string()
    }
}

/// CLI parse failure.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[error("{message}")]
pub struct CliParseError {
    kind: ErrorKind,
    message: String,
}

impl CliParseError {
    /// Returns the underlying clap error kind.
    #[must_use]
    pub const fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns whether this parse failure represents help or version output.
    #[must_use]
    pub const fn is_help(&self) -> bool {
        matches!(
            self.kind,
            ErrorKind::DisplayHelp
                | ErrorKind::DisplayVersion
                | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
        )
    }

    fn validation(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

impl From<clap::Error> for CliParseError {
    fn from(error: clap::Error) -> Self {
        Self {
            kind: error.kind(),
            message: format!("{error}"),
        }
    }
}

impl TryFrom<CliDefinition> for CliCommand {
    type Error = CliParseError;

    fn try_from(value: CliDefinition) -> Result<Self, Self::Error> {
        match value.command {
            CliDefinitionCommand::Providerless(args) => match args.command {
                ProviderlessSubcommand::Setup => Ok(Self::ProviderlessSetup),
            },
            CliDefinitionCommand::Serve(args) => Ok(Self::Serve {
                role: args.role.map(Into::into),
                frontends: if args.frontends.is_empty() {
                    None
                } else {
                    Some(deduplicated_cli_frontends(
                        args.frontends.into_iter().map(Into::into),
                    ))
                },
            }),
            CliDefinitionCommand::Config(args) => match args.command {
                ConfigSubcommand::Check => Ok(Self::ConfigCheck),
            },
            CliDefinitionCommand::Db(db_args) => match db_args.command {
                DbSubcommand::Migrate(migrate) => match migrate.command {
                    DbMigrateSubcommand::Up(up_args) => Ok(Self::DbMigrate {
                        database_url: up_args.database_url.map(RedactedDbUrl),
                        command: DatabaseMigrationCommand::Up {
                            steps: up_args.steps.map(NonZeroUsize::get),
                        },
                    }),
                    DbMigrateSubcommand::Down(down_args) => Ok(Self::DbMigrate {
                        database_url: down_args.database_url.map(RedactedDbUrl),
                        command: DatabaseMigrationCommand::Down {
                            steps: down_args.steps.map_or(1, NonZeroUsize::get),
                        },
                    }),
                    DbMigrateSubcommand::Status(status_args) => Ok(Self::DbMigrate {
                        database_url: status_args.database_url.map(RedactedDbUrl),
                        command: DatabaseMigrationCommand::Status,
                    }),
                },
            },
            CliDefinitionCommand::Admin(args) => match args.command {
                AdminSubcommand::Token(args) => Ok(Self::AdminToken {
                    issuer: args.issuer,
                    subject: args.subject,
                    scope: args.scope.into(),
                    provider: args.provider.into(),
                    owner: args.owner,
                    repo: args.repo,
                    revision: args.revision,
                    ttl_seconds: args.ttl_seconds,
                    key_file: args.key_file,
                    key_env: args.key_env,
                }),
            },
            CliDefinitionCommand::Fsck(args) => Ok(Self::Fsck { root: args.root }),
            CliDefinitionCommand::Index(args) => match args.command {
                IndexSubcommand::Rebuild(args) => Ok(Self::IndexRebuild { root: args.root }),
            },
            CliDefinitionCommand::Repair(args) => match args.command {
                Some(RepairSubcommand::Lifecycle(options)) => Ok(Self::RepairLifecycle {
                    root: options.root,
                    webhook_retention_seconds: options.webhook_retention_seconds,
                }),
                None => Ok(Self::Repair {
                    root: args.options.root,
                    webhook_retention_seconds: args.options.webhook_retention_seconds,
                }),
            },
            CliDefinitionCommand::Backup(args) => match args.command {
                BackupSubcommand::Manifest(args) => Ok(Self::BackupManifest {
                    root: args.root,
                    output: args.output,
                }),
            },
            CliDefinitionCommand::Storage(args) => match args.command {
                StorageSubcommand::Migrate(args) => Ok(Self::StorageMigrate {
                    from: args.from.into(),
                    from_root: args.from_root,
                    to: args.to.into(),
                    to_root: args.to_root,
                    prefix: args.prefix,
                    dry_run: args.dry_run,
                }),
            },
            CliDefinitionCommand::Gc(gc_args) => match gc_args.command {
                Some(GcSubcommand::Schedule(schedule)) => match schedule.command {
                    GcScheduleSubcommand::Install(install_args) => Ok(Self::GcScheduleInstall {
                        output_dir: install_args.output_dir,
                        unit_prefix: install_args.unit_prefix,
                        calendar: install_args.calendar,
                        retention_seconds: install_args.retention_seconds,
                        binary_path: install_args.binary_path,
                        env_file: install_args.env_file,
                        working_directory: install_args.working_directory,
                        user: install_args.user,
                        group: install_args.group,
                    }),
                    GcScheduleSubcommand::Uninstall(uninstall_args) => {
                        Ok(Self::GcScheduleUninstall {
                            output_dir: uninstall_args.output_dir,
                            unit_prefix: uninstall_args.unit_prefix,
                        })
                    }
                },
                None => Ok(Self::Gc {
                    root: gc_args.options.root,
                    mark: gc_args.options.mark,
                    sweep: gc_args.options.sweep,
                    retention_seconds: gc_args.options.retention_seconds,
                    retention_report: gc_args.options.retention_report,
                    orphan_inventory: gc_args.options.orphan_inventory,
                }),
            },
            CliDefinitionCommand::Hold(args) => match args.command {
                HoldSubcommand::Set(args) => Ok(Self::HoldSet {
                    root: args.root,
                    object_key: args.object_key,
                    reason: args.reason,
                    ttl_seconds: args.ttl_seconds,
                }),
                HoldSubcommand::List(args) => Ok(Self::HoldList {
                    root: args.root,
                    active_only: args.active_only,
                }),
                HoldSubcommand::Release(args) => Ok(Self::HoldRelease {
                    root: args.root,
                    object_key: args.object_key,
                }),
            },
            CliDefinitionCommand::Bench(args) => {
                if args.mode == BenchMode::EndToEnd && args.storage_dir.is_none() {
                    return Err(CliParseError::validation(
                        ErrorKind::MissingRequiredArgument,
                        "end-to-end benchmark mode requires --storage-dir",
                    ));
                }

                Ok(Self::Bench {
                    mode: args.mode,
                    deployment_target: args.deployment_target,
                    scenario: args.scenario,
                    storage_dir: args.storage_dir,
                    iterations: args.iterations,
                    concurrency: args.concurrency,
                    upload_max_in_flight_chunks: args.upload_max_in_flight_chunks,
                    chunk_size_bytes: args.chunk_size_bytes,
                    base_bytes: args.base_bytes,
                    mutated_bytes: args.mutated_bytes,
                    json: args.json,
                })
            }
            CliDefinitionCommand::Health(args) => Ok(Self::Health {
                server_url: args.server_url,
            }),
            CliDefinitionCommand::Completion(args) => Ok(Self::Completion {
                shell: args.shell,
                output: args.output,
            }),
            CliDefinitionCommand::Manpage(args) => Ok(Self::Manpage {
                output: args.output,
            }),
        }
    }
}

pub(crate) fn cli_definition_command() -> clap::Command {
    CliDefinition::command()
}

impl From<CliServerRole> for ServerRole {
    fn from(value: CliServerRole) -> Self {
        match value {
            CliServerRole::All => Self::All,
            CliServerRole::Api => Self::Api,
            CliServerRole::Transfer => Self::Transfer,
        }
    }
}

impl From<CliServerFrontend> for ServerFrontend {
    fn from(value: CliServerFrontend) -> Self {
        match value {
            CliServerFrontend::Xet => Self::Xet,
            CliServerFrontend::Lfs => Self::Lfs,
            CliServerFrontend::BazelHttp => Self::BazelHttp,
            CliServerFrontend::Oci => Self::Oci,
            CliServerFrontend::Hub => Self::Hub,
        }
    }
}

impl From<CliTokenScope> for TokenScope {
    fn from(value: CliTokenScope) -> Self {
        match value {
            CliTokenScope::Read => Self::Read,
            CliTokenScope::Write => Self::Write,
        }
    }
}

impl From<CliRepositoryProvider> for RepositoryProvider {
    fn from(value: CliRepositoryProvider) -> Self {
        match value {
            CliRepositoryProvider::GitHub => Self::GitHub,
            CliRepositoryProvider::Gitea => Self::Gitea,
            CliRepositoryProvider::GitLab => Self::GitLab,
            CliRepositoryProvider::Codeberg => Self::Codeberg,
            CliRepositoryProvider::Generic => Self::Generic,
        }
    }
}

impl From<CliObjectStorageAdapter> for ObjectStorageAdapter {
    fn from(value: CliObjectStorageAdapter) -> Self {
        match value {
            CliObjectStorageAdapter::Local => Self::Local,
            CliObjectStorageAdapter::S3 => Self::S3,
        }
    }
}

fn parse_positive_usize(value: &str) -> Result<NonZeroUsize, String> {
    let parsed = value
        .parse::<usize>()
        .map_err(|_error| "value must be a positive integer".to_owned())?;
    NonZeroUsize::new(parsed).ok_or_else(|| "value must be a positive integer".to_owned())
}

fn deduplicated_cli_frontends(
    frontends: impl IntoIterator<Item = ServerFrontend>,
) -> Vec<ServerFrontend> {
    let mut deduplicated = Vec::new();
    for frontend in frontends {
        if !deduplicated.contains(&frontend) {
            deduplicated.push(frontend);
        }
    }
    deduplicated
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use clap::error::ErrorKind;
    use shardline_protocol::{RepositoryProvider, TokenScope};
    use shardline_server::{
        DEFAULT_LOCAL_GC_RETENTION_SECONDS, DEFAULT_WEBHOOK_DELIVERY_RETENTION_SECONDS,
        DatabaseMigrationCommand, ObjectStorageAdapter, ServerFrontend, ServerRole,
    };

    use super::{BenchMode, CliCommand, CompletionShell, RedactedDbUrl};
    use crate::bench::{BenchDeploymentTarget, BenchScenario};

    #[test]
    fn parse_defaults_to_help() {
        let args = vec!["shardline".to_owned()];
        let parsed = CliCommand::parse(args);

        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert!(error.is_help());
        assert!(format!("{error}").contains("Usage: shardline"));
    }

    #[test]
    fn parse_help_aliases() {
        let long = vec!["shardline".to_owned(), "--help".to_owned()];
        let short = vec!["shardline".to_owned(), "-h".to_owned()];
        let command = vec!["shardline".to_owned(), "help".to_owned()];

        for args in [long, short, command] {
            let parsed = CliCommand::parse(args);
            assert!(parsed.is_err());
            let Err(error) = parsed else {
                return;
            };
            assert!(error.is_help());
            assert!(format!("{error}").contains("Usage: shardline"));
        }
    }

    #[test]
    fn help_text_is_generated_from_clap() {
        let help = CliCommand::help_text();

        assert!(help.contains("Usage: shardline"));
        assert!(help.contains("Examples:"));
        assert!(help.contains("gc schedule install"));
        assert!(help.contains("completion"));
        assert!(help.contains("manpage"));
        assert!(help.contains("db"));
        assert!(help.contains("gc"));
        assert!(help.contains("bench"));
        assert!(help.contains("providerless"));
    }

    #[test]
    fn nested_help_includes_examples_for_gc_schedule_install() {
        let args = vec![
            "shardline".to_owned(),
            "gc".to_owned(),
            "schedule".to_owned(),
            "install".to_owned(),
            "--help".to_owned(),
        ];
        let parsed = CliCommand::parse(args);

        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert!(error.is_help());
        assert!(format!("{error}").contains("Examples:"));
        assert!(
            error
                .to_string()
                .contains("--env-file /etc/shardline/shardline.env")
        );
    }

    #[test]
    fn parse_top_level_commands() {
        let providerless = vec![
            "shardline".to_owned(),
            "providerless".to_owned(),
            "setup".to_owned(),
        ];
        let serve = vec!["shardline".to_owned(), "serve".to_owned()];
        let bench = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--storage-dir".to_owned(),
            "/var/lib/shardline-bench".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(providerless),
            Ok(CliCommand::ProviderlessSetup)
        );
        assert_eq!(
            CliCommand::parse(serve),
            Ok(CliCommand::Serve {
                role: None,
                frontends: None,
            })
        );
        assert_eq!(
            CliCommand::parse(bench),
            Ok(CliCommand::Bench {
                mode: BenchMode::EndToEnd,
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                storage_dir: Some(PathBuf::from("/var/lib/shardline-bench")),
                iterations: 1,
                concurrency: 4,
                upload_max_in_flight_chunks: 64,
                chunk_size_bytes: 65_536,
                base_bytes: 1_048_576,
                mutated_bytes: 4_096,
                json: false,
            })
        );
    }

    #[test]
    fn parse_serve_with_role() {
        let args = vec![
            "shardline".to_owned(),
            "serve".to_owned(),
            "--role".to_owned(),
            "transfer".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Serve {
                role: Some(ServerRole::Transfer),
                frontends: None,
            })
        );
    }

    #[test]
    fn parse_serve_with_frontends() {
        let args = vec![
            "shardline".to_owned(),
            "serve".to_owned(),
            "--frontend".to_owned(),
            "xet,xet".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Serve {
                role: None,
                frontends: Some(vec![ServerFrontend::Xet]),
            })
        );
    }

    #[test]
    fn parse_serve_with_multiple_frontends() {
        let args = vec![
            "shardline".to_owned(),
            "serve".to_owned(),
            "--frontend".to_owned(),
            "lfs,bazel-http,oci".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Serve {
                role: None,
                frontends: Some(vec![
                    ServerFrontend::Lfs,
                    ServerFrontend::BazelHttp,
                    ServerFrontend::Oci,
                ]),
            })
        );
    }

    #[test]
    fn parse_fsck() {
        let args = vec![
            "shardline".to_owned(),
            "fsck".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Fsck {
                root: Some(PathBuf::from("/var/lib/shardline")),
            })
        );
    }

    #[test]
    fn parse_fsck_without_root_override() {
        let args = vec!["shardline".to_owned(), "fsck".to_owned()];

        assert_eq!(CliCommand::parse(args), Ok(CliCommand::Fsck { root: None }));
    }

    #[test]
    fn parse_index_rebuild() {
        let args = vec![
            "shardline".to_owned(),
            "index".to_owned(),
            "rebuild".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::IndexRebuild {
                root: Some(PathBuf::from("/var/lib/shardline")),
            })
        );
    }

    #[test]
    fn parse_repair_lifecycle() {
        let args = vec![
            "shardline".to_owned(),
            "repair".to_owned(),
            "lifecycle".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--webhook-retention-seconds".to_owned(),
            "3600".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::RepairLifecycle {
                root: Some(PathBuf::from("/var/lib/shardline")),
                webhook_retention_seconds: 3600,
            })
        );
    }

    #[test]
    fn parse_repair_orchestrator_with_defaults() {
        let args = vec!["shardline".to_owned(), "repair".to_owned()];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Repair {
                root: None,
                webhook_retention_seconds: DEFAULT_WEBHOOK_DELIVERY_RETENTION_SECONDS,
            })
        );
    }

    #[test]
    fn parse_repair_orchestrator_with_options() {
        let args = vec![
            "shardline".to_owned(),
            "repair".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--webhook-retention-seconds".to_owned(),
            "3600".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Repair {
                root: Some(PathBuf::from("/var/lib/shardline")),
                webhook_retention_seconds: 3600,
            })
        );
    }

    #[test]
    fn parse_gc() {
        let args = vec![
            "shardline".to_owned(),
            "gc".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--mark".to_owned(),
            "--sweep".to_owned(),
            "--retention-seconds".to_owned(),
            "600".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Gc {
                root: Some(PathBuf::from("/var/lib/shardline")),
                mark: true,
                sweep: true,
                retention_seconds: 600,
                retention_report: None,
                orphan_inventory: None,
            })
        );
    }

    #[test]
    fn parse_gc_schedule_install() {
        let args = vec![
            "shardline".to_owned(),
            "gc".to_owned(),
            "schedule".to_owned(),
            "install".to_owned(),
            "--output-dir".to_owned(),
            "/tmp/systemd".to_owned(),
            "--unit-prefix".to_owned(),
            "assets-gc".to_owned(),
            "--calendar".to_owned(),
            "hourly".to_owned(),
            "--retention-seconds".to_owned(),
            "600".to_owned(),
            "--binary-path".to_owned(),
            "/usr/bin/shardline".to_owned(),
            "--env-file".to_owned(),
            "/etc/shardline/env".to_owned(),
            "--working-directory".to_owned(),
            "/srv/assets".to_owned(),
            "--user".to_owned(),
            "svc".to_owned(),
            "--group".to_owned(),
            "svc".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::GcScheduleInstall {
                output_dir: PathBuf::from("/tmp/systemd"),
                unit_prefix: "assets-gc".to_owned(),
                calendar: "hourly".to_owned(),
                retention_seconds: 600,
                binary_path: PathBuf::from("/usr/bin/shardline"),
                env_file: PathBuf::from("/etc/shardline/env"),
                working_directory: PathBuf::from("/srv/assets"),
                user: "svc".to_owned(),
                group: "svc".to_owned(),
            })
        );
    }

    #[test]
    fn parse_gc_schedule_uninstall() {
        let args = vec![
            "shardline".to_owned(),
            "gc".to_owned(),
            "schedule".to_owned(),
            "uninstall".to_owned(),
            "--output-dir".to_owned(),
            "/tmp/systemd".to_owned(),
            "--unit-prefix".to_owned(),
            "assets-gc".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::GcScheduleUninstall {
                output_dir: PathBuf::from("/tmp/systemd"),
                unit_prefix: "assets-gc".to_owned(),
            })
        );
    }

    #[test]
    fn parse_backup_manifest() {
        let args = vec![
            "shardline".to_owned(),
            "backup".to_owned(),
            "manifest".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--output".to_owned(),
            "backup.json".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::BackupManifest {
                root: Some(PathBuf::from("/var/lib/shardline")),
                output: PathBuf::from("backup.json"),
            })
        );
    }

    #[test]
    fn parse_backup_manifest_requires_output() {
        let args = vec![
            "shardline".to_owned(),
            "backup".to_owned(),
            "manifest".to_owned(),
        ];

        let parsed = CliCommand::parse(args);
        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert_eq!(error.kind(), ErrorKind::MissingRequiredArgument);
        assert!(format!("{error}").contains("--output"));
    }

    #[test]
    fn parse_db_migrate_up() {
        let args = vec![
            "shardline".to_owned(),
            "db".to_owned(),
            "migrate".to_owned(),
            "up".to_owned(),
            "--database-url".to_owned(),
            "postgres://user:password@localhost:5432/shardline".to_owned(),
            "--steps".to_owned(),
            "2".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::DbMigrate {
                database_url: Some(RedactedDbUrl(
                    "postgres://user:password@localhost:5432/shardline".to_owned()
                )),
                command: DatabaseMigrationCommand::Up { steps: Some(2) },
            })
        );
    }

    #[test]
    fn cli_command_debug_redacts_database_url_credentials() {
        let parsed = CliCommand::parse(vec![
            "shardline".to_owned(),
            "db".to_owned(),
            "migrate".to_owned(),
            "up".to_owned(),
            "--database-url".to_owned(),
            "postgres://user:database-secret@localhost:5432/shardline".to_owned(),
        ]);
        assert!(parsed.is_ok());
        let Ok(parsed) = parsed else {
            return;
        };

        let rendered = format!("{parsed:?}");

        assert!(!rendered.contains("database-secret"));
        assert!(rendered.contains("***"));
    }

    #[test]
    fn parse_db_migrate_status() {
        let args = vec![
            "shardline".to_owned(),
            "db".to_owned(),
            "migrate".to_owned(),
            "status".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::DbMigrate {
                database_url: None,
                command: DatabaseMigrationCommand::Status,
            })
        );
    }

    #[test]
    fn parse_db_migrate_rejects_zero_steps() {
        let args = vec![
            "shardline".to_owned(),
            "db".to_owned(),
            "migrate".to_owned(),
            "down".to_owned(),
            "--steps".to_owned(),
            "0".to_owned(),
        ];

        let parsed = CliCommand::parse(args);
        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert_eq!(error.kind(), ErrorKind::ValueValidation);
        assert!(
            error
                .to_string()
                .contains("value must be a positive integer")
        );
    }

    #[test]
    fn parse_storage_migrate() {
        let args = vec![
            "shardline".to_owned(),
            "storage".to_owned(),
            "migrate".to_owned(),
            "--from".to_owned(),
            "local".to_owned(),
            "--from-root".to_owned(),
            "/srv/assets/.shardline/data".to_owned(),
            "--to".to_owned(),
            "s3".to_owned(),
            "--prefix".to_owned(),
            "xorbs/default/".to_owned(),
            "--dry-run".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::StorageMigrate {
                from: ObjectStorageAdapter::Local,
                from_root: Some(PathBuf::from("/srv/assets/.shardline/data")),
                to: ObjectStorageAdapter::S3,
                to_root: None,
                prefix: "xorbs/default/".to_owned(),
                dry_run: true,
            })
        );
    }

    #[test]
    fn parse_gc_with_export_paths() {
        let args = vec![
            "shardline".to_owned(),
            "gc".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--retention-report".to_owned(),
            "retention.json".to_owned(),
            "--orphan-inventory".to_owned(),
            "orphans.json".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Gc {
                root: Some(PathBuf::from("/var/lib/shardline")),
                mark: false,
                sweep: false,
                retention_seconds: DEFAULT_LOCAL_GC_RETENTION_SECONDS,
                retention_report: Some(PathBuf::from("retention.json")),
                orphan_inventory: Some(PathBuf::from("orphans.json")),
            })
        );
    }

    #[test]
    fn parse_hold_set() {
        let args = vec![
            "shardline".to_owned(),
            "hold".to_owned(),
            "set".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--object-key".to_owned(),
            format!("de/{}", "de".repeat(32)),
            "--reason".to_owned(),
            "provider deletion grace".to_owned(),
            "--ttl-seconds".to_owned(),
            "600".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::HoldSet {
                root: Some(PathBuf::from("/var/lib/shardline")),
                object_key: format!("de/{}", "de".repeat(32)),
                reason: "provider deletion grace".to_owned(),
                ttl_seconds: Some(600),
            })
        );
    }

    #[test]
    fn parse_hold_list() {
        let args = vec![
            "shardline".to_owned(),
            "hold".to_owned(),
            "list".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--active-only".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::HoldList {
                root: Some(PathBuf::from("/var/lib/shardline")),
                active_only: true,
            })
        );
    }

    #[test]
    fn parse_hold_release() {
        let args = vec![
            "shardline".to_owned(),
            "hold".to_owned(),
            "release".to_owned(),
            "--root".to_owned(),
            "/var/lib/shardline".to_owned(),
            "--object-key".to_owned(),
            format!("de/{}", "de".repeat(32)),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::HoldRelease {
                root: Some(PathBuf::from("/var/lib/shardline")),
                object_key: format!("de/{}", "de".repeat(32)),
            })
        );
    }

    #[test]
    fn parse_bench_with_explicit_options() {
        let args = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--storage-dir".to_owned(),
            "/var/lib/shardline-bench".to_owned(),
            "--iterations".to_owned(),
            "5".to_owned(),
            "--concurrency".to_owned(),
            "8".to_owned(),
            "--upload-max-in-flight-chunks".to_owned(),
            "32".to_owned(),
            "--chunk-size-bytes".to_owned(),
            "4096".to_owned(),
            "--base-bytes".to_owned(),
            "65536".to_owned(),
            "--mutated-bytes".to_owned(),
            "1024".to_owned(),
            "--json".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Bench {
                mode: BenchMode::EndToEnd,
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                storage_dir: Some(PathBuf::from("/var/lib/shardline-bench")),
                iterations: 5,
                concurrency: 8,
                upload_max_in_flight_chunks: 32,
                chunk_size_bytes: 4096,
                base_bytes: 65_536,
                mutated_bytes: 1024,
                json: true,
            })
        );
    }

    #[test]
    fn parse_bench_with_configured_deployment_target() {
        let args = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--storage-dir".to_owned(),
            "/var/lib/shardline-bench".to_owned(),
            "--deployment-target".to_owned(),
            "configured".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Bench {
                mode: BenchMode::EndToEnd,
                deployment_target: BenchDeploymentTarget::Configured,
                scenario: BenchScenario::Full,
                storage_dir: Some(PathBuf::from("/var/lib/shardline-bench")),
                iterations: 1,
                concurrency: 4,
                upload_max_in_flight_chunks: 64,
                chunk_size_bytes: 65_536,
                base_bytes: 1_048_576,
                mutated_bytes: 4_096,
                json: false,
            })
        );
    }

    #[test]
    fn parse_ingest_bench_without_storage_dir() {
        let args = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--mode".to_owned(),
            "ingest".to_owned(),
            "--iterations".to_owned(),
            "3".to_owned(),
            "--concurrency".to_owned(),
            "16".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Bench {
                mode: BenchMode::Ingest,
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                storage_dir: None,
                iterations: 3,
                concurrency: 16,
                upload_max_in_flight_chunks: 64,
                chunk_size_bytes: 65_536,
                base_bytes: 1_048_576,
                mutated_bytes: 4_096,
                json: false,
            })
        );
    }

    #[test]
    fn parse_bench_with_focused_scenario() {
        let args = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--storage-dir".to_owned(),
            "/var/lib/shardline-bench".to_owned(),
            "--scenario".to_owned(),
            "cross-repository-upload".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Bench {
                mode: BenchMode::EndToEnd,
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::CrossRepositoryUpload,
                storage_dir: Some(PathBuf::from("/var/lib/shardline-bench")),
                iterations: 1,
                concurrency: 4,
                upload_max_in_flight_chunks: 64,
                chunk_size_bytes: 65_536,
                base_bytes: 1_048_576,
                mutated_bytes: 4_096,
                json: false,
            })
        );
    }

    #[test]
    fn parse_bench_with_cached_reconstruction_scenario() {
        let args = vec![
            "shardline".to_owned(),
            "bench".to_owned(),
            "--storage-dir".to_owned(),
            "/var/lib/shardline-bench".to_owned(),
            "--scenario".to_owned(),
            "cached-latest-reconstruction".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Bench {
                mode: BenchMode::EndToEnd,
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::CachedLatestReconstruction,
                storage_dir: Some(PathBuf::from("/var/lib/shardline-bench")),
                iterations: 1,
                concurrency: 4,
                upload_max_in_flight_chunks: 64,
                chunk_size_bytes: 65_536,
                base_bytes: 1_048_576,
                mutated_bytes: 4_096,
                json: false,
            })
        );
    }

    #[test]
    fn parse_bench_requires_storage_dir_for_e2e_mode() {
        let args = vec!["shardline".to_owned(), "bench".to_owned()];
        let parsed = CliCommand::parse(args);

        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert_eq!(error.kind(), ErrorKind::MissingRequiredArgument);
        assert!(format!("{error}").contains("--storage-dir"));
    }

    #[test]
    fn parse_health() {
        let args = vec![
            "shardline".to_owned(),
            "health".to_owned(),
            "--server".to_owned(),
            "http://127.0.0.1:8080".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Health {
                server_url: "http://127.0.0.1:8080".to_owned()
            })
        );
    }

    #[test]
    fn parse_completion() {
        let args = vec![
            "shardline".to_owned(),
            "completion".to_owned(),
            "bash".to_owned(),
            "--output".to_owned(),
            "./shardline.bash".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Completion {
                shell: CompletionShell::Bash,
                output: Some(PathBuf::from("./shardline.bash")),
            })
        );
    }

    #[test]
    fn parse_manpage() {
        let args = vec![
            "shardline".to_owned(),
            "manpage".to_owned(),
            "--output".to_owned(),
            "./shardline.1".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::Manpage {
                output: Some(PathBuf::from("./shardline.1")),
            })
        );
    }

    #[test]
    fn parse_config_check() {
        let args = vec![
            "shardline".to_owned(),
            "config".to_owned(),
            "check".to_owned(),
        ];

        assert_eq!(CliCommand::parse(args), Ok(CliCommand::ConfigCheck));
    }

    #[test]
    fn parse_admin_token() {
        let args = vec![
            "shardline".to_owned(),
            "admin".to_owned(),
            "token".to_owned(),
            "--issuer".to_owned(),
            "local".to_owned(),
            "--subject".to_owned(),
            "operator-1".to_owned(),
            "--scope".to_owned(),
            "write".to_owned(),
            "--provider".to_owned(),
            "github".to_owned(),
            "--owner".to_owned(),
            "team".to_owned(),
            "--repo".to_owned(),
            "assets".to_owned(),
            "--revision".to_owned(),
            "main".to_owned(),
            "--key-file".to_owned(),
            "/tmp/shardline.key".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::AdminToken {
                issuer: "local".to_owned(),
                subject: "operator-1".to_owned(),
                scope: TokenScope::Write,
                provider: RepositoryProvider::GitHub,
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: Some("main".to_owned()),
                ttl_seconds: 3600,
                key_file: Some(PathBuf::from("/tmp/shardline.key")),
                key_env: None,
            })
        );
    }

    #[test]
    fn parse_admin_token_with_key_env() {
        let args = vec![
            "shardline".to_owned(),
            "admin".to_owned(),
            "token".to_owned(),
            "--issuer".to_owned(),
            "local".to_owned(),
            "--subject".to_owned(),
            "operator-1".to_owned(),
            "--scope".to_owned(),
            "write".to_owned(),
            "--provider".to_owned(),
            "github".to_owned(),
            "--owner".to_owned(),
            "team".to_owned(),
            "--repo".to_owned(),
            "assets".to_owned(),
            "--key-env".to_owned(),
            "SHARDLINE_TOKEN_SIGNING_KEY".to_owned(),
        ];

        assert_eq!(
            CliCommand::parse(args),
            Ok(CliCommand::AdminToken {
                issuer: "local".to_owned(),
                subject: "operator-1".to_owned(),
                scope: TokenScope::Write,
                provider: RepositoryProvider::GitHub,
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: None,
                ttl_seconds: 3600,
                key_file: None,
                key_env: Some("SHARDLINE_TOKEN_SIGNING_KEY".to_owned()),
            })
        );
    }

    #[test]
    fn parse_rejects_unknown_command() {
        let args = vec!["shardline".to_owned(), "unknown".to_owned()];
        let parsed = CliCommand::parse(args);

        assert!(parsed.is_err());
        let Err(error) = parsed else {
            return;
        };
        assert_eq!(error.kind(), ErrorKind::InvalidSubcommand);
        assert!(format!("{error}").contains("unknown"));
    }

    #[test]
    fn parse_rejects_incomplete_nested_commands() {
        let config = vec!["shardline".to_owned(), "config".to_owned()];
        let admin = vec!["shardline".to_owned(), "admin".to_owned()];
        let providerless = vec!["shardline".to_owned(), "providerless".to_owned()];

        for args in [config, admin, providerless] {
            let parsed = CliCommand::parse(args);
            assert!(parsed.is_err());
            let Err(error) = parsed else {
                return;
            };
            assert_eq!(
                error.kind(),
                ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
            );
        }
    }
}