gloves 0.5.11

seamless secret manager and handoff
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
mod commands;
mod daemon;
#[cfg(feature = "tui")]
mod navigator;
mod output;
mod runtime;
mod secret_input;
mod vault_cmd;

use std::path::PathBuf;

use chrono::Duration;
use clap::{Parser, Subcommand, ValueEnum};

use crate::{
    config::VaultMode, error::Result, types::Owner,
    DEFAULT_SECRET_TTL_DAYS as DEFAULT_CONFIG_SECRET_TTL_DAYS,
};

const DEFAULT_AGENT_ID: &str = "default-agent";
const DEFAULT_ROOT_DIR: &str = ".openclaw/secrets";
const DEFAULT_TTL_DAYS: i64 = DEFAULT_CONFIG_SECRET_TTL_DAYS;
const DEFAULT_TTL_SECONDS: i64 = 86_400;
const DEFAULT_DAEMON_REQUEST_LIMIT_BYTES: usize = 16 * 1024;
const DEFAULT_DAEMON_BIND: &str = "127.0.0.1:7788";
const DEFAULT_DAEMON_IO_TIMEOUT_SECONDS: u64 = 5;
const DEFAULT_VAULT_MOUNT_TTL: &str = "1h";
const DEFAULT_VAULT_SECRET_TTL_DAYS: i64 = 365;
const DEFAULT_VAULT_SECRET_LENGTH_BYTES: usize = 64;
const SECRET_NAME_ARG_HELP: &str =
    "Secret id (example: `service/token`). Allowed characters: letters, digits, `.`, `_`, `-`, and `/`.";
const REQUEST_ID_ARG_HELP: &str =
    "Request UUID from `gloves requests list` (example: `123e4567-e89b-12d3-a456-426614174000`).";
const ERROR_CODE_ARG_HELP: &str = "Error code from CLI stderr (example: `E102`).";
const ERROR_FORMAT_ARG_HELP: &str = "Error output format (`text` or `json`).";
const CLI_AFTER_HELP: &str = r#"Examples:
  gloves bootstrap --profile openclaw --root ~/.openclaw/secrets --config ~/.openclaw/.gloves.toml --agents main,relationships,coder
  gloves --root .openclaw/secrets init
  gloves --root .openclaw/secrets secrets set service/token --generate
  gloves --root .openclaw/secrets secrets get service/token --pipe-to cat
  gloves --root .openclaw/secrets run --env API_KEY=gloves://shared/github-token -- env
  gloves --root .openclaw/secrets exec env --env API_KEY=gloves://shared/github-token -- env
  gloves --root .openclaw/secrets request prod/db --reason "run migration"
  gloves --root .openclaw/secrets requests list
  gloves --root .openclaw/secrets secrets grant service/token --to agent-b
  gloves help requests approve
  gloves help secrets set
  gloves requests help approve
  gloves tui --config /etc/gloves/prod.gloves.toml audit --limit 100
  gloves explain E102
  gloves --json requests approve 123e4567-e89b-12d3-a456-426614174000
  gloves --error-format json requests approve 123e4567-e89b-12d3-a456-426614174000

Version:
  gloves --version
  gloves --json --version

More help:
  gloves help [topic...]
  gloves requests help [topic...]
  gloves help vault
"#;
const SET_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets set service/token --generate
  gloves secrets set long-lived/token --generate --ttl never
  printf 'secret-value' | gloves secrets set service/token --stdin --ttl 7

Tips:
  - Use `--generate` or `--stdin` for safer input handling.
  - `--ttl` accepts a positive number of days or `never`.
  - Omitting `--ttl` uses `defaults.secret_ttl_days` from config.
  - `gloves secrets set` prints the expiry timestamp or says `never expires`.
"#;
const REQUEST_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves request prod/db --reason "run migration"
  gloves requests list
  gloves requests approve <request-id>
"#;
const REQUESTS_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves requests list
  gloves requests approve <request-id>
  gloves requests deny <request-id>

Aliases:
  gloves req list
  gloves req approve <request-id>
  gloves req deny <request-id>

Tip:
  Use this command group when you want noun-first navigation.
"#;
const APPROVE_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves approve <request-id>
  gloves --agent human-ops approve <request-id>

Find request IDs:
  gloves requests list

See also:
  gloves requests approve  (preferred form)
"#;
const DENY_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves deny <request-id>
  gloves --agent human-ops deny <request-id>

Find request IDs:
  gloves requests list

See also:
  gloves requests deny  (preferred form)
"#;
const LIST_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves list
  gloves list --pending

See also:
  gloves requests list  (alias: list only pending requests)
"#;
const GRANT_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets grant service/token --to agent-b
  gloves --agent default-agent secrets grant service/token --to reviewer-a

Notes:
  - Grant updates recipient access for an existing agent-owned secret.
  - The caller must be the original creator of the secret.
"#;
const GET_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets get service/token
  gloves secrets get service/token --pipe-to cat

Recovery:
  If the secret does not exist, run `gloves list`.
"#;
const REVOKE_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets revoke service/token

Recovery:
  Use `gloves list` to confirm the exact secret id before revoking.
"#;
const STATUS_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets status prod/db
  gloves requests list
"#;
const HELP_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves help
  gloves help secrets set
  gloves help requests approve
  gloves secrets help get
  gloves requests help approve
  gloves vault help mount

Tips:
  - Use command paths to drill down recursively.
  - `help` works both at the top level and inside command groups.
"#;
const SECRETS_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves secrets set service/token --generate
  gloves secrets get service/token
  gloves secrets grant service/token --to agent-b
  gloves secrets revoke service/token
  gloves secrets status service/token
"#;
const EXPLAIN_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves explain E102
  gloves explain e200

