revault_cli 0.0.3

CLI for reVault encrypted lockboxes, store files, variables and forms with integration to your platform key storage
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
use clap::{Arg, ArgAction, Command};
use clap_complete::engine::ArgValueCompleter;

use super::completion;

const ABOUT: &str =
    "Create encrypted file archives, store secrets safely, and grant access with public keys.";
const VERBOSE_HELP_TEMPLATE: &str = "\
{about-with-newline}
{before-help}
{usage-heading} {usage}

{all-args}{after-help}\
";

pub(crate) fn command(verbose: bool) -> Command {
    let command = Command::new("lockbox")
        .about(ABOUT)
        .disable_version_flag(true)
        .disable_help_subcommand(true)
        .arg_required_else_help(true)
        .subcommand_required(true)
        .subcommand_help_heading("Available commands")
        .after_help("Run \"lockbox <command> --help\" for more information about a command.")
        .next_help_heading("Global options")
        .arg(
            Arg::new("verbose")
                .long("verbose")
                .global(true)
                .action(ArgAction::SetTrue)
                .help("Show detailed command forms and advanced options."),
        )
        .arg(
            Arg::new("key")
                .long("key")
                .global(true)
                .value_name("RAW_CONTENT_KEY")
                .hide(!verbose)
                .help("Developer override: open with a raw content key supplied out of band."),
        )
        .subcommands([
            archive_command("create", "Create a new encrypted lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault init\n  lockbox create secrets.lbox\n  lockbox create --password secrets.lbox\n  lockbox create --for alice secrets.lbox",
                    "Context:\n  Use create when starting a new encrypted archive. By default it creates a lockbox for the vault's default profile. Use --password when you need a password-protected lockbox.",
                ))
                .arg(
                    Arg::new("password")
                        .long("password")
                        .conflicts_with("for")
                        .action(ArgAction::SetTrue)
                        .help("Create a password-protected lockbox."),
                )
                .arg(
                    Arg::new("for")
                        .long("for")
                        .conflicts_with("password")
                        .value_name("PROFILE_OR_CONTACT")
                        .help("Create the lockbox for one of your profiles or a saved contact.")
                        .add(ArgValueCompleter::new(completion::named_candidates)),
                )
                .arg(required("lockbox", "Lockbox path.")),
            archive_command("open", "Open the lockbox for later commands.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox open secrets.lbox\n  lockbox open --duration 30m secrets.lbox\n  LOCKBOX_PASSWORD=secret lockbox open secrets.lbox\n  printf '%s\\n' \"$LOCKBOX_PASSWORD\" | lockbox open --password-stdin secrets.lbox",
                    "Context:\n  Opens the lockbox for later commands. Close the lockbox when you have finished working with it. On supported platforms, the Lockbox Session Agent will automatically close the lockbox after 30 minutes.",
                ))
                .arg(
                    Arg::new("duration")
                        .short('d')
                        .long("duration")
                        .value_name("DURATION")
                        .help("Keep the lockbox open for this session duration, such as 30s, 30m, 2h, or 1d."),
                )
                .arg(
                    Arg::new("password-env")
                        .long("password-env")
                        .value_name("NAME")
                        .conflicts_with_all(["password-file", "password-stdin"])
                        .help("Read the lockbox password from this variable."),
                )
                .arg(
                    Arg::new("password-file")
                        .long("password-file")
                        .value_name("FILE")
                        .conflicts_with_all(["password-env", "password-stdin"])
                        .help("Read the lockbox password from a file."),
                )
                .arg(
                    Arg::new("password-stdin")
                        .long("password-stdin")
                        .action(ArgAction::SetTrue)
                        .conflicts_with_all(["password-env", "password-file"])
                        .help("Read the lockbox password from stdin."),
                )
                .arg(optional("lockbox", "Lockbox path. Defaults to the session default lockbox.")),
            archive_command("close", "Close the lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox close secrets.lbox\n  lockbox close",
                    "Context:\n  Closes the given lockbox or the session default lockbox if no argument is given. On supported platforms the Lockbox Session Agent will automatically close the lockbox after 30 minutes.",
                ))
                .arg(optional("lockbox", "Lockbox path. Defaults to the session default lockbox.")),
            archive_command("recover", "Recover readable entries from a damaged lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox recover damaged.lbox\n  lockbox recover damaged.lbox --output recovered.lbox\n  lockbox recover --dry-run --format table damaged.lbox",
                    "Context:\n  Recover scans a damaged lockbox and writes a new lockbox containing readable entries. By default the recovered file is written next to the original as <name>.recovered.lbox. Use --dry-run first when you want to inspect what can be recovered without writing an output file.",
                ))
                .arg(optional(
                    "lockbox",
                    "Damaged lockbox path. Defaults to the session default lockbox.",
                ))
                .arg(
                    Arg::new("output")
                        .long("output")
                        .short('o')
                        .value_name("RECOVERED_LOCKBOX")
                        .help("Write recovered entries to this new lockbox."),
                )
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Replace the recovered lockbox output file if it already exists."),
                )
                .arg(
                    Arg::new("dry-run")
                        .long("dry-run")
                        .action(ArgAction::SetTrue)
                        .conflicts_with_all(["output", "overwrite"])
                        .help("Print a recovery report without writing a recovered lockbox."),
                )
                .arg(output_format_arg()),
            file_command("add", "Add a file or directory to a lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox add ./notes.txt\n  lockbox add secrets.lbox ./notes.txt\n  lockbox add --recursive ./project /project\n  lockbox add -r secrets.lbox ./large-dir /archive",
                    "Context:\n  Add imports a host file into an open lockbox. With a session default lockbox, omit the lockbox path and pass the source first. Pass --recursive when the source is a directory. If no destination path is supplied, files keep their filename at the lockbox root and recursive directory imports go under the root. Use --jobs in verbose mode to tune large imports.",
                ))
                .arg(
                    Arg::new("recursive")
                        .short('r')
                        .long("recursive")
                        .action(ArgAction::SetTrue)
                        .help("Recursively import a directory source."),
                )
                .arg(
                    Arg::new("jobs")
                        .long("jobs")
                        .value_name("auto|1|N")
                        .hide(!verbose)
                        .help("Set import worker count."),
                )
                .arg(required(
                    "lockbox-or-source",
                    "Lockbox path, or source file/directory when a session default lockbox is set.",
                ))
                .arg(optional(
                    "source-or-lockbox-path",
                    "Source file/directory, or destination path when a session default lockbox is set.",
                ))
                .arg(optional(
                    "lockbox-path",
                    "Destination path inside the lockbox. Defaults to root.",
                )),
            file_command("extract", "Extract files from a lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox extract secrets.lbox /notes.txt ./notes.txt\n  lockbox extract --to ./restore secrets.lbox\n  lockbox extract --to ./restore --overwrite secrets.lbox",
                    "Context:\n  Extract copies encrypted content back to the host filesystem. Use the single-file form for one stored path, or --to when restoring the whole lockbox into a directory.",
                ))
                .arg(
                    Arg::new("to")
                        .long("to")
                        .value_name("DESTINATION")
                        .help("Extract the full lockbox to a directory."),
                )
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Overwrite existing files."),
                )
                .arg(
                    Arg::new("restore-symlinks")
                        .long("restore-symlinks")
                        .action(ArgAction::SetTrue)
                        .help("Restore symlinks when extracting a directory."),
                )
                .arg(
                    Arg::new("restore-permissions")
                        .long("restore-permissions")
                        .action(ArgAction::SetTrue)
                        .help("Restore file permissions when extracting a directory."),
                )
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH DESTINATION | PATH DESTINATION")
                        .num_args(0..=3)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass path and destination. Otherwise pass lockbox, path, and destination.")
                        .add(ArgValueCompleter::new(completion::archive_value_candidates)),
                ),
            file_command("cat", "Write a stored file to stdout.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox cat secrets.lbox /notes.txt\n  lockbox cat secrets.lbox /notes.txt > notes.txt",
                    "Context:\n  Cat streams one stored file to stdout. Use it for inspection, piping, or shell redirection when you do not want reVault to create a host file directly.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the stored path.")
                        .add(ArgValueCompleter::new(completion::archive_value_candidates)),
                ),
            file_command("list", "List stored entries.")
                .visible_alias("ls")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox list secrets.lbox\n  lockbox list secrets.lbox /project\n  lockbox list secrets.lbox '/project/**/*.txt'\n  lockbox list --recursive --format json secrets.lbox",
                    "Context:\n  List shows files and inferred directories stored in a lockbox. The default view mirrors a normal directory listing; pass a glob pattern to match stored paths, or use --recursive when scripts or audits need full stored paths.",
                ))
                .arg(output_format_arg())
                .arg(
                    Arg::new("recursive")
                        .short('R')
                        .long("recursive")
                        .action(ArgAction::SetTrue)
                        .help("List entries below child directories."),
                )
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(0..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the optional stored path or glob.")
                        .add(ArgValueCompleter::new(completion::archive_value_candidates)),
                ),
            file_command("rm", "Remove a stored entry.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox rm secrets.lbox /notes.txt\n  lockbox rm --force secrets.lbox /old.txt",
                    "Context:\n  Remove deletes a stored file or directory entry from the lockbox and commits that change. Without --force, reVault asks for confirmation before changing the archive.",
                ))
                .arg(
                    Arg::new("force")
                        .long("force")
                        .action(ArgAction::SetTrue)
                        .help("Remove without an interactive confirmation."),
                )
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the stored path.")
                        .add(ArgValueCompleter::new(completion::archive_value_candidates)),
                ),
            file_command("rename", "Rename a stored entry.")
                .visible_alias("mv")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox rename secrets.lbox /draft.txt /final.txt\n  lockbox mv secrets.lbox /old-dir /archive/old-dir",
                    "Context:\n  Rename changes the path stored inside the lockbox. It does not touch host filesystem paths; both arguments are lockbox paths.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX FROM TO | FROM TO")
                        .num_args(2..=3)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the stored source and destination paths.")
                        .add(ArgValueCompleter::new(completion::archive_value_candidates)),
                ),
            variables_command(verbose),
            form_command(verbose),
            session_command(verbose),
            completion_command(),
            migration_command(verbose),
            access_command(verbose),
            archive_command("doctor", "Show vault, agent, or lockbox diagnostics.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox doctor\n  lockbox doctor secrets.lbox",
                    "Context:\n  With no lockbox path, doctor reports local configuration and runtime state, including vault path, auto-open support, and whether the session agent is reachable. With a lockbox path, doctor inspects public lockbox metadata without opening and adds deeper checks when the lockbox is already open.",
                ))
                .arg(optional(
                    "lockbox",
                    "Lockbox path to inspect without prompting.",
                )),
            vault_command(verbose),
            developer_command("visualize", "Print internal lockbox structure.")
                .visible_alias("visualise")
                .arg(optional("lockbox", "Lockbox path. Defaults to the session default lockbox.")),
            developer_command("keygen", "Generate raw keypair files.")
                .arg(required("private-key", "Private key output path."))
                .arg(required("public-key", "Public key output path.")),
            developer_command("open-key", "Open a lockbox using a vault private key.")
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX VAULT_KEY | VAULT_KEY")
                        .num_args(0..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the optional vault private key name."),
                ),
        ]);
    if verbose {
        apply_verbose_help_template(command)
    } else {
        command
    }
}

pub(crate) fn usage(verbose: bool) {
    eprintln!(
        "{ABOUT}

Usage: lockbox <command> [arguments]

Global options:
    --verbose        Show detailed command forms and advanced options.
-h, --help           Print this usage information.

Available commands:

Archives
  create          Create a new encrypted lockbox.
  open            Open a lockbox for later commands.
  close           Close the lockbox.
  recover         Recover readable entries from a damaged lockbox.

Files
  add             Add a file or directory to a lockbox.
  extract         Extract files from a lockbox.
  cat             Write a stored file to stdout.
  list            List stored entries.
  rm              Remove a stored entry.
  rename          Rename a stored entry.

Data
  variable        Store, retrieve, list, export, or remove variable values.
  form            Manage typed multi-field form records.

Session
  session         Manage the default lockbox and open lockbox sessions.

Completion
  completion      Generate or install dynamic shell completion.

Sharing
  access          Grant or revoke who can open a lockbox.

Diagnostics
  doctor          Show vault, agent, or lockbox diagnostics.

Vault
  vault           Manage profiles, contacts, and reusable forms."
    );

    if verbose {
        eprintln!(
            "
Advanced global options:
    --key <raw-content-key>    Developer override: open with a raw content key supplied out of band.

Advanced command options:
  lockbox add --jobs auto|1|N <lockbox> <source> <lockbox-path>

Developer and compatibility commands:
  keygen          Generate raw keypair files.
  open-key        Open a lockbox using a vault private key.
  visualize       Print internal lockbox structure.

Migration commands:
  migrate         Migrate vaults and archives between native format versions.

Process variables:
  LOCKBOX_KEY=<raw-content-key> lockbox <command> ...
    LOCKBOX_PASSWORD=<password> lockbox open <lockbox>
  LOCKBOX_OPEN_DURATION=30m lockbox open <lockbox>
  LOCKBOX_VAULT_PASSWORD=<password> lockbox vault <command>
  LOCKBOX_PLATFORM_SECRET_STORE=auto|disabled lockbox vault <command>
  LOCKBOX_SESSION_AGENT_DIR=<dir> lockbox <command> ...
  LOCKBOX_VAULT_DIR=<dir> lockbox <command> ...

Raw content keys are for developer recovery and local testing. reVault does not
print or export them; normal commands should open through the vault session."
        );
    }

    eprintln!(
        "
Run \"lockbox <command> --help\" for more information about a command."
    );
}

fn archive_command(name: &'static str, about: &'static str) -> Command {
    base_command(name, about)
}

fn file_command(name: &'static str, about: &'static str) -> Command {
    base_command(name, about)
}

fn sharing_command(name: &'static str, about: &'static str) -> Command {
    base_command(name, about)
}

fn developer_command(name: &'static str, about: &'static str) -> Command {
    base_command(name, about).hide(true)
}

fn base_command(name: &'static str, about: &'static str) -> Command {
    Command::new(name)
        .about(about)
        .disable_help_subcommand(true)
}