Tip:
  Error codes are shown in stderr output, for example `error[E102]: ...`.
"#;
#[cfg(feature = "tui")]
const TUI_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves tui
  gloves tui --config /etc/gloves/prod.gloves.toml audit --limit 100

Startup:
  - When a command path is provided after `gloves tui`, it is preloaded and auto-executed.
  - Startup runs open in fullscreen output view.

Controls:
  - Up/Down or j/k: move command tree
  - Left/Right: collapse/expand command groups in command tree; change choices in field panes; in output they pan horizontally
  - Shift+Left/Shift+Right: horizontal scroll for focused pane
  - Mouse wheel left/right (or Shift+wheel): horizontal scroll for hovered pane
  - Mouse wheel up/down: vertical scroll in command tree and output pane
  - o or O: focus execution output pane
  - Enter: split view cycles commands -> global flags -> command fields -> run -> commands; fullscreen keeps current pane focus
  - Tab / Shift+Tab: switch panes
  - f: toggle fullscreen for focused pane
  - e: edit selected text field
  - Space: toggle booleans
  - Left/Right in field panes: change choices in split view; in fullscreen they pan horizontally
  - r or F5: execute selected command with live streaming output
  - Ctrl+C: cancel active run (q/Esc waits for cancellation first)
  - ? : run `gloves help` for selected command in output pane
  - / : filter command tree
  - Home or g: jump output to top and disable follow-tail
  - End or G: jump output to tail and re-enable follow-tail
  - c: clear output history cards
  - Esc: exit fullscreen and return focus to command tree; in split view it quits
  - q: quit
"#;
const GPG_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves --agent agent-main gpg create
  gloves --agent agent-main gpg fingerprint
"#;
const SET_IDENTITY_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves set-identity --agent devy
  gloves set-identity --agent devy --force
"#;
const BOOTSTRAP_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves bootstrap --profile openclaw --root ~/.openclaw/secrets --config ~/.openclaw/.gloves.toml --agents main,relationships,coder
  gloves bootstrap --profile openclaw --root ~/.openclaw/secrets --agents main,coder --force

This command is intentionally thin:
  - initializes the existing runtime layout
  - creates agent age identities and recipients files
  - writes `.gloves.toml` and `store/.gloves.yaml`
  - validates config and verifies runtime state

It does not migrate secrets, patch OpenClaw config files, mutate Docker, or bootstrap GPG by default.
"#;
const OPENCLAW_BOOTSTRAP_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves openclaw bootstrap --agents main,relationships,coder --root ~/.openclaw/secrets --config ~/.openclaw/.gloves.toml
"#;
const OPENCLAW_DOCTOR_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves doctor openclaw
"#;
const INTEGRATION_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves integration github list-refs
  gloves integration github test token --profile work
  gloves integration github rotate token --profile personal --generate
"#;
const TOP_LEVEL_SET_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves --agent devy set agents/devy/api-keys/anthropic --stdin
  gloves --agent main set shared/database-url --value postgres://localhost
"#;
const TOP_LEVEL_GET_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves --agent devy get agents/devy/api-keys/anthropic --format raw
  gloves --agent devy get agents/devy/api-keys/anthropic --format json
"#;
const RUN_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves run --env API_KEY=gloves://shared/github-token -- curl -H "Authorization: Bearer $API_KEY" https://api.example.com
  gloves run --env DB_URL=gloves://shared/db-url -- ./migrate.sh

Comparable tools:
  - `op run`
  - `doppler run`
  - `aws-vault exec`

Use `gloves run` for the generic secret-aware execution UX.
Use `gloves exec env` when you want the lower-level env-delivery mechanic directly.
Use `gloves vault exec` when you specifically need the mount / execute / unmount workflow.
"#;
const EXEC_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves exec env --env API_KEY=gloves://shared/github-token -- env

Use `gloves exec` when you want to select a specific delivery mechanism directly.
"#;
const EXEC_ENV_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves exec env --env API_KEY=gloves://shared/github-token -- env
  gloves exec env --env DB_URL=gloves://shared/db-url -- ./migrate.sh

This command is the explicit env-delivery primitive behind `gloves run`.
"#;
const SHOW_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves show agents/devy/api-keys/anthropic --redacted
  gloves show agents/devy/api-keys/anthropic --format json
"#;
const UPDATEKEYS_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves updatekeys
  gloves updatekeys --path shared --dry-run
"#;
const ROTATE_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves rotate --agent devy
  gloves rotate --agent devy --keep-old
"#;
const GPG_CREATE_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves --agent agent-main gpg create

Notes:
  - Creates a key only when missing (idempotent).
"#;
const GPG_FINGERPRINT_COMMAND_AFTER_HELP: &str = r#"Examples:
  gloves --agent agent-main gpg fingerprint

Recovery:
  If no key exists yet, run `gloves --agent <id> gpg create` first.
"#;

/// Top-level command line parser.
#[derive(Debug, Parser)]
#[command(
    name = "gloves",
    version,
    about = "Secure secrets control plane for OpenClaw and multi-agent runtimes.",
    after_help = CLI_AFTER_HELP,
    infer_subcommands = true,
    disable_help_subcommand = true,
    arg_required_else_help = true
)]
pub struct Cli {
    /// Root storage directory override.
    /// Default when unset and no config override is active: `.openclaw/secrets`.
    #[arg(long, global = true)]
    pub root: Option<PathBuf>,
    /// Agent identifier override for this invocation.
    /// Default when unset and no config override is active: `default-agent`.
    #[arg(long, global = true)]
    pub agent: Option<String>,
    /// Config file override path.
    #[arg(long, global = true)]
    pub config: Option<PathBuf>,
    /// Disable config loading and discovery.
    #[arg(long, global = true)]
    pub no_config: bool,
    /// Vault runtime mode override.
    #[arg(long, value_enum, global = true)]
    pub vault_mode: Option<VaultModeArg>,
    /// Error output format.
    #[arg(
        long,
        value_enum,
        global = true,
        default_value_t = ErrorFormatArg::Text,
        help = ERROR_FORMAT_ARG_HELP
    )]
    pub error_format: ErrorFormatArg,
    /// Emit JSON output for command results and errors.
    #[arg(long, global = true)]
    pub json: bool,
    /// Subcommand.
    #[command(subcommand)]
    pub command: Command,
}

/// Supported CLI commands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Initializes directory tree.
    Init,
    /// Bootstraps a fresh runtime layout for one profile.
    #[command(after_help = BOOTSTRAP_COMMAND_AFTER_HELP)]
    Bootstrap {
        /// Bootstrap profile.
        #[arg(long, value_enum)]
        profile: BootstrapProfileArg,
        /// Comma-separated agent identifiers.
        #[arg(long, value_name = "AGENT_LIST")]
        agents: String,
        /// Default agent identifier for generated config.
        #[arg(long)]
        default_agent: Option<String>,
        /// Replace existing bootstrap files and identities.
        #[arg(long)]
        force: bool,
    },
    /// OpenClaw-specific runtime setup and bridge commands.
    Openclaw {
        /// OpenClaw operation.
        #[command(subcommand)]
        command: OpenclawCommand,
    },
    /// Runs health checks for supported targets.
    Doctor {
        /// Doctor operation.
        #[command(subcommand)]
        command: DoctorCommand,
    },
    /// Runs generic integration workflows derived from config.
    #[command(after_help = INTEGRATION_COMMAND_AFTER_HELP)]
    Integration {
        /// Integration name from `.gloves.toml`.
        name: String,
        /// Integration operation.
        #[command(subcommand)]
        command: IntegrationCommand,
    },
    /// Creates an age identity for one OpenClaw agent namespace.
    #[command(after_help = SET_IDENTITY_COMMAND_AFTER_HELP)]
    SetIdentity {
        /// Agent identifier.
        #[arg(long)]
        agent: String,
        /// Replace an existing identity, preserving it as revoked.
        #[arg(long)]
        force: bool,
        /// Reserved for future post-quantum identities.
        #[arg(long, hide = true)]
        post_quantum: bool,
    },
    /// Stores a namespaced secret using `.gloves.yaml` creation rules.
    #[command(after_help = TOP_LEVEL_SET_COMMAND_AFTER_HELP)]
    Set {
        /// Secret path.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        path: String,
        /// Inline secret value (prefer `--stdin`).
        #[arg(long)]
        value: Option<String>,
        /// Read the secret value from stdin.
        #[arg(long)]
        stdin: bool,
    },
    /// Reads a namespaced secret.
    #[command(after_help = TOP_LEVEL_GET_COMMAND_AFTER_HELP)]
    Get {
        /// Secret path.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        path: String,
        /// Output format.
        #[arg(long, value_enum, default_value_t = SecretReadFormatArg::Raw)]
        format: SecretReadFormatArg,
    },
    /// Runs one command with secrets injected into its environment.
    #[command(after_help = RUN_COMMAND_AFTER_HELP)]
    Run {
        /// Secret ref bindings for environment injection.
        /// Format: `NAME=gloves://namespace/secret-path`. Repeat `--env` for each binding.
        #[arg(long = "env", value_name = "BINDING", action = clap::ArgAction::Append)]
        env: Vec<String>,
        /// Command and arguments to execute.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        command: Vec<String>,
    },
    /// Runs one command with an explicit delivery mechanic.
    #[command(after_help = EXEC_COMMAND_AFTER_HELP)]
    Exec {
        /// Delivery mechanic.
        #[command(subcommand)]
        command: ExecCommand,
    },
    /// Shows namespaced secret metadata without revealing the value.
    #[command(after_help = SHOW_COMMAND_AFTER_HELP)]
    Show {
        /// Secret path.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        path: String,
        /// Show only redacted metadata.
        #[arg(long, default_value_t = true)]
        redacted: bool,
        /// Output format.
        #[arg(long, value_enum, default_value_t = SecretShowFormatArg::Text)]
        format: SecretShowFormatArg,
    },
    /// Re-encrypts namespaced secrets using current creation rules and recipients.
    #[command(after_help = UPDATEKEYS_COMMAND_AFTER_HELP)]
    Updatekeys {
        /// Optional path prefix filter.
        #[arg(long)]
        path: Option<String>,
        /// Report changes without modifying files.
        #[arg(long)]
        dry_run: bool,
        /// Explicit identity file used for decryption.
        #[arg(long)]
        identity: Option<PathBuf>,
    },
    /// Rotates one agent identity and re-encrypts affected secrets.
    #[command(after_help = ROTATE_COMMAND_AFTER_HELP)]
    Rotate {
        /// Agent identifier.
        #[arg(long)]
        agent: String,
        /// Preserve the old identity under a non-revoked archive name.
        #[arg(long)]
        keep_old: bool,
    },
    /// Explains a stable error code with recovery guidance.
    #[command(after_help = EXPLAIN_COMMAND_AFTER_HELP)]
    Explain {
        /// Error code from stderr (for example: `E102`).
        #[arg(help = ERROR_CODE_ARG_HELP)]
        code: String,
    },
    /// Opens an interactive command navigator.
    #[cfg(feature = "tui")]
    #[command(visible_alias = "ui", after_help = TUI_COMMAND_AFTER_HELP)]
    Tui {
        /// Optional TUI startup arguments: global overrides first, then command path and fields.
        /// Example: `gloves tui --config /etc/gloves/prod.gloves.toml audit --limit 100`
        #[arg(
            value_name = "ARGS",
            num_args = 0..,
            trailing_var_arg = true,
            allow_hyphen_values = true
        )]
        args: Vec<String>,
    },
    /// Shows recursively helpful command documentation.
    #[command(after_help = HELP_COMMAND_AFTER_HELP)]
    Help {
        /// Command path segments (for example: `requests approve`).
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Manages secret workflows (set/get/grant/revoke/status).
    #[command(after_help = SECRETS_COMMAND_AFTER_HELP)]
    Secrets {
        /// Secret operation.
        #[command(subcommand)]
        command: SecretsCommand,
    },
    /// Prints redacted env export text.
    Env {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
        /// Variable name.
        var: String,
    },
    /// Creates one pending human request.
    #[command(after_help = REQUEST_COMMAND_AFTER_HELP)]
    Request {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
        /// Justification.
        #[arg(long)]
        reason: String,
        /// Optional allowlist of requestable secret patterns.
        /// Format: comma-separated patterns (`*`, `namespace/*`, or exact id).
        #[arg(long)]
        allowlist: Option<String>,
        /// Optional blocklist of disallowed secret patterns.
        /// Format: comma-separated patterns (`*`, `namespace/*`, or exact id).
        #[arg(long)]
        blocklist: Option<String>,
    },
    /// Manages pending request workflows (list/approve/deny).
    #[command(visible_alias = "req", after_help = REQUESTS_COMMAND_AFTER_HELP)]
    Requests {
        /// Request operation.
        #[command(subcommand)]
        command: RequestsCommand,
    },
    /// Legacy shortcut: approves a pending request by id.
    #[command(hide = true, after_help = APPROVE_COMMAND_AFTER_HELP)]
    Approve {
        /// Request UUID.
        #[arg(help = REQUEST_ID_ARG_HELP)]
        request_id: String,
    },
    /// Legacy shortcut: denies a pending request by id.
    #[command(hide = true, after_help = DENY_COMMAND_AFTER_HELP)]
    Deny {
        /// Request UUID.
        #[arg(help = REQUEST_ID_ARG_HELP)]
        request_id: String,
    },
    /// Lists secret entries (`requests list` shows pending requests).
    #[command(visible_alias = "ls", after_help = LIST_COMMAND_AFTER_HELP)]
    List {
        /// Show only pending request entries.
        #[arg(long)]
        pending: bool,
    },
    /// Views audit events.
    Audit {
        /// Show only the latest N events.
        #[arg(long, default_value_t = 50)]
        limit: usize,
    },
    /// Verifies registry and expiry state.
    Verify,
    /// Runs local sidecar daemon.
    Daemon {
        /// TCP bind address for daemon mode.
        #[arg(long)]
        bind: Option<String>,
        /// Perform strict startup checks and exit.
        #[arg(long)]
        check: bool,
        /// Maximum handled requests before exiting. Intended for tests.
        #[arg(long, hide = true, default_value_t = 0)]
        max_requests: usize,
    },
    /// Manages encrypted vaults.
    Vault {
        /// Vault operation.
        #[command(subcommand)]
        command: VaultCommand,
    },
    /// Validates loaded config state.
    Config {
        /// Config operation.
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Shows access visibility for configured private paths.
    Access {
        /// Access operation.
        #[command(subcommand)]
        command: AccessCommand,
    },
    /// Manages per-agent GPG keys used for human secret workflows.
    #[command(after_help = GPG_COMMAND_AFTER_HELP)]
    Gpg {
        /// GPG operation.
        #[command(subcommand)]
        command: GpgCommand,
    },
    /// Internal helper to print one secret for gocryptfs -extpass.
    #[command(hide = true)]
    ExtpassGet {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
    },
}

/// Vault owner argument.
#[derive(Debug, Clone, ValueEnum)]
pub enum VaultOwnerArg {
    /// Agent-controlled vault.
    Agent,
    /// Human-approved vault.
    Human,
}

impl From<VaultOwnerArg> for Owner {
    fn from(value: VaultOwnerArg) -> Self {
        match value {
            VaultOwnerArg::Agent => Owner::Agent,
            VaultOwnerArg::Human => Owner::Human,
        }
    }
}

/// Vault runtime mode argument.
#[derive(Debug, Clone, ValueEnum)]
pub enum VaultModeArg {
    /// Opportunistic vault mode.
    Auto,
    /// Vault dependencies are mandatory.
    Required,
    /// Vault commands are blocked.
    Disabled,
}

impl From<VaultModeArg> for VaultMode {
    fn from(value: VaultModeArg) -> Self {
        match value {
            VaultModeArg::Auto => VaultMode::Auto,
            VaultModeArg::Required => VaultMode::Required,
            VaultModeArg::Disabled => VaultMode::Disabled,
        }
    }
}

/// Supported bootstrap profiles.
#[derive(Debug, Clone, ValueEnum)]
pub enum BootstrapProfileArg {
    /// Opinionated fresh setup for OpenClaw runtimes.
    Openclaw,
}

/// Supported OpenClaw subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum OpenclawCommand {
    /// Bootstraps a fresh OpenClaw runtime layout.
    #[command(after_help = OPENCLAW_BOOTSTRAP_COMMAND_AFTER_HELP)]
    Bootstrap {
        /// Comma-separated agent identifiers.
        #[arg(long, value_name = "AGENT_LIST")]
        agents: String,
        /// Default agent identifier for generated config.
        #[arg(long)]
        default_agent: Option<String>,
        /// Replace existing bootstrap files and identities.
        #[arg(long)]
        force: bool,
    },
    /// Manages the OpenClaw bridge daemon.
    Bridge {
        /// Bridge operation.
        #[command(subcommand)]
        command: OpenclawBridgeCommand,
    },
}