fn variables_command(verbose: bool) -> Command {
    base_command(
        "variable",
        "Store, retrieve, list, export, or remove variable values.",
    )
    .visible_aliases(["var", "variables"])
    .after_help(verbose_help(
        verbose,
        "Examples:\n  lockbox variable set secrets.lbox APP_MODE production\n  lockbox variable set secrets.lbox APP_MODE=production\n  lockbox variable get secrets.lbox APP_MODE\n  lockbox variable export secrets.lbox",
        "Context:\n  Variables let you store name/value pairs securely in your lockbox. For secrets, such as an API key, set the variable using the --secret flag to ensure an additional level of security is applied to those values.",
    ))
    .subcommand_required(true)
    .arg_required_else_help(true)
    .subcommand(
        Command::new("set")
            .about("Store a variable value.")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  lockbox variable set secrets.lbox APP_MODE production\n  lockbox variable set secrets.lbox APP_MODE=production\n  lockbox variable set --secret secrets.lbox API_TOKEN --interactive\n  printf '%s' \"$TOKEN\" | lockbox variable set --secret --stdin secrets.lbox API_TOKEN",
                "Context:\n  Variables set writes one named value into a lockbox. Use --secret for values that should not be exported in bulk, such as tokens and passwords. Choose one value source: argument, prompt, stdin, file, or process environment. Secret values cannot use --value; use --stdin, --file, --interactive, or --from-env.",
            ))
            .arg(
                Arg::new("secret")
                    .short('s')
                    .long("secret")
                    .action(ArgAction::SetTrue)
                    .help("Store the value as secret."),
            )
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX NAME[=VALUE] [VALUE] | NAME[=VALUE] [VALUE]")
                    .num_args(1..=3)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass name and optional value. Otherwise pass lockbox, name, and optional value."),
            )
            .arg(
                Arg::new("interactive")
                    .short('i')
                    .long("interactive")
                    .action(ArgAction::SetTrue)
                    .help("Prompt for the value."),
            )
            .arg(
                Arg::new("stdin")
                    .short('t')
                    .long("stdin")
                    .action(ArgAction::SetTrue)
                    .help("Read the value from stdin."),
            )
            .arg(
                Arg::new("value")
                    .short('v')
                    .long("value")
                    .value_name("VALUE")
                    .help("Read a normal value from this argument; not accepted with --secret."),
            )
            .arg(
                Arg::new("file")
                    .short('f')
                    .long("file")
                    .value_name("FILE")
                    .help("Read the value from a file."),
            )
            .arg(
                Arg::new("from-env")
                    .short('e')
                    .long("from-env")
                    .value_name("NAME")
                    .help("Read the value from a process variable."),
            ),
    )
    .subcommand(
        Command::new("get")
            .about("Print one stored variable value by name.")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  lockbox variable get secrets.lbox APP_MODE\n  lockbox variable get --secret secrets.lbox API_TOKEN\n  lockbox variable get --secret --output api-token.txt secrets.lbox API_TOKEN",
                "Context:\n  Variables get reads one named value from a lockbox. Secret values require --secret so accidental terminal output is an explicit user choice. Use --output when the exact bytes should go to a file.",
            ))
            .arg(
                Arg::new("secret")
                    .short('s')
                    .long("secret")
                    .action(ArgAction::SetTrue)
                    .help("Print a secret value."),
            )
            .arg(
                Arg::new("output")
                    .long("output")
                    .value_name("FILE")
                    .help("Write the exact value bytes to a file instead of stdout."),
            )
            .arg(
                Arg::new("overwrite")
                    .long("overwrite")
                    .requires("output")
                    .action(ArgAction::SetTrue)
                    .help("Replace the output file if it already exists."),
            )
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX NAME | NAME")
                    .num_args(1..=2)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass only the variable name."),
            ),
    )
    .subcommand(
        Command::new("list")
            .about("List variable values.")
            .visible_alias("ls")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  lockbox variable list secrets.lbox\n  lockbox variable list secrets.lbox /production\n  lockbox variable list secrets.lbox '**/API_KEY'\n  lockbox variable list --format json secrets.lbox",
                "Context:\n  Variables list shows value names and whether each value is normal or secret. It does not print stored values. Pass a path such as /production to list that group, or a glob such as **/API_KEY to match names across groups.",
            ))
            .arg(output_format_arg())
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX PATTERN | PATTERN")
                    .num_args(0..=2)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass only the optional pattern."),
            ),
    )
    .subcommand(
        Command::new("export")
            .about("Print all non-secret variable values in an importable format.")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  eval \"$(lockbox variable export secrets.lbox)\"\n  lockbox variable export secrets.lbox /production\n  lockbox variable export secrets.lbox '**/API_KEY'\n  lockbox variable export --format posix secrets.lbox > variables.sh\n  lockbox variable export --format powershell secrets.lbox | Invoke-Expression\n\nFormats:\n  posix       NAME='value' lines for sh, bash, and zsh. Default.\n  powershell  $env:NAME = 'value' lines for PowerShell.\n  cmd         set \"NAME=value\" lines for cmd.exe.\n  json        One JSON object per line with name and value fields.\n\n`variable export` writes to stdout. Use shell redirection to write it to a file.",
                "Context:\n  Variables export is intended for shell startup, CI setup, or scripting. It only includes non-secret values; use explicit `variable get --secret` for secret values so they are never exported in bulk by accident. The optional filter follows the same path or glob pattern rules as variable list. Grouped names are flattened with underscores for shell-safe output.",
            ))
            .arg(
                Arg::new("format")
                    .long("format")
                    .value_name("posix|powershell|cmd|json")
                    .default_value("posix")
                    .help("Output format."),
            )
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX PATTERN | PATTERN")
                    .num_args(0..=2)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass only the optional pattern."),
            ),
    )
    .subcommand(
        Command::new("move")
            .visible_alias("mv")
            .about("Move matching variables into another path.")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  lockbox variable move secrets.lbox '/*' /dev\n  lockbox variable mv secrets.lbox '/production/*' /archive",
                "Context:\n  Move treats the destination as a variable group. Every match keeps its path relative to the non-glob source prefix. Existing destination variables are never overwritten. Quote glob patterns so the shell does not expand them.",
            ))
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX SOURCE DESTINATION | SOURCE DESTINATION")
                    .num_args(2..=3)
                    .required(true)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass only source and destination."),
            ),
    )
    .subcommand(
        Command::new("remove")
            .about("Remove a variable value.")
            .after_help(verbose_help(
                verbose,
                "Examples:\n  lockbox variable remove secrets.lbox APP_MODE\n  lockbox variable remove secrets.lbox API_TOKEN",
                "Context:\n  Variables remove deletes one named value from a lockbox. It affects only the lockbox record, not the current process environment.",
            ))
            .arg(
                Arg::new("args")
                    .value_name("LOCKBOX NAME | NAME")
                    .num_args(1..=2)
                    .action(ArgAction::Append)
                    .help("With a session default lockbox, pass only the variable name."),
            ),
    )
}