/// Supported OpenClaw bridge subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum OpenclawBridgeCommand {
    /// Installs bridge support files.
    Install,
    /// Starts the bridge service.
    Start,
    /// Stops the bridge service.
    Stop,
    /// Shows bridge service status.
    Status,
    /// Runs the bridge in the foreground.
    Run,
}

/// Supported doctor subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum DoctorCommand {
    /// Checks OpenClaw bootstrap and bridge state.
    #[command(after_help = OPENCLAW_DOCTOR_COMMAND_AFTER_HELP)]
    Openclaw,
}

/// Supported integration subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum IntegrationCommand {
    /// Lists inferred refs for one integration.
    ListRefs,
    /// Checks whether one integration secret resolves.
    Test {
        /// Secret slot to check.
        slot: String,
        /// Optional profile override. Omit to use `default`.
        #[arg(long)]
        profile: Option<String>,
    },
    /// Rotates one integration secret by writing a new value.
    Rotate {
        /// Secret slot to rotate.
        slot: String,
        /// Optional profile override. Omit to use `default`.
        #[arg(long)]
        profile: Option<String>,
        /// Generate a random secret value instead of reading stdin or `--value`.
        #[arg(long)]
        generate: bool,
        /// Inline secret value.
        #[arg(long)]
        value: Option<String>,
        /// Read the secret value from stdin.
        #[arg(long)]
        stdin: bool,
        /// TTL in days, or `never`. Omit to use the configured default.
        #[arg(long)]
        ttl: Option<String>,
    },
}

/// Supported vault subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum VaultCommand {
    /// Shows help for vault workflows.
    Help {
        /// Optional nested topic (for example: `mount`).
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Initializes a new vault.
    Init {
        /// Vault name.
        name: String,
        /// Vault owner.
        #[arg(long, value_enum)]
        owner: VaultOwnerArg,
    },
    /// Mounts a vault.
    Mount {
        /// Vault name.
        name: String,
        /// Mount session TTL.
        #[arg(long)]
        ttl: Option<String>,
        /// Optional mountpoint override.
        #[arg(long)]
        mountpoint: Option<PathBuf>,
        /// Agent identity for this mount session.
        #[arg(long)]
        agent: Option<String>,
    },
    /// Mounts a vault, runs a command, and unmounts automatically.
    Exec {
        /// Vault name.
        name: String,
        /// Mount session TTL.
        #[arg(long)]
        ttl: Option<String>,
        /// Optional mountpoint override.
        #[arg(long)]
        mountpoint: Option<PathBuf>,
        /// Agent identity for this exec session.
        #[arg(long)]
        agent: Option<String>,
        /// Command and arguments to execute after mount.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        command: Vec<String>,
    },
    /// Unmounts a vault.
    Unmount {
        /// Vault name.
        name: String,
        /// Agent identity associated with unmount audit event.
        #[arg(long)]
        agent: Option<String>,
    },
    /// Shows vault mount status.
    Status,
    /// Lists configured vaults.
    List,
    /// Generates a trusted-agent handoff prompt for one file.
    AskFile {
        /// Vault name.
        name: String,
        /// File path relative to vault root.
        #[arg(long)]
        file: String,
        /// Agent that is requesting the file.
        #[arg(long)]
        requester: Option<String>,
        /// Trusted agent expected to have mount access.
        #[arg(long)]
        trusted_agent: String,
        /// Optional reason shown in the prompt.
        #[arg(long)]
        reason: Option<String>,
    },
}

/// Supported generic execution subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum ExecCommand {
    /// Runs a command with environment-variable delivery.
    #[command(after_help = EXEC_ENV_COMMAND_AFTER_HELP)]
    Env {
        /// Secret ref bindings for environment injection.
        /// Format: `NAME=gloves://namespace/secret-path`. Repeat `--env` for each binding.
        #[arg(long = "env", value_name = "BINDING", action = clap::ArgAction::Append)]
        env: Vec<String>,
        /// Command and arguments to execute.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        command: Vec<String>,
    },
}

/// Supported config subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum SecretsCommand {
    /// Shows help for secret workflows.
    Help {
        /// Optional nested topic (for example: `set`).
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Sets an agent secret.
    #[command(after_help = SET_COMMAND_AFTER_HELP)]
    Set {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
        /// Generate random value.
        #[arg(long)]
        generate: bool,
        /// Inline secret value (less secure than stdin).
        #[arg(long)]
        value: Option<String>,
        /// Read secret value from stdin (trims trailing CR/LF).
        #[arg(long)]
        stdin: bool,
        /// TTL in days, or `never`. Omit to use the configured default.
        #[arg(long)]
        ttl: Option<String>,
    },
    /// Gets a secret value.
    #[command(after_help = GET_COMMAND_AFTER_HELP)]
    Get {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
        /// Pipe secret bytes to an approved command.
        #[arg(long, conflicts_with = "pipe_to_args")]
        pipe_to: Option<String>,
        /// Execute an approved command template with `{secret}` interpolation.
        #[arg(long, conflicts_with = "pipe_to")]
        pipe_to_args: Option<String>,
    },
    /// Grants an existing secret to another agent.
    #[command(after_help = GRANT_COMMAND_AFTER_HELP)]
    Grant {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
        /// Agent id to grant access to.
        #[arg(long)]
        to: String,
    },
    /// Revokes a secret.
    #[command(after_help = REVOKE_COMMAND_AFTER_HELP)]
    Revoke {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
    },
    /// Shows request status by secret name.
    #[command(after_help = STATUS_COMMAND_AFTER_HELP)]
    Status {
        /// Secret name.
        #[arg(help = SECRET_NAME_ARG_HELP)]
        name: String,
    },
}