fn form_command(verbose: bool) -> Command {
    base_command("form", "Manage typed multi-field form records.")
        .after_help(verbose_help(
            verbose,
            "Examples:\n  lockbox vault form define login --field username:text --field password:secret\n  lockbox form use login secrets.lbox\n  lockbox form add secrets.lbox /work/github --type login --name GitHub --set username=bsutton\n  lockbox form show secrets.lbox /work/github",
            "Context:\n  Forms store structured records inside a lockbox. Reusable definitions normally live in the vault and can be copied into a lockbox with form use. Definitions remain embedded in each lockbox so published lockboxes are self-describing.",
        ))
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(
            Command::new("define")
                .about("Create or revise a form definition.")
                .override_usage(
                    "lockbox form define <lockbox> [alias] --field <NAME[:KIND[:required[:LABEL]]]>...\n\nExample:\n  lockbox form define secrets.lbox login --field username:text --field password:secret",
                )
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form define secrets.lbox login --field username:text --field password:secret\n  lockbox form define secrets.lbox --name Login --description \"Website sign-in\" --field username:text:required:User --field password:secret:required:Password\n  lockbox form define secrets.lbox login --name Login --description \"Website sign-in\" --field username:text:required:User --field password:secret:required:Password\n\nField form:\n  NAME[:KIND[:required[:LABEL]]]\n\nKinds:\n  text, secret, password, url, email, date, month, notes, number\n\nFormats:\n  date uses YYYY-MM-DD; month uses YYYY-MM",
                    "Context:\n  Define creates or revises a form definition. The alias is optional; when omitted, --name is required and an alias slug is derived from the display name. If the alias already resolves to exactly one definition, define appends a new revision. If an imported published lockbox has conflicting aliases, pass --definition-id to revise the intended definition explicitly.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX ALIAS | ALIAS")
                        .num_args(0..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the optional form alias."),
                )
                .arg(
                    Arg::new("name")
                        .long("name")
                        .value_name("DISPLAY_NAME")
                        .help("Human display name for this form definition."),
                )
                .arg(
                    Arg::new("description")
                        .long("description")
                        .value_name("TEXT")
                        .help("Human description for this form definition."),
                )
                .arg(
                    Arg::new("definition-id")
                        .long("definition-id")
                        .alias("type-id")
                        .value_name("DEFINITION_ID")
                        .help("Revise or create this stable form definition id."),
                )
                .arg(
                    Arg::new("field")
                        .long("field")
                        .value_name("NAME[:KIND[:required[:LABEL]]]")
                        .action(ArgAction::Append)
                        .required(true)
                        .help("Add one field to the definition."),
                ),
        )
        .subcommand(
            Command::new("definitions")
                .about("List form definitions.")
                .arg(output_format_arg())
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX")
                        .num_args(0..=1)
                        .action(ArgAction::Append)
                        .help("Lockbox path. Defaults to the session default lockbox."),
                ),
        )
        .subcommand(
            Command::new("use")
                .about("Copy a vault form definition into a lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form use login secrets.lbox\n  lockbox form use login",
                    "Context:\n  Use copies a reusable definition from the vault into the lockbox. With a session default lockbox, the lockbox path can be omitted.",
                ))
                .arg(required("form", "Vault form alias or definition id."))
                .arg(optional("lockbox", "Lockbox path. Defaults to the session default lockbox.")),
        )
        .subcommand(
            Command::new("capture")
                .about("Copy a lockbox form definition into the vault.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form capture secrets.lbox login\n  lockbox form capture secrets.lbox login published-login\n  lockbox form capture login",
                    "Context:\n  Capture stores a lockbox definition in the vault so it can be reused. Pass a new form name when the vault already uses the same alias for a different definition.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX FORM NEW_NAME | FORM NEW_NAME")
                        .num_args(1..=3)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass form name and optional new name."),
                ),
        )
        .subcommand(
            Command::new("add")
                .about("Add a form record.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form add secrets.lbox /work/github --type login --name GitHub\n  lockbox form add secrets.lbox /work/github --type login --set username=bsutton --set site=https://github.com\n  lockbox form add secrets.lbox /work/github --type login --interactive",
                    "Context:\n  Add creates one form record in the lockbox. Use --set for non-secret values known up front. Use --interactive to prompt for remaining fields, including secret fields without echoing them.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the form record path."),
                )
                .arg(
                    Arg::new("type")
                        .long("type")
                        .value_name("ALIAS_OR_DEFINITION_ID")
                        .required(true)
                        .help("Form definition alias or stable definition id."),
                )
                .arg(
                    Arg::new("name")
                        .long("name")
                        .value_name("RECORD_NAME")
                        .help("Display name for this record. Defaults to the last path component."),
                )
                .arg(
                    Arg::new("set")
                        .long("set")
                        .value_name("FIELD=VALUE")
                        .action(ArgAction::Append)
                        .help("Set one non-secret field while adding the form record."),
                )
                .arg(
                    Arg::new("interactive")
                        .long("interactive")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("Prompt for fields that were not supplied with --set."),
                ),
        )
        .subcommand(
            Command::new("edit")
                .about("Edit a form record.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form edit secrets.lbox /work/github --set username=bsutton\n  lockbox form edit secrets.lbox /work/github --interactive",
                    "Context:\n  Edit updates an existing form record. Use --interactive after a form definition revision to fill fields that exist in the latest definition but are missing from the stored record.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the form record path."),
                )
                .arg(
                    Arg::new("set")
                        .long("set")
                        .value_name("FIELD=VALUE")
                        .action(ArgAction::Append)
                        .help("Set one non-secret field while editing the form record."),
                )
                .arg(
                    Arg::new("interactive")
                        .long("interactive")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("Prompt for fields missing from the current record."),
                ),
        )
        .subcommand(
            Command::new("set")
                .about("Set one form field value.")
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH FIELD VALUE | PATH FIELD VALUE")
                        .num_args(2..=4)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass form record path, field id, and optional value."),
                )
                .arg(
                    Arg::new("secret")
                        .long("secret")
                        .action(ArgAction::SetTrue)
                        .help("Set a secret field value."),
                )
                .arg(
                    Arg::new("explicit-value")
                        .long("value")
                        .short('v')
                        .value_name("VALUE")
                        .conflicts_with_all(["stdin", "file", "from-env", "interactive"])
                        .help("Set a literal non-secret field value."),
                )
                .arg(
                    Arg::new("stdin")
                        .long("stdin")
                        .short('t')
                        .action(ArgAction::SetTrue)
                        .conflicts_with_all(["explicit-value", "file", "from-env", "interactive"])
                        .help("Read the field value from stdin."),
                )
                .arg(
                    Arg::new("file")
                        .long("file")
                        .short('f')
                        .value_name("FILE")
                        .conflicts_with_all(["explicit-value", "stdin", "from-env", "interactive"])
                        .help("Read the field value from a file."),
                )
                .arg(
                    Arg::new("from-env")
                        .long("from-env")
                        .short('e')
                        .value_name("NAME")
                        .conflicts_with_all(["explicit-value", "stdin", "file", "interactive"])
                        .help("Read the field value from an variable."),
                )
                .arg(
                    Arg::new("interactive")
                        .long("interactive")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .conflicts_with_all(["explicit-value", "stdin", "file", "from-env"])
                        .help("Prompt for the field value."),
                ),
        )
        .subcommand(
            Command::new("get")
                .about("Print one form field value.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form get secrets.lbox /work/github username\n  lockbox form get --secret secrets.lbox /work/github password\n  lockbox form get --secret --output password.txt secrets.lbox /work/github password",
                    "Context:\n  Form get reads one field from a form record. Secret fields require --secret so accidental terminal output is an explicit user choice. Use --output when the exact bytes should go to a file.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH FIELD | PATH FIELD")
                        .num_args(2..=3)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the form record path and field id."),
                )
                .arg(
                    Arg::new("secret")
                        .long("secret")
                        .action(ArgAction::SetTrue)
                        .help("Print a secret field value."),
                )
                .arg(
                    Arg::new("output")
                        .long("output")
                        .value_name("FILE")
                        .help("Write the field value to this file."),
                )
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .requires("output")
                        .action(ArgAction::SetTrue)
                        .help("Replace the output file if it already exists."),
                ),
        )
        .subcommand(
            Command::new("show")
                .about("Show one form record.")
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the form record path."),
                ),
        )
        .subcommand(
            Command::new("list")
                .about("List form records.")
                .arg(output_format_arg())
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATTERN | PATTERN")
                        .num_args(0..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the optional pattern."),
                ),
        )
        .subcommand(
            Command::new("move")
                .visible_alias("mv")
                .about("Move matching form records into another path.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox form move secrets.lbox '/work/*' /archive\n  lockbox form mv secrets.lbox '/dev/*' /production",
                    "Context:\n  Move treats the destination as a form-record directory. Every match keeps its path relative to the non-glob source prefix. Existing destination records are never overwritten. Quote glob patterns so the shell does not expand them.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX SOURCE DESTINATION | SOURCE DESTINATION")
                        .num_args(2..=3)
                        .required(true)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only source and destination."),
                ),
        )
        .subcommand(
            Command::new("remove")
                .about("Remove one form record.")
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PATH | PATH")
                        .num_args(1..=2)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only the form record path."),
                ),
        )
}