/// Supported config subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum ConfigCommand {
    /// Shows help for config workflows.
    Help {
        /// Optional nested topic.
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Validates the effective config and runtime policy checks.
    Validate,
}

/// Supported access subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum AccessCommand {
    /// Shows help for access workflows.
    Help {
        /// Optional nested topic.
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Shows one agent's configured private path visibility.
    Paths {
        /// Agent identifier.
        #[arg(long)]
        agent: String,
    },
}

/// Supported request-group subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum RequestsCommand {
    /// Shows help for request workflows.
    Help {
        /// Optional nested topic (for example: `approve`).
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Lists only pending request entries.
    #[command(
        after_help = "Examples:\n  gloves requests list\n  gloves req list\n\nSee also:\n  gloves list  (shows secrets and pending requests)\n"
    )]
    List,
    /// Approves a pending request by id.
    #[command(after_help = APPROVE_COMMAND_AFTER_HELP)]
    Approve {
        /// Request UUID.
        #[arg(help = REQUEST_ID_ARG_HELP)]
        request_id: String,
    },
    /// Denies a pending request by id.
    #[command(after_help = DENY_COMMAND_AFTER_HELP)]
    Deny {
        /// Request UUID.
        #[arg(help = REQUEST_ID_ARG_HELP)]
        request_id: String,
    },
}

/// Error format argument.
#[derive(Debug, Clone, Copy, ValueEnum, Eq, PartialEq)]
pub enum ErrorFormatArg {
    /// Human-readable text diagnostics.
    Text,
    /// Machine-readable JSON diagnostics.
    Json,
}

/// Output format for top-level `get`.
#[derive(Debug, Clone, Copy, ValueEnum, Eq, PartialEq)]
pub enum SecretReadFormatArg {
    /// Emit only the secret value bytes.
    Raw,
    /// Emit structured JSON with metadata.
    Json,
}

/// Output format for top-level `show`.
#[derive(Debug, Clone, Copy, ValueEnum, Eq, PartialEq)]
pub enum SecretShowFormatArg {
    /// Emit text lines.
    Text,
    /// Emit structured JSON.
    Json,
}

/// Supported GPG subcommands.
#[derive(Debug, Subcommand)]
#[command(disable_help_subcommand = true)]
pub enum GpgCommand {
    /// Shows help for GPG workflows.
    Help {
        /// Optional nested topic.
        #[arg(value_name = "TOPIC", num_args = 0..)]
        topic: Vec<String>,
    },
    /// Creates a GPG key for the selected agent if one does not exist.
    #[command(after_help = GPG_CREATE_COMMAND_AFTER_HELP)]
    Create,
    /// Prints the selected agent GPG key fingerprint.
    #[command(after_help = GPG_FINGERPRINT_COMMAND_AFTER_HELP)]
    Fingerprint,
}

/// Runs CLI and returns process exit code.
pub fn run(cli: Cli) -> Result<i32> {
    commands::run(cli)
}

/// Prints version/runtime defaults in text or JSON and returns process exit code.
pub fn emit_version_output(json: bool) -> Result<i32> {
    commands::emit_version_output(json)
}

#[allow(dead_code)]
fn ttl_seconds(ttl: Duration) -> i64 {
    ttl.num_seconds().max(DEFAULT_TTL_SECONDS)
}

#[cfg(test)]
mod unit_tests {
    use super::{
        runtime::{
            load_or_create_identity_for_agent, load_or_create_signing_key_for_agent,
            parse_secret_ttl_argument, validate_ttl_days, SecretTtl,
        },
        secret_input::{parse_duration_value, resolve_secret_input},
        ttl_seconds, BootstrapProfileArg, Cli, Command, ErrorFormatArg, ExecCommand,
        RequestsCommand, SecretReadFormatArg, SecretShowFormatArg, SecretsCommand,
    };
    use crate::error::GlovesError;
    use crate::paths::SecretsPaths;
    use crate::types::AgentId;
    use chrono::Duration;
    use clap::{error::ErrorKind, CommandFactory, Parser};
    use std::path::PathBuf;