fn session_command(verbose: bool) -> Command {
    base_command("session", "Manage the default lockbox and open lockbox sessions.")
        .disable_help_subcommand(true)
        .arg_required_else_help(false)
        .after_help(verbose_help(
            verbose,
            "Examples:\n  lockbox session\n  lockbox session default secrets.lbox\n  lockbox session default --clear\n  lockbox session auto-open lockboxes",
            "Context:\n  Session shows the default lockbox and lockboxes currently open in the session agent. The default lockbox is the path used by commands that can safely omit a lockbox argument. An open lockbox has cached unlock material and can be read or changed without opening it again.",
        ))
        .arg(output_format_arg())
        .subcommand(
            Command::new("default")
                .about("Set or clear the default lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox session default secrets.lbox\n  lockbox session default --clear",
                    "Context:\n  Default sets the lockbox path used by commands that can safely omit a lockbox argument. Clearing the default only removes that path; it does not close any open lockbox sessions or change auto-open keys.",
                ))
                .arg(
                    Arg::new("clear")
                        .long("clear")
                        .action(ArgAction::SetTrue)
                        .conflicts_with("lockbox")
                        .help("Clear the default lockbox."),
                )
                .arg(optional("lockbox", "Lockbox path.").required_unless_present("clear")),
        )
        .subcommand(
            Command::new("close-all")
                .about("Close all lockboxes.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox session close-all",
                    "Context:\n  Close-all clears every cached lockbox content key from the session agent and clears the default lockbox.",
                )),
        )
        .subcommand(
            Command::new("stop")
                .about("Close all sessions and stop the session agent.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox session stop",
                    "Context:\n  Stop clears cached open sessions, clears the default lockbox, and shuts down the session agent process. Later commands can start it again when needed.",
                )),
        )
        .subcommand(
            Command::new("auto-open")
                .about("Allow reVault to use your OS login to automatically open the vault and lockboxes as required.")
                .disable_help_subcommand(true)
                .arg_required_else_help(false)
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox session auto-open status\n  lockbox session auto-open disable\n  lockbox session auto-open disable --yes\n  lockbox session auto-open vault\n  lockbox session auto-open lockboxes",
                    "Context:\n  Auto-open controls whether reVault may use your OS login to automatically open only the vault, or both the vault and lockboxes as required.",
                ))
                .subcommand(
                    Command::new("status")
                        .about("Show the current auto-open scope.")
                        .arg(output_format_arg()),
                )
                .subcommand(
                    Command::new("disable")
                        .about("Disable auto-open and close all open lockbox sessions.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox session auto-open disable\n  lockbox session auto-open disable --yes",
                            "Context:\n  Disabling auto-open removes the stored vault pass phrase from the OS key store and closes all open lockbox sessions.",
                        ))
                        .arg(
                            Arg::new("yes")
                                .long("yes")
                                .action(ArgAction::SetTrue)
                                .help("Disable auto-open without prompting."),
                        ),
                )
                .subcommand(Command::new("vault").about(
                    "Allow reVault to automatically open the vault only.",
                ))
                .subcommand(Command::new("lockboxes").about(
                    "Allow reVault to automatically open the vault and lockboxes.",
                )),
        )
}

fn access_command(verbose: bool) -> Command {
    sharing_command("access", "Grant or revoke who can open a lockbox.")
        .after_help(verbose_help(
            verbose,
            "Examples:\n  lockbox access list secrets.lbox\n  lockbox access grant secrets.lbox alice\n  lockbox access revoke secrets.lbox alice\n  lockbox access revoke secrets.lbox 2",
            "Context:\n  Access entries are stored on a lockbox and describe which profiles or contacts may open it. Use this command when sharing a lockbox or rotating/revoking access.",
        ))
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(
            Command::new("grant")
                .about("Allow a profile or contact to open a lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox access grant secrets.lbox alice\n  lockbox access grant secrets.lbox profile:alice\n  lockbox access grant secrets.lbox contact:alice\n  lockbox access grant secrets.lbox alice ./alice.pub",
                    "Context:\n  Access grant allows a profile or contact to open the lockbox. A bare name can refer to one of your saved profiles or saved contacts. If both use the same name, use profile:name or contact:name. For a public key file, provide the contact name first so the lockbox can record who the access entry belongs to.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PROFILE PUBLIC_KEY | PROFILE PUBLIC_KEY")
                        .num_args(1..=3)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass profile/contact and optional public key. Profile name, contact name, profile:name, contact:name, or contact name plus a public key file. Public key path."),
                ),
        )
        .subcommand(
            Command::new("list")
                .about("List who can open a lockbox.")
                .visible_alias("ls")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox access list secrets.lbox\n  lockbox access list --format json secrets.lbox",
                    "Context:\n  Access list shows the access slots currently attached to a lockbox, plus verified owner-signing status and host created/updated times. Contact names are not stored in lockbox metadata, so this output cannot identify or correlate the same contact across lockboxes. Use slot ids from this output when revoking access.",
                ))
                .arg(output_format_arg())
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX")
                        .num_args(0..=1)
                        .action(ArgAction::Append)
                        .help("Lockbox path. Defaults to the session default lockbox."),
                ),
        )
        .subcommand(
            Command::new("revoke")
                .about("Revoke access from a lockbox.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox access revoke secrets.lbox alice\n  lockbox access revoke secrets.lbox 2\n  lockbox access revoke secrets.lbox alice bob 7",
                    "Context:\n  Access revoke removes one or more open slots and rewrites the archive with a fresh content key. Pass local profile/contact names when this vault remembers which slots were granted for those names, or pass the slot id from access list. reVault fails safely if retained access cannot be reconstructed.",
                ))
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX NAME_OR_SLOT_ID... | NAME_OR_SLOT_ID...")
                        .num_args(1..)
                        .action(ArgAction::Append)
                        .help("With a session default lockbox, pass only local access names or slot ids."),
                ),
        )
        .subcommand(
            Command::new("refresh")
                .about("Refresh stale lockbox access entries.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox access refresh project.lbox alice\n  lockbox access refresh --all alice\n  lockbox access refresh --all --dry-run",
                    "Context:\n  Access refresh checks named contact access entries and rewrites matching entries to the current vault profile key. Use --dry-run first to see the planned changes and missing known lockboxes.",
                ))
                .arg(
                    Arg::new("all")
                        .long("all")
                        .action(ArgAction::SetTrue)
                        .help("Check every lockbox known to the vault."),
                )
                .arg(
                    Arg::new("args")
                        .value_name("LOCKBOX PROFILE | PROFILE")
                        .num_args(0..=2)
                        .action(ArgAction::Append)
                        .help("Without --all, pass lockbox and profile. With --all, optionally pass one profile."),
                )
                .arg(
                    Arg::new("dry-run")
                        .long("dry-run")
                        .action(ArgAction::SetTrue)
                        .help("Print the refresh plan without changing lockboxes."),
                )
                .arg(
                    Arg::new("yes")
                        .long("yes")
                        .action(ArgAction::SetTrue)
                        .help("Apply without interactive confirmation."),
                ),
        )
}