    #[test]
    fn resolve_secret_input_generate_ok() {
        let bytes = resolve_secret_input(true, None, false).unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn resolve_secret_input_generate_conflict() {
        assert!(matches!(
            resolve_secret_input(true, Some("abc".to_owned()), false),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn resolve_secret_input_value_ok() {
        let bytes = resolve_secret_input(false, Some("abc".to_owned()), false).unwrap();
        assert_eq!(bytes, b"abc");
    }

    #[test]
    fn resolve_secret_input_empty_value_rejected() {
        assert!(matches!(
            resolve_secret_input(false, Some(String::new()), false),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn resolve_secret_input_requires_source() {
        assert!(matches!(
            resolve_secret_input(false, None, false),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn ttl_seconds_enforces_default_floor() {
        let below_floor = ttl_seconds(Duration::seconds(1));
        assert!(below_floor >= 86_400);
    }

    #[test]
    fn validate_ttl_days_rejects_non_positive_values() {
        assert!(matches!(
            validate_ttl_days(0, "--ttl"),
            Err(GlovesError::InvalidInput(_))
        ));
        assert!(matches!(
            validate_ttl_days(-1, "--ttl"),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn validate_ttl_days_accepts_positive_value() {
        let ttl_days = validate_ttl_days(7, "--ttl").unwrap();
        assert_eq!(ttl_days, 7);
    }

    #[test]
    fn parse_secret_ttl_argument_accepts_never() {
        let ttl = parse_secret_ttl_argument(Some("never"), 30, "--ttl").unwrap();
        assert_eq!(ttl, SecretTtl::Never);
    }

    #[test]
    fn parse_secret_ttl_argument_uses_default_days_when_omitted() {
        let ttl = parse_secret_ttl_argument(None, 30, "--ttl").unwrap();
        assert_eq!(ttl, SecretTtl::Days(30));
    }

    #[test]
    fn parse_duration_value_accepts_hours() {
        let duration = parse_duration_value("2h", "--ttl").unwrap();
        assert_eq!(duration, Duration::hours(2));
    }

    #[test]
    fn parse_duration_value_rejects_invalid_units() {
        assert!(matches!(
            parse_duration_value("2w", "--ttl"),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn parse_duration_value_rejects_non_positive_values() {
        assert!(matches!(
            parse_duration_value("0h", "--ttl"),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn load_or_create_identity_for_agent_rejects_invalid_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp_dir.path().join("agents").join("default-agent")).unwrap();
        std::fs::write(
            temp_dir
                .path()
                .join("agents")
                .join("default-agent")
                .join("age.key"),
            "invalid",
        )
        .unwrap();
        let paths = SecretsPaths::new(temp_dir.path());
        let agent_id = AgentId::new("default-agent").unwrap();
        assert!(load_or_create_identity_for_agent(&paths, &agent_id).is_err());
    }

    #[test]
    fn load_or_create_signing_key_for_agent_rejects_invalid_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp_dir.path().join("agents").join("default-agent")).unwrap();
        std::fs::write(
            temp_dir
                .path()
                .join("agents")
                .join("default-agent")
                .join("signing.key"),
            [1_u8; 8],
        )
        .unwrap();
        let paths = SecretsPaths::new(temp_dir.path());
        let agent_id = AgentId::new("default-agent").unwrap();
        assert!(matches!(
            load_or_create_signing_key_for_agent(&paths, &agent_id),
            Err(GlovesError::InvalidInput(_))
        ));
    }

    #[test]
    fn load_or_create_identity_for_agent_uses_agent_specific_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let paths = SecretsPaths::new(temp_dir.path());
        let agent_id = AgentId::new("agent-main").unwrap();
        let identity_file = load_or_create_identity_for_agent(&paths, &agent_id).unwrap();

        assert!(identity_file.ends_with("agents/agent-main/age.key"));
        assert!(identity_file.exists());
        assert!(!paths.default_identity_file().exists());
    }

    #[test]
    fn load_or_create_signing_key_for_agent_uses_agent_specific_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let paths = SecretsPaths::new(temp_dir.path());
        let agent_id = AgentId::new("agent-main").unwrap();
        let key = load_or_create_signing_key_for_agent(&paths, &agent_id).unwrap();

        assert!(temp_dir
            .path()
            .join("agents")
            .join("agent-main")
            .join("signing.key")
            .exists());
        assert!(!paths.default_signing_key_file().exists());
        assert_eq!(key.to_bytes().len(), 32);
    }

    #[test]
    fn cli_help_includes_examples_and_help_hint() {
        let mut command = Cli::command();
        let help = command.render_long_help().to_string();
        assert!(help.contains("Examples:"));
        assert!(help.contains("gloves --version"));
        assert!(help.contains("gloves --json --version"));
        assert!(help.contains("gloves help [topic...]"));
        assert!(help.contains("--error-format"));
    }

    #[test]
    fn cli_version_flag_is_available() {
        let error = Cli::try_parse_from(["gloves", "--version"]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::DisplayVersion);
    }

    #[test]
    fn cli_short_version_flag_is_available() {
        let error = Cli::try_parse_from(["gloves", "-V"]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::DisplayVersion);
    }

    #[test]
    fn cli_approve_help_includes_request_lookup_example() {
        let cli = Cli::try_parse_from(["gloves", "help", "approve"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Help { topic } if topic == vec!["approve".to_owned()]
        ));
    }

    #[test]
    fn cli_set_help_includes_input_examples() {
        let cli = Cli::try_parse_from(["gloves", "help", "secrets", "set"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Help { topic } if topic == vec!["secrets".to_owned(), "set".to_owned()]
        ));
    }

    #[test]
    fn cli_secrets_set_parses_to_nested_command() {
        let cli = Cli::try_parse_from([
            "gloves",
            "secrets",
            "set",
            "service/token",
            "--generate",
            "--ttl",
            "1",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Secrets {
                command: SecretsCommand::Set { name, generate, ttl, .. }
            } if name == "service/token" && generate && ttl.as_deref() == Some("1")
        ));
    }

    #[test]
    fn cli_top_level_set_parses_namespaced_path() {
        let cli =
            Cli::try_parse_from(["gloves", "set", "agents/devy/api-keys/anthropic", "--stdin"])
                .unwrap();
        assert!(matches!(
            cli.command,
            Command::Set { path, stdin, value }
                if path == "agents/devy/api-keys/anthropic" && stdin && value.is_none()
        ));
    }

    #[test]
    fn cli_top_level_get_accepts_format_flag() {
        let cli = Cli::try_parse_from([
            "gloves",
            "get",
            "agents/devy/api-keys/anthropic",
            "--format",
            "json",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Get { path, format }
                if path == "agents/devy/api-keys/anthropic"
                    && format == SecretReadFormatArg::Json
        ));
    }

    #[test]
    fn cli_run_accepts_repeated_env_secret_ref_bindings() {
        let cli = Cli::try_parse_from([
            "gloves",
            "run",
            "--env",
            "API_KEY=gloves://shared/github-token",
            "--env",
            "DB_URL=gloves://shared/db-url",
            "--",
            "sh",
            "-c",
            "env",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Run {
                env,
                command,
            } if env
                == vec![
                    "API_KEY=gloves://shared/github-token".to_owned(),
                    "DB_URL=gloves://shared/db-url".to_owned()
                ] && command == vec![
                    "sh".to_owned(),
                    "-c".to_owned(),
                    "env".to_owned()
                ]
        ));
    }

    #[test]
    fn cli_bootstrap_accepts_openclaw_profile_arguments() {
        let cli = Cli::try_parse_from([
            "gloves",
            "bootstrap",
            "--profile",
            "openclaw",
            "--root",
            "~/.openclaw/secrets",
            "--config",
            "~/.openclaw/.gloves.toml",
            "--agents",
            "main,relationships,coder",
            "--default-agent",
            "main",
            "--force",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Bootstrap {
                profile: BootstrapProfileArg::Openclaw,
                agents,
                default_agent,
                force,
            } if agents == "main,relationships,coder"
                && default_agent == Some("main".to_owned())
                && force
        ));
        assert_eq!(cli.root, Some(PathBuf::from("~/.openclaw/secrets")));
        assert_eq!(cli.config, Some(PathBuf::from("~/.openclaw/.gloves.toml")));
    }

    #[test]
    fn cli_exec_env_accepts_repeated_env_secret_ref_bindings() {
        let cli = Cli::try_parse_from([
            "gloves",
            "exec",
            "env",
            "--env",
            "API_KEY=gloves://shared/github-token",
            "--",
            "sh",
            "-c",
            "env",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Exec {
                command: ExecCommand::Env { env, command }
            } if env == vec!["API_KEY=gloves://shared/github-token".to_owned()]
                && command == vec!["sh".to_owned(), "-c".to_owned(), "env".to_owned()]
        ));
    }

    #[test]
    fn cli_show_accepts_json_format_flag() {
        let cli = Cli::try_parse_from([
            "gloves",
            "show",
            "agents/devy/api-keys/anthropic",
            "--format",
            "json",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Show { path, format, .. }
                if path == "agents/devy/api-keys/anthropic"
                    && format == SecretShowFormatArg::Json
        ));
    }

    #[test]
    fn cli_set_identity_requires_agent() {
        let cli = Cli::try_parse_from(["gloves", "set-identity", "--agent", "devy"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::SetIdentity { agent, force, .. } if agent == "devy" && !force
        ));
    }

    #[test]
    fn cli_requests_alias_parses_to_requests_command() {
        let cli = Cli::try_parse_from(["gloves", "req", "list"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Requests {
                command: RequestsCommand::List
            }
        ));
    }

    #[test]
    fn cli_list_alias_parses_to_list_command() {
        let cli = Cli::try_parse_from(["gloves", "ls"]).unwrap();
        assert!(matches!(cli.command, Command::List { pending: false }));
    }

    #[test]
    fn cli_grant_parses_to_secrets_grant_command() {
        let cli = Cli::try_parse_from([
            "gloves",
            "secrets",
            "grant",
            "service/token",
            "--to",
            "agent-b",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Secrets {
                command: SecretsCommand::Grant { name, to }
            } if name == "service/token" && to == "agent-b"
        ));
    }

    #[test]
    fn cli_secrets_help_subcommand_parses_nested_topic() {
        let cli = Cli::try_parse_from(["gloves", "secrets", "help", "get"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Secrets {
                command: SecretsCommand::Help { topic }
            } if topic == vec!["get".to_owned()]
        ));
    }

    #[test]
    fn cli_version_subcommand_is_not_supported() {
        let error = Cli::try_parse_from(["gloves", "version"]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidSubcommand);
    }

    #[test]
    fn cli_explain_help_mentions_error_codes() {
        let cli = Cli::try_parse_from(["gloves", "help", "explain"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Help { topic } if topic == vec!["explain".to_owned()]
        ));
    }

    #[test]
    fn cli_help_parses_recursive_topic_path() {
        let cli = Cli::try_parse_from(["gloves", "help", "requests", "approve"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Help { topic }
                if topic == vec!["requests".to_owned(), "approve".to_owned()]
        ));
    }

    #[test]
    fn cli_requests_help_subcommand_parses_nested_topic() {
        let cli = Cli::try_parse_from(["gloves", "requests", "help", "approve"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Requests {
                command: RequestsCommand::Help { topic }
            } if topic == vec!["approve".to_owned()]
        ));
    }

    #[test]
    fn cli_json_flag_defaults_to_false() {
        let cli = Cli::try_parse_from(["gloves", "init"]).unwrap();
        assert!(!cli.json);
    }

    #[test]
    fn cli_json_flag_alias_is_available() {
        let cli = Cli::try_parse_from(["gloves", "--json", "init"]).unwrap();
        assert!(cli.json);
    }

    #[test]
    fn cli_error_format_defaults_to_text() {
        let cli = Cli::try_parse_from(["gloves", "init"]).unwrap();
        assert_eq!(cli.error_format, ErrorFormatArg::Text);
    }

    #[test]
    fn cli_error_format_accepts_json() {
        let cli = Cli::try_parse_from(["gloves", "--error-format", "json", "init"]).unwrap();
        assert_eq!(cli.error_format, ErrorFormatArg::Json);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn cli_tui_accepts_trailing_bootstrap_args() {
        let cli = Cli::try_parse_from([
            "gloves",
            "tui",
            "--config",
            "/etc/gloves/prod.gloves.toml",
            "audit",
            "--limit",
            "100",
        ])
        .unwrap();
        assert_eq!(
            cli.config,
            Some(PathBuf::from("/etc/gloves/prod.gloves.toml"))
        );
        assert!(matches!(
            cli.command,
            Command::Tui { args }
                if args
                    == vec![
                        "audit".to_owned(),
                        "--limit".to_owned(),
                        "100".to_owned()
                    ]
        ));
    }
}