fn vault_command(verbose: bool) -> Command {
    base_command("vault", "Manage profiles, contacts, and reusable forms.")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(
            Command::new("init")
                .about("Create or open the local vault.")
                .after_help(verbose_help(
                    verbose,
                    "If the vault already exists, init reports the path and makes no changes. Use --verify to validate the pass phrase, or --overwrite only when replacing the vault and losing records stored only there.",
                    "Context:\n  The local vault stores profiles, contacts, and key-directory backups. New vault pass phrases must be at least 15 characters. A new vault also gets a default profile. Store the vault pass phrase safely; reVault cannot recover the vault without it.",
                ))
                .arg(
                    Arg::new("verify")
                        .long("verify")
                        .conflicts_with("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Ask for the vault pass phrase and verify the existing vault opens."),
                )
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .conflicts_with("verify")
                        .action(ArgAction::SetTrue)
                        .help("Replace an existing local vault."),
                ),
        )
        .subcommand(
            Command::new("backup")
                .about("Create an encrypted backup archive of the local vault.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault backup ./vault-backup.lockbox-backup\n  lockbox vault backup --overwrite ./vault-backup.lockbox-backup",
                    "Context:\n  Backup takes a locked snapshot of the encrypted local-vault.lbox file and stores it with a manifest and checksum. It does not decrypt or export vault records.",
                ))
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Replace an existing backup file."),
                )
                .arg(required("output", "Backup archive output path.")),
        )
        .subcommand(
            Command::new("passphrase")
                .about("Change the local vault pass phrase.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault passphrase",
                    "Context:\n  The command verifies the current vault pass phrase, creates an encrypted backup of the vault file, then replaces the vault pass phrase. Store the new pass phrase safely; reVault cannot recover the vault without it.",
                )),
        )
        .subcommand(
            Command::new("restore")
                .about("Restore the local vault from an encrypted backup archive.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault restore ./vault-backup.lockbox-backup\n  lockbox vault restore --overwrite ./vault-backup.lockbox-backup",
                    "Context:\n  Restore verifies the backup checksum before replacing the local vault. Existing vaults are not overwritten unless --overwrite is passed.",
                ))
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Replace the existing local vault."),
                )
                .arg(required("backup", "Backup archive input path.")),
        )
        .subcommand(vault_profile_command(verbose))
        .subcommand(
            Command::new("form")
                .about("Manage reusable form definitions.")
                .disable_help_subcommand(true)
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault form define login --field username:text --field password:secret\n  lockbox vault form definitions\n  lockbox form use login secrets.lbox",
                    "Context:\n  Vault form definitions are reusable templates stored in the local vault. Use form use to copy one into a lockbox before creating records that use it.",
                ))
                .subcommand_required(true)
                .arg_required_else_help(true)
                .subcommand(
                    Command::new("define")
                        .about("Create or revise a reusable form definition.")
                .override_usage(
                    "lockbox vault form define [alias] --field <NAME[:KIND[:required[:LABEL]]]>...",
                )
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault form define login --field username:text --field password:secret\n  lockbox vault form define --name Login --description \"Website sign-in\" --field username:text:required:User --field password:secret:required:Password\n  lockbox vault form define login --name Login --description \"Website sign-in\" --field username:text:required:User --field password:secret:required:Password\n\nField form:\n  NAME[:KIND[:required[:LABEL]]]\n\nKinds:\n  text, secret, password, url, email, date, month, notes, number\n\nFormats:\n  date uses YYYY-MM-DD; month uses YYYY-MM",
                    "Context:\n  Define stores the reusable form definition in the vault. The alias is optional; when omitted, --name is required and an alias slug is derived from the display name. If the alias already resolves to one definition, define appends a new revision.",
                ))
                        .arg(optional("alias", "Form alias."))
                        .arg(
                            Arg::new("name")
                                .long("name")
                                .value_name("DISPLAY_NAME")
                                .help("Human display name for this form definition."),
                        )
                        .arg(
                            Arg::new("description")
                                .long("description")
                                .value_name("TEXT")
                                .help("Human description for this form definition."),
                        )
                        .arg(
                            Arg::new("definition-id")
                                .long("definition-id")
                                .alias("type-id")
                                .value_name("DEFINITION_ID")
                                .help("Revise or create this stable form definition id."),
                        )
                        .arg(
                            Arg::new("field")
                                .long("field")
                                .value_name("NAME[:KIND[:required[:LABEL]]]")
                                .action(ArgAction::Append)
                                .required(true)
                                .help("Add one field to the definition."),
                        ),
                )
                .subcommand(
                    Command::new("definitions")
                        .about("List reusable form definitions.")
                        .arg(output_format_arg()),
                ),
        )
        .subcommand(
            Command::new("contact")
                .about("Manage contacts that can be given access to a lockbox.")
                .disable_help_subcommand(true)
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault contact list\n  lockbox vault contact receive <publish-code> alice\n  lockbox vault contact import alice ./alice.pub --fingerprint <fingerprint-code> --fingerprint-channel phone-call-to-owner\n  lockbox vault contact remove alice",
                    "Context:\n  Contacts are saved public keys for other people or systems. A contact can be added to a lockbox access list, but cannot open a lockbox by itself; opening requires the matching private profile.",
                ))
                .subcommand_required(true)
                .arg_required_else_help(true)
                .subcommand(
                    Command::new("list")
                        .about("List saved contacts.")
                        .visible_alias("ls")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault contact list\n  lockbox vault contact list --format json",
                            "Context:\n  Contact list shows public keys you have saved for other profiles. Saved contacts have already passed fingerprint verification during import or receive; there is no separate trust-state that changes over time. Use these names with access grant when granting lockbox access.",
                        ))
                        .arg(output_format_arg()),
                )
                .subcommand(
                    Command::new("import")
                        .about("Import a contact public key after fingerprint verification.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault contact import alice ./alice.pub --fingerprint <fingerprint-code> --fingerprint-channel phone-call-to-owner\n  lockbox vault contact import --overwrite alice ./alice-new.pub --fingerprint <fingerprint-code> --fingerprint-channel sms-to-owner",
                            "Context:\n  Contact import saves someone else's public key only after the 96-bit Crockford public-key fingerprint code matches. Ask the key owner for the code over a receiver-initiated second channel before importing the key. Email and owner-initiated messages are rejected.",
                        ))
                        .arg(
                            Arg::new("overwrite")
                                .long("overwrite")
                                .hide(!verbose)
                                .action(ArgAction::SetTrue)
                                .help("Replace an existing contact."),
                        )
                        .arg(
                            Arg::new("fingerprint")
                                .long("fingerprint")
                                .value_name("FINGERPRINT-CODE")
                                .help("96-bit Crockford public-key fingerprint code from the key owner. Prompts when omitted."),
                        )
                        .arg(
                            Arg::new("fingerprint-channel")
                                .long("fingerprint-channel")
                                .value_name("CHANNEL")
                                .help("How the fingerprint was received: phone-call-to-owner, sms-to-owner, or in-person. Prompts when omitted."),
                        )
                        .arg(required("name", "Contact name."))
                        .arg(required("public-key", "Public key path.")),
                )
                .subcommand(
                    Command::new("receive")
                        .about("Receive a published profile and save it as a contact.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault contact receive <publish-code>\n  lockbox vault contact receive <publish-code> alice",
                            concat!(
                                "Context:\n  Receive saves the published public key and signing key as a local contact. ",
                                "The key server must have verified the publisher email first. Enter the ",
                                "96-bit Crockford fingerprint code by asking the publisher over a communications channel that you ",
                                "already trust. You must initiate the communication. If the publisher sends you ",
                                "the fingerprint before you ask, do not accept it. Short PINs are only ",
                                "accidental-error checks and are too small to authenticate a public key against ",
                                "substitution. Email, newly supplied channels, and owner-initiated messages are rejected.",
                            ),
                        ))
                        .arg(key_server_arg())
                        .arg(publish_topology_arg())
                        .arg(
                            Arg::new("fingerprint")
                                .long("fingerprint")
                                .value_name("FINGERPRINT-CODE")
                                .help("96-bit Crockford contact fingerprint code from a trusted second channel. Prompts when omitted."),
                        )
                        .arg(
                            Arg::new("fingerprint-channel")
                                .long("fingerprint-channel")
                                .value_name("CHANNEL")
                                .help("How the fingerprint was received: phone-call-to-owner, sms-to-owner, or in-person. Prompts when omitted."),
                        )
                        .arg(
                            Arg::new("overwrite")
                                .long("overwrite")
                                .action(ArgAction::SetTrue)
                                .help("Replace an existing contact."),
                        )
                        .arg(required("publish-code", "Publish code."))
                        .arg(optional("contact-name", "Contact name to save.")),
                )
                .subcommand(
                    Command::new("remove")
                        .about("Remove a contact.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault contact remove alice",
                            "Context:\n  Contact remove deletes the saved public key from your vault. It does not remove access already written into any lockbox; use access revoke for that.",
                        ))
                        .arg(
                            required("name", "Contact name.")
                                .add(ArgValueCompleter::new(completion::contact_candidates)),
                        ),
                ),
        )
        .subcommand(
            Command::new("lockbox")
                .about("Manage lockboxes remembered by the vault.")
                .disable_help_subcommand(true)
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault lockbox list\n  lockbox vault lockbox move ./old.lbox ./archive/new.lbox\n  lockbox vault lockbox forget ./old-project.lbox",
                    "Context:\n  The vault remembers lockboxes it has created, opened, or modified so bulk maintenance commands can find them later. Move coordinates the file, session cache, default path, lock sidecar, and vault record. Forget removes only the vault reference; it does not delete the lockbox file.",
                ))
                .subcommand_required(true)
                .arg_required_else_help(true)
                .subcommand(
                    Command::new("list")
                        .about("List lockboxes remembered by the vault.")
                        .visible_alias("ls")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault lockbox list\n  lockbox vault lockbox list --format json",
                            "Context:\n  The lockbox list command reports remembered lockboxes, including file state, signed-owner status, compact file size, lockbox id, and path.",
                        ))
                        .arg(output_format_arg()),
                )
                .subcommand(
                    Command::new("move")
                        .about("Move a lockbox and update its session and vault paths.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault lockbox move ./secrets.lbox ./archive/\n  lockbox vault lockbox move ./secrets.lbox ./archive/renamed.lbox",
                            "Context:\n  Move closes the old cached path, moves the lockbox and hidden lock sidecar, updates the remembered vault path, and updates the session default when it points at the source. Source and destination must be on the same filesystem.",
                        ))
                        .arg(required("source", "Current lockbox path."))
                        .arg(required(
                            "destination",
                            "New lockbox path, or an existing destination directory.",
                        )),
                )
                .subcommand(
                    Command::new("forget")
                        .about("Forget one remembered lockbox path.")
                        .after_help(verbose_help(
                            verbose,
                            "Examples:\n  lockbox vault lockbox forget ./old-project.lbox",
                            "Context:\n  Forget removes a stale known-lockbox record from the vault. It does not delete the lockbox file.",
                        ))
                        .arg(required("lockbox", "Lockbox path to forget.")),
                ),
        )
}

fn key_server_arg() -> Arg {
    Arg::new("server")
        .long("server")
        .value_name("URL")
        .help("Key server /v1/publish URL or host.")
}

fn publish_topology_arg() -> Arg {
    Arg::new("topology-url")
        .long("topology-url")
        .value_name("URL")
        .help("Key server /v1/topology URL.")
}

fn vault_profile_command(verbose: bool) -> Command {
    Command::new("profile")
        .about("Manage your lockbox open profiles.")
        .disable_help_subcommand(true)
        .after_help(verbose_help(
            verbose,
            "Examples:\n  lockbox vault profile list\n  lockbox vault profile create laptop\n  lockbox vault profile publish laptop\n  lockbox vault profile fingerprint laptop\n  lockbox vault profile backup ./default.profile-backup",
            "Context:\n  A profile has a public key, private open key, and owner signing key. Publish or export the public key so someone else can grant you access to a lockbox. Use profile backup and restore for emergency recovery of one profile.",
        ))
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(
            Command::new("list")
                .about("List local profiles.")
                .visible_alias("ls")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile list\n  lockbox vault profile list --format json",
                    "Context:\n  Profile list shows the private open profiles stored in your vault. These are the profiles reVault can use when opening lockboxes granted to you.",
                ))
                .arg(output_format_arg()),
        )
        .subcommand(
            Command::new("create")
                .about("Create one of your profiles.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile create\n  lockbox vault profile create laptop\n  lockbox vault profile export ./laptop.pub --name laptop",
                    "Context:\n  Profile create generates a new profile in your vault. With no name, reVault creates the `default` profile. To publish the profile, create it first and then run `lockbox vault profile publish` or `lockbox vault profile export <path>`.",
                ))
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .hide(!verbose)
                        .action(ArgAction::SetTrue)
                        .help("Replace an existing profile."),
                )
                .arg(optional("name", "Profile name."))
        )
        .subcommand(
            Command::new("history")
                .about("Show profile key generations.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile history\n  lockbox vault profile history laptop --format json",
                    "Context:\n  Profile history shows the active and retired key generations for one vault profile. Retired generations are retained so older lockboxes can still be opened until their access entries are refreshed.",
                ))
                .arg(output_format_arg())
                .arg(
                    optional("name", "Profile name.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                ),
        )
        .subcommand(
            Command::new("email")
                .about("Set the email address associated with a profile.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile email alice@example.com\n  lockbox vault profile email laptop alice@example.com",
                    "Context:\n  Publish requires a profile email address. The key server sends a verification link to this address before receivers can receive the public key by email.",
                ))
                .arg(
                    Arg::new("args")
                        .value_names(["profile", "email"])
                        .num_args(1..=2)
                        .required(true)
                        .help("Optional profile name followed by the profile email address."),
                ),
        )
        .subcommand(
            Command::new("fingerprint")
                .about("Show the publish fingerprint for one profile.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile fingerprint\n  lockbox vault profile fingerprint laptop",
                    "Context:\n  Fingerprint prints the same 96-bit Crockford contact fingerprint code shown by publish. The receiver must ask you for this code through a trusted second channel before saving the contact.",
                ))
                .arg(
                    optional("name", "Profile name. Defaults to default.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                ),
        )
        .subcommand(
            Command::new("publish")
                .about("Publish one profile public key by verified email.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile publish\n  lockbox vault profile publish laptop",
                    "Context:\n  Publish sends one profile public key to the key server and prints a 96-bit Crockford fingerprint code. The receiver must ask you for that code through a trusted second channel before saving the contact.",
                ))
                .arg(key_server_arg())
                .arg(publish_topology_arg())
                .arg(
                    Arg::new("ttl")
                        .long("ttl")
                        .value_name("SECONDS")
                        .help("Publish lifetime in seconds."),
                )
                .arg(
                    Arg::new("max-receives")
                        .long("max-receives")
                        .value_name("N")
                        .help("Maximum successful receives."),
                )
                .arg(
                    optional("name", "Profile name. Defaults to default.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                ),
        )
        .subcommand(
            Command::new("backup")
                .about("Back up one profile to a text recovery file.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile backup ./default.profile-backup\n  lockbox vault profile backup ./laptop.profile-backup --name laptop",
                    "Context:\n  Profile backup writes the same text recovery block printed by vault init. It contains the profile name, fingerprint, profile private key, and owner signing private key.",
                ))
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Replace an existing backup file."),
                )
                .arg(
                    Arg::new("name")
                        .long("name")
                        .value_name("PROFILE")
                        .help("Profile name. Defaults to default.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                )
                .arg(required("output", "Profile backup output path.")),
        )
        .subcommand(
            Command::new("restore")
                .about("Restore one profile from a text recovery file.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile restore ./default.profile-backup\n  lockbox vault profile restore ./default.profile-backup --name laptop --overwrite",
                    "Context:\n  Profile restore reads one profile backup text file, derives the public key from the private key, and restores the required owner signing key. If the profile already exists, use --overwrite; reVault backs up the current vault before replacing it.",
                ))
                .arg(
                    Arg::new("overwrite")
                        .long("overwrite")
                        .action(ArgAction::SetTrue)
                        .help("Replace an existing profile after backing up the current vault."),
                )
                .arg(
                    Arg::new("name")
                        .long("name")
                        .value_name("PROFILE")
                        .help("Restore to this profile name instead of the name in the backup."),
                )
                .arg(required("input", "Profile backup input path.")),
        )
        .subcommand(
            Command::new("export")
                .about("Export one profile public key.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile export ./default.pub\n  lockbox vault profile export ./laptop.pub --name laptop",
                    "Context:\n  Profile export writes the public key for sharing with someone who needs to grant you access to a lockbox. Use profile backup, not export, for private recovery material.",
                ))
                .arg(format_arg(verbose))
                .arg(
                    Arg::new("name")
                        .long("name")
                        .value_name("PROFILE")
                        .help("Profile name. Defaults to default.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                )
                .arg(required("output", "Public key output path.")),
        )
        .subcommand(
            Command::new("remove")
                .about("Remove a profile.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile remove laptop\n  lockbox vault profile remove --force laptop",
                    "Context:\n  Profile remove deletes a profile from your vault. Lockboxes that only grant access to that profile may become inaccessible from this vault.",
                ))
                .arg(
                    Arg::new("force")
                        .long("force")
                        .action(ArgAction::SetTrue)
                        .help("Remove the key without an interactive confirmation."),
                )
                .arg(
                    optional("name", "Profile name.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                ),
        )
        .subcommand(
            Command::new("rotate")
                .about("Rotate a profile to a new key generation.")
                .after_help(verbose_help(
                    verbose,
                    "Examples:\n  lockbox vault profile rotate\n  lockbox vault profile rotate laptop",
                    "Context:\n  Profile rotate creates a new active private key generation and retires the previous active generation. Refresh remembered lockboxes afterward so they grant access to the new key.",
                ))
                .arg(
                    optional("name", "Profile name.")
                        .add(ArgValueCompleter::new(completion::profile_candidates)),
                ),
        )
}

fn format_arg(verbose: bool) -> Arg {
    Arg::new("format")
        .long("format")
        .hide(!verbose)
        .value_name("lockbox-pem|jwk|jwks|raw-hex")
        .help("Select the key file format.")
}

fn output_format_arg() -> Arg {
    Arg::new("format")
        .long("format")
        .value_name("table|tsv|json")
        .default_value("table")
        .help("Output format.")
}

fn required(name: &'static str, help: &'static str) -> Arg {
    dynamic_completion_arg(Arg::new(name), name)
        .value_name(name)
        .required(true)
        .help(help)
}

fn optional(name: &'static str, help: &'static str) -> Arg {
    dynamic_completion_arg(Arg::new(name), name)
        .value_name(name)
        .required(false)
        .help(help)
}

fn dynamic_completion_arg(arg: Arg, name: &str) -> Arg {
    match name {
        "form" => arg.add(ArgValueCompleter::new(completion::form_candidates)),
        _ => arg,
    }
}

fn completion_command() -> Command {
    Command::new("completion")
        .about("Generate, install, or remove dynamic shell completion.")
        .disable_help_subcommand(true)
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommands([
            Command::new("generate")
                .about("Write a completion registration script to stdout or a file.")
                .arg(completion_shell_arg())
                .arg(
                    Arg::new("output")
                        .long("output")
                        .short('o')
                        .value_name("FILE")
                        .help("Write the script to this file."),
                ),
            Command::new("install")
                .about("Install completion in a standard per-user completion directory.")
                .arg(completion_shell_arg())
                .arg(
                    Arg::new("path")
                        .long("path")
                        .value_name("FILE")
                        .help("Override the standard per-user installation path."),
                ),
            Command::new("uninstall")
                .about("Remove a completion installed by revault.")
                .arg(completion_shell_arg())
                .arg(
                    Arg::new("path")
                        .long("path")
                        .value_name("FILE")
                        .help("Override the standard per-user installation path."),
                ),
        ])
}

fn migration_command(verbose: bool) -> Command {
    Command::new("migrate")
        .about("Migrate vaults and archives between native format versions.")
        .hide(!verbose)
        .disable_help_subcommand(true)
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommands([
            migration_vault_command(verbose),
            migration_archive_command(verbose),
        ])
}

fn migration_vault_command(verbose: bool) -> Command {
    Command::new("vault")
        .about("Migrate the configured vault to the latest format.")
        .arg(migration_output_arg())
        .arg(migration_replace_arg())
        .arg(migration_exporter_arg())
        .subcommands([
            Command::new("export")
                .about("Export the configured vault to a migration artifact.")
                .hide(!verbose)
                .arg(migration_output_arg().required(true))
                .arg(hidden_secret_stdin_arg("vault-password-stdin"))
                .arg(hidden_secret_stdin_arg("migration-password-stdin")),
            Command::new("upgrade")
                .about("Upgrade a vault migration artifact to the latest schema.")
                .hide(!verbose)
                .arg(required("artifact", "Input migration artifact."))
                .arg(migration_output_arg().required(true)),
            Command::new("import")
                .about("Import a vault migration artifact into a new vault.")
                .hide(!verbose)
                .arg(required("artifact", "Input migration artifact."))
                .arg(migration_output_arg().required(true)),
            Command::new("verify")
                .about("Verify a vault migration artifact.")
                .hide(!verbose)
                .arg(required("artifact", "Migration artifact to verify.")),
        ])
}

fn migration_archive_command(verbose: bool) -> Command {
    Command::new("archive")
        .about("Migrate an archive to the latest format.")
        .arg(optional("lockbox", "Archive to migrate."))
        .arg(migration_output_arg())
        .arg(migration_replace_arg())
        .arg(migration_exporter_arg())
        .subcommands([
            Command::new("export")
                .about("Export an archive to a migration artifact.")
                .hide(!verbose)
                .arg(required("lockbox", "Archive to export."))
                .arg(migration_output_arg().required(true))
                .arg(hidden_secret_stdin_arg("migration-password-stdin")),
            Command::new("upgrade")
                .about("Upgrade an archive migration artifact to the latest schema.")
                .hide(!verbose)
                .arg(required("artifact", "Input migration artifact."))
                .arg(migration_output_arg().required(true)),
            Command::new("import")
                .about("Import an archive migration artifact.")
                .hide(!verbose)
                .arg(required("artifact", "Input migration artifact."))
                .arg(migration_output_arg().required(true)),
            Command::new("verify")
                .about("Verify an archive migration artifact.")
                .hide(!verbose)
                .arg(required("artifact", "Migration artifact to verify.")),
        ])
}

fn migration_output_arg() -> Arg {
    Arg::new("output")
        .long("output")
        .short('o')
        .value_name("PATH")
        .help("Write the migrated artifact to this path.")
}

fn migration_replace_arg() -> Arg {
    Arg::new("replace")
        .long("replace")
        .action(ArgAction::SetTrue)
        .conflicts_with("output")
        .help("Replace the source after retaining a versioned backup.")
}

fn migration_exporter_arg() -> Arg {
    Arg::new("exporter")
        .long("exporter")
        .value_name("PATH")
        .hide(true)
        .help("Use this historical reVault exporter executable.")
}

fn hidden_secret_stdin_arg(name: &'static str) -> Arg {
    Arg::new(name)
        .long(name)
        .hide(true)
        .action(ArgAction::SetTrue)
}

fn completion_shell_arg() -> Arg {
    Arg::new("shell")
        .long("shell")
        .value_name("bash|zsh|fish|powershell|elvish")
        .help("Shell override; otherwise detect SHELL or PowerShell.")
}

fn verbose_help(verbose: bool, normal: &'static str, context: &'static str) -> String {
    if verbose {
        format!("{context}\n\n{normal}")
    } else {
        normal.to_string()
    }
}

fn apply_verbose_help_template(mut command: Command) -> Command {
    if let Some(after_help) = command.get_after_help().map(|help| help.to_string()) {
        if let Some((context, examples)) = after_help.split_once("\n\nExamples:") {
            if context.starts_with("Context:") {
                command = command
                    .before_help(context.to_string())
                    .after_help(format!("Examples:{examples}"));
            }
        }
    }
    command
        .help_template(VERBOSE_HELP_TEMPLATE)
        .mut_subcommands(apply_verbose_help_template)
}