cli-engine 0.9.3

Rust CLI framework for consistent command modules
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
use std::{collections::BTreeMap, future::Future, pin::Pin, sync::Arc};

use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command};
use schemars::JsonSchema;
use serde_json::{Number, Value};
use tokio::sync::mpsc;

use crate::{
    AuthRequirement, CommandMeta, Credential, CredentialResolver, FeatureFlag, Middleware,
    OutputSchema, Result, SchemaInfo, Stage, Tier,
    middleware::ValueMap,
    output::{NextAction, TableColumn},
};

/// Sender half for streaming command output.
///
/// Streaming handlers call [`StreamSender::send`] for each progress event.
/// The engine drains the channel and writes each event as an NDJSON line.
#[derive(Clone, Debug)]
pub struct StreamSender(pub(crate) mpsc::Sender<Value>);

impl StreamSender {
    /// Sends one event. Silently drops the event if the receiver is gone.
    pub async fn send(&self, event: Value) {
        drop(self.0.send(event).await);
    }
}

/// Boxed future returned by runtime command handlers.
pub type CommandFuture = Pin<Box<dyn Future<Output = Result<CommandResult>> + Send>>;
/// Shared command handler used by [`RuntimeCommandSpec`].
pub type CommandHandler = Arc<dyn Fn(CommandContext) -> CommandFuture + Send + Sync>;

/// Boxed future returned by streaming command handlers.
pub type StreamingCommandFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
/// Shared streaming handler: receives context and an event sender; returns when the stream ends.
pub type StreamingCommandHandler =
    Arc<dyn Fn(CommandContext, StreamSender) -> StreamingCommandFuture + Send + Sync>;

/// Data returned by a command handler.
///
/// Command handlers should return renderable data and keep output metadata on
/// [`CommandSpec`]. The metadata field is reserved for future command-result
/// extensions that are not known when the command is registered.
///
/// Construct with [`CommandResult::new`], then chain `with_*` methods —
/// never as a struct literal. `#[non_exhaustive]` enforces this so the engine
/// can add fields without a breaking release.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CommandResult {
    /// JSON data rendered by the configured output formatter.
    pub data: Value,
    /// Optional command-result extension metadata.
    pub metadata: CommandResultMetadata,
}

impl CommandResult {
    /// Creates a command result from renderable JSON data.
    #[must_use]
    pub fn new(data: Value) -> Self {
        Self {
            data,
            metadata: CommandResultMetadata::default(),
        }
    }

    /// Attaches suggested follow-up actions to this result.
    #[must_use]
    pub fn with_next_actions(mut self, actions: Vec<NextAction>) -> Self {
        self.metadata.next_actions = actions;
        self
    }

    /// Marks this result as a dry-run preview outcome.
    ///
    /// Call only when the handler actually skipped its mutating step because
    /// [`CommandContext::dry_run`] was `true`. This requires the command to
    /// have opted in via [`CommandSpec::handles_dry_run`] — otherwise
    /// middleware never invokes the handler under `--dry-run` in the first
    /// place. Middleware tags the audit/activity outcome as `dry-run` instead
    /// of `ok` and marks the rendered envelope accordingly.
    #[must_use]
    pub fn with_dry_run(mut self) -> Self {
        self.metadata.dry_run = true;
        self
    }
}

impl From<Value> for CommandResult {
    fn from(data: Value) -> Self {
        Self::new(data)
    }
}

/// Optional metadata a command can attach to its result.
#[non_exhaustive]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CommandResultMetadata {
    /// Suggested follow-up actions for the caller.
    pub next_actions: Vec<NextAction>,
    /// Set by [`CommandResult::with_dry_run`] when a
    /// [`handles_dry_run`](CommandSpec::handles_dry_run) handler skipped its
    /// mutating step. Middleware tags the audit/activity outcome and envelope
    /// as `dry-run` instead of `ok` when this is `true`.
    pub dry_run: bool,
}

/// Runtime context passed to advanced command handlers.
///
/// Most commands can use [`RuntimeCommandSpec::new`] and receive just the
/// credential and effective args. Use this context when a command needs the
/// colon path, user-supplied args, or a snapshot of middleware state.
///
/// This struct is constructed by the framework during command dispatch.
/// Consumer code receives it in handler closures and should not construct it
/// directly.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct CommandContext {
    /// Lazy credential resolver.
    pub credential: CredentialResolver,
    /// Effective arguments, including defaults and framework-injected values.
    pub args: ValueMap,
    /// Arguments explicitly supplied by the user.
    pub user_args: ValueMap,
    /// Colon-separated command path such as `project:list`.
    pub command_path: String,
    /// Middleware snapshot for this invocation.
    pub middleware: Middleware,
    /// Raw `clap` matches for typed argument deserialization via derive.
    pub raw_matches: Arc<ArgMatches>,
}

impl CommandContext {
    /// Returns the per-application config file as loaded at startup.
    ///
    /// Read a consumer-owned section with
    /// [`ConfigFile::section`](crate::config::ConfigFile::section), for example
    /// `ctx.config().section::<DeployConfig>("deploy")?`. Engine-reserved
    /// settings are available via
    /// [`ConfigFile::engine`](crate::config::ConfigFile::engine).
    ///
    /// **Snapshot semantics**: this is the config loaded once when
    /// [`crate::cli::Cli::new`] was called. Changes made by `config set` during the same process
    /// invocation (e.g. from a previous `Cli::run`) are not reflected here;
    /// restart the CLI (a new `Cli::new`) to pick them up. For a one-shot CLI
    /// process this is always the current on-disk state.
    #[must_use]
    pub fn config(&self) -> &crate::config::ConfigFile {
        &self.middleware.config
    }

    /// Returns whether `--dry-run` was passed for this invocation.
    ///
    /// Only meaningful for commands that opted in via
    /// [`CommandSpec::handles_dry_run`] — other mutating commands never reach
    /// their handler under `--dry-run` at all, so there's nothing to branch
    /// on. An opted-in handler should run its real validation unconditionally
    /// and use this only to skip the actual mutating I/O, returning a preview
    /// result tagged with [`CommandResult::with_dry_run`].
    #[must_use]
    pub fn dry_run(&self) -> bool {
        self.middleware.dry_run
    }

    /// Returns the resolved interactivity mode for this invocation.
    ///
    /// Use this to decide whether to prompt for missing inputs, show progress
    /// spinners, or offer interactive choices. When `false`, the command should
    /// fail with a descriptive error if required inputs are missing.
    #[must_use]
    pub fn is_interactive(&self) -> bool {
        self.middleware.interactive
    }

    /// Returns the resolved [`InteractivityMode`](crate::InteractivityMode).
    ///
    /// Equivalent to [`is_interactive`](Self::is_interactive) but returns the
    /// enum for pattern matching.
    #[must_use]
    pub fn interactivity_mode(&self) -> crate::InteractivityMode {
        self.middleware.interactive.into()
    }

    /// Resolves the active environment's merged TOML table for this
    /// invocation, as an [`EnvSource`](crate::env_config::EnvSource).
    ///
    /// The active environment name is `self.middleware.env`, seeded at startup
    /// from the persisted active environment or configured default and
    /// overridden per invocation by the global `--env` flag. Resolution merges
    /// the compiled-in table and the `environments.toml` file layer (file
    /// wins). Use this for generic introspection (see the built-in `env info`
    /// command); for a typed section with the app-scoped environment-variable
    /// override tier applied, use
    /// [`environment_config`](Self::environment_config) instead.
    ///
    /// # Blocking
    ///
    /// When the `environments.toml` file layer is enabled, this performs
    /// synchronous filesystem I/O via
    /// [`Environments::source`](crate::environments::Environments::source).
    /// Call it once per invocation and reuse the result rather than calling it
    /// repeatedly inside an async handler on a latency-sensitive path.
    ///
    /// # Errors
    ///
    /// Returns an error if no environment system was registered via
    /// [`CliConfig::with_environments`](crate::CliConfig::with_environments) or
    /// if the active name does not resolve to a known environment.
    pub fn environment(&self) -> Result<crate::env_config::EnvSource> {
        let environments = self.middleware.environments.as_ref().ok_or_else(|| {
            crate::error::CliCoreError::message("no environment system configured")
        })?;
        environments.source(&self.middleware.env)
    }

    /// Resolves the active environment into a typed
    /// [`EnvConfig`](crate::env_config::EnvConfig) section, with the
    /// app-scoped environment-variable override tier applied (see
    /// [`Environments::resolve`](crate::environments::Environments::resolve)).
    ///
    /// # Blocking
    ///
    /// See [`environment`](Self::environment).
    ///
    /// # Errors
    ///
    /// Returns an error under the same conditions as
    /// [`environment`](Self::environment), or when a field's present value
    /// fails to convert to its type, or a required field has no value in any
    /// source and no default.
    pub fn environment_config<T: crate::env_config::EnvConfig>(
        &self,
    ) -> std::result::Result<T, crate::env_config::EnvConfigError> {
        let environments = self.middleware.environments.as_ref().ok_or_else(|| {
            crate::error::CliCoreError::message("no environment system configured")
        })?;
        environments.resolve(&self.middleware.env)
    }

    /// Deserializes the raw argument matches into a typed args struct.
    ///
    /// Use this with `#[derive(clap::Args)]` structs to get type-safe access
    /// to command arguments instead of working with the `ValueMap` directly.
    ///
    /// # Errors
    ///
    /// Returns an error if the matches cannot be deserialized into `T`.
    pub fn typed_args<T: clap::FromArgMatches>(&self) -> Result<T> {
        T::from_arg_matches(self.raw_matches.as_ref())
            .map_err(|e| crate::CliCoreError::Message(format!("argument parse error: {e}")))
    }

    /// Resolves the credential for this command, triggering the auth flow on
    /// first use and memoizing the result.
    ///
    /// Convenience wrapper over [`self.credential.resolve()`](CredentialResolver::resolve).
    ///
    /// # Errors
    ///
    /// Returns an error when the command is marked `no_auth`, or when the auth
    /// provider fails to produce a credential.
    pub async fn credential(&self) -> Result<Credential> {
        self.credential.resolve().await
    }

    /// Resolves the credential when one is available, returning `Ok(None)` for
    /// no-auth commands.
    ///
    /// Convenience wrapper over [`self.credential.try_resolve()`](CredentialResolver::try_resolve).
    ///
    /// # Errors
    ///
    /// Propagates the auth provider error when resolution is attempted and fails.
    pub async fn try_credential(&self) -> Result<Option<Credential>> {
        self.credential.try_resolve().await
    }

    /// Resolves a credential that additionally covers `extra` scopes, on top of
    /// the command's declared scopes.
    ///
    /// Use this when the required scopes are only known at runtime (for example
    /// a generic API caller that derives scopes from the target endpoint). A
    /// scope-aware auth provider re-authenticates when the cached token does not
    /// already cover the requested set.
    ///
    /// Convenience wrapper over
    /// [`self.credential.resolve_with_scopes()`](CredentialResolver::resolve_with_scopes).
    ///
    /// If the handler also issues HTTP requests through the transport bearer
    /// injector, call this **before** the first request: the injector resolves
    /// and caches a scope-unaware token, so stepping up afterwards would not
    /// affect requests it already authorized. See
    /// [`CredentialResolver::resolve_with_scopes`] for the full ordering note.
    ///
    /// # Errors
    ///
    /// Returns an error when the command is marked `no_auth`, or when the auth
    /// provider fails to produce a credential.
    pub async fn credential_with_scopes(&self, extra: &[String]) -> Result<Credential> {
        self.credential.resolve_with_scopes(extra).await
    }
}

/// Declarative leaf command metadata and parser arguments.
///
/// `CommandSpec` intentionally keeps command metadata next to the command's
/// handler. This is the primary copy/paste surface for teams adding commands.
///
/// Construct with [`CommandSpec::new`] or [`CommandSpec::from_args`], then
/// configure with the `with_*` builder methods — never as a struct literal.
/// `#[non_exhaustive]` enforces this so the engine can add fields (as it did
/// for [`arg_groups`](CommandSpec::arg_groups)) without a breaking release.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CommandSpec {
    /// Leaf command name.
    pub name: String,
    /// One-line command description.
    pub short: String,
    /// Optional long help text.
    pub long: Option<String>,
    /// Alternate command names accepted by the parser.
    pub aliases: Vec<String>,
    /// Whether the command runs but is hidden from help, tree, and search.
    pub hidden: bool,
    /// Backend/system id used in output metadata and generic error envelopes.
    pub system: Option<String>,
    /// Default comma-separated field projection.
    pub default_fields: Option<String>,
    /// Authentication requirement enforced by the engine for this command.
    ///
    /// Defaults to [`AuthRequirement::Required`] (fail-closed). Use
    /// [`auth_optional`](CommandSpec::auth_optional) for commands that should run
    /// logged out, or [`no_auth`](CommandSpec::no_auth) for commands that never
    /// authenticate.
    pub auth: AuthRequirement,
    /// Auth provider name for this command.
    pub auth_provider: Option<String>,
    /// Risk tier used by authentication, authorization, and dry-run.
    pub tier: Option<Tier>,
    /// Explicit dry-run prompt marker for commands without a tier.
    pub mutates: bool,
    /// Opts this command into handler-driven `--dry-run`.
    ///
    /// Set with [`handles_dry_run`](CommandSpec::handles_dry_run). When
    /// `true`, the engine skips its generic `--dry-run` short-circuit for
    /// this command and invokes the handler as normal (still respecting the
    /// command's [`AuthRequirement`]). The handler is responsible for
    /// running its real validation unconditionally, checking
    /// [`CommandContext::dry_run`] to skip only the mutating I/O, and tagging
    /// its preview result with [`CommandResult::with_dry_run`].
    ///
    /// **Requires a context-aware handler.** Only handlers built with
    /// [`RuntimeCommandSpec::new_with_context`],
    /// [`new_streaming`](RuntimeCommandSpec::new_streaming),
    /// [`new_typed_with_context`](RuntimeCommandSpec::new_typed_with_context),
    /// or [`new_typed_streaming`](RuntimeCommandSpec::new_typed_streaming)
    /// receive a [`CommandContext`] and can call [`CommandContext::dry_run`].
    /// A handler built with [`RuntimeCommandSpec::new`]/[`new_typed`](RuntimeCommandSpec::new_typed)
    /// only receives `(CredentialResolver, args)` — it has no way to observe
    /// `--dry-run` at all, so opting it into `handles_dry_run` would silently
    /// execute the handler's real side effects under `--dry-run` instead of
    /// skipping them. `RuntimeCommandSpec::new`/`new_typed` debug-assert
    /// against this misuse; release builds do not, so treat the assert as a
    /// development-time safety net, not the actual guarantee — only pair this
    /// field with one of the four context-aware constructors above.
    pub handles_dry_run: bool,
    /// Forces this command's successful output to print verbatim to stdout.
    pub raw_output: bool,
    /// Provider-specific auth metadata.
    pub auth_metadata: BTreeMap<String, String>,
    /// Command-specific `clap` arguments.
    pub args: Vec<Arg>,
    /// Argument relations (mutually-exclusive or "at least one of" groups).
    ///
    /// Set with [`with_arg_group`](CommandSpec::with_arg_group), or captured
    /// automatically by [`from_args`](CommandSpec::from_args) from a
    /// `#[derive(clap::Args)]` struct's `#[group(...)]` attribute.
    pub arg_groups: Vec<ArgGroup>,
    /// Optional output schema published through `--schema` and help.
    pub output_schema: Option<SchemaInfo>,
    /// Inline human-output table columns assigned directly to this command.
    ///
    /// Set with [`with_view`](CommandSpec::with_view). When present (and
    /// [`view_id`](CommandSpec::view_id) is unset), the engine registers these
    /// columns under the command's own path so human output renders them.
    pub view_columns: Vec<TableColumn>,
    /// Id of a shared human view this command should use.
    ///
    /// Set with [`with_view_id`](CommandSpec::with_view_id). Names a
    /// [`HumanViewDef`](crate::HumanViewDef) registered with `with_view` on the
    /// module or CLI, so several commands can share one table. Takes precedence
    /// over inline [`view_columns`](CommandSpec::view_columns).
    pub view_id: Option<String>,
    /// This command's own feature-flag declaration, if any.
    ///
    /// `None` means the command has no explicit stage declaration of its own,
    /// in which case it inherits its effective stage from its nearest ancestor
    /// (nested group, then enclosing group, then module — nearest declaration
    /// wins), implicitly resolving to [`Stage::Ga`] if nothing in the ancestor
    /// chain declares a flag either; see [`Stage`]'s documentation for why
    /// that is its default. Set with
    /// [`with_feature_flag`](CommandSpec::with_feature_flag). This field only
    /// records the command's own declaration; cascading resolution against the
    /// ancestor chain happens when a [`Cli`](crate::Cli) mounts the enclosing
    /// module or group.
    pub feature_flag: Option<FeatureFlag>,
    /// This command's opt-in pagination policy, if any.
    ///
    /// `None` (the default) means the command does not paginate: `--limit`/
    /// `--offset` are not registered for it, so they neither show up in its
    /// `--help` nor parse on its command line. Set with
    /// [`with_pagination`](CommandSpec::with_pagination).
    pub pagination: Option<PaginationConfig>,
}

/// Opt-in pagination policy for a single command, set with
/// [`CommandSpec::with_pagination`].
///
/// Registering this is what makes `--limit`/`--offset` exist for a command at
/// all — without it, the engine does not register those flags, so they are
/// absent from `--help` and rejected as unknown arguments if passed. Construct
/// it with `..Default::default()`, as in the example below, so a future
/// engine release can add fields without breaking existing callers.
///
/// ```
/// use cli_engine::PaginationConfig;
///
/// let pagination = PaginationConfig {
///     default_limit: 20,
///     max_limit: 100,
///     ..Default::default()
/// };
/// assert_eq!(pagination.default_limit, 20);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PaginationConfig {
    /// Page size applied when the user passes neither `--limit` nor
    /// `--offset`. `0` (the default) means unlimited — the same "no
    /// pagination" sentinel used everywhere else in the output pipeline.
    pub default_limit: i64,
    /// Upper bound a user can request with an explicit `--limit`. `0` (the
    /// default) means uncapped. Does not affect `default_limit` itself.
    pub max_limit: i64,
}

impl CommandSpec {
    /// Creates a command spec with the required name and one-line help.
    #[must_use]
    pub fn new(name: impl Into<String>, short: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            short: short.into(),
            ..Self::default()
        }
    }

    /// Creates a command spec from a `#[derive(clap::Args)]` struct.
    ///
    /// Extracts the argument definitions from the derive type and populates the
    /// spec's args list. The command name and help text are still required since
    /// `Args` types do not carry those. Also captures any `ArgGroup`s the derive
    /// macro registers (via a struct-level `#[group(...)]` attribute) into
    /// [`arg_groups`](CommandSpec::arg_groups).
    ///
    /// **Flatten caveat**: `clap_derive` empties a struct's own implicit group's
    /// member list when the struct also has a `#[command(flatten)]` field, so a
    /// `#[group(required = true)]` on such a struct silently enforces nothing.
    /// This is debug-asserted against below; treat it as a development-time
    /// safety net, not the actual guarantee.
    #[must_use]
    pub fn from_args<T: clap::Args>(name: impl Into<String>, short: impl Into<String>) -> Self {
        let name = name.into();
        let placeholder = Command::new("__placeholder");
        let augmented = T::augment_args(placeholder);
        let args: Vec<Arg> = augmented
            .get_arguments()
            // `cli-engine` registers its own global `--help` flag. Retain a
            // command-specific `--version` flag: it may represent a resource
            // version rather than the CLI binary version.
            .filter(|arg| arg.get_id().as_str() != "help")
            .cloned()
            .collect();
        let arg_groups: Vec<ArgGroup> = augmented.get_groups().cloned().collect();
        debug_assert!(
            arg_groups
                .iter()
                .all(|group| !group.is_required_set() || group.get_args().count() > 0),
            "command {name:?} has a required ArgGroup with no member args — likely the \
             clap_derive flatten+group interaction emptying the implicit group's \
             member list; the constraint will not be enforced"
        );
        Self {
            name,
            short: short.into(),
            args,
            arg_groups,
            ..Self::default()
        }
    }

    /// Sets expanded command help.
    #[must_use]
    pub fn with_long(mut self, long: impl Into<String>) -> Self {
        self.long = Some(long.into());
        self
    }

    /// Adds one command alias.
    #[must_use]
    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Hides or shows this command in discovery output.
    #[must_use]
    pub fn hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets the backend/system id for output metadata and error attribution.
    #[must_use]
    pub fn with_system(mut self, system: impl Into<String>) -> Self {
        self.system = Some(system.into());
        self
    }

    /// Sets the default field projection used when `--fields` is absent.
    #[must_use]
    pub fn with_default_fields(mut self, default_fields: impl Into<String>) -> Self {
        self.default_fields = Some(default_fields.into());
        self
    }

    /// Assigns an inline human-output table view to this command.
    ///
    /// The columns are registered under the command's own path, so human output
    /// renders this table directly. Field selection still applies: `--fields`
    /// (defaulting to [`default_fields`](CommandSpec::default_fields)) narrows
    /// which of these columns show. Use
    /// [`with_view_id`](CommandSpec::with_view_id) instead to point at a shared
    /// view registered with `with_view` on the module or CLI.
    #[must_use]
    pub fn with_view(mut self, columns: impl Into<Vec<TableColumn>>) -> Self {
        self.view_columns = columns.into();
        self
    }

    /// Points this command at a shared human view by id.
    ///
    /// The id must match a [`HumanViewDef`](crate::HumanViewDef) registered with
    /// `with_view` on the module or CLI, letting several commands share one
    /// table. Takes precedence over inline [`with_view`](CommandSpec::with_view)
    /// columns.
    #[must_use]
    pub fn with_view_id(mut self, id: impl Into<String>) -> Self {
        self.view_id = Some(id.into());
        self
    }

    /// Selects the auth provider for this command.
    #[must_use]
    pub fn with_auth_provider(mut self, provider: impl Into<String>) -> Self {
        self.auth_provider = Some(provider.into());
        self
    }

    /// Marks the command as no-auth.
    ///
    /// `no_auth(true)` sets [`AuthRequirement::None`]: the command never resolves
    /// a credential and default-env injection is suppressed. `no_auth(false)`
    /// restores the default [`AuthRequirement::Required`].
    #[must_use]
    pub fn no_auth(mut self, no_auth: bool) -> Self {
        self.auth = if no_auth {
            AuthRequirement::None
        } else {
            AuthRequirement::Required
        };
        self
    }

    /// Sets the command's [`AuthRequirement`] explicitly.
    #[must_use]
    pub fn auth(mut self, requirement: AuthRequirement) -> Self {
        self.auth = requirement;
        self
    }

    /// Marks authentication as optional ([`AuthRequirement::Optional`]).
    ///
    /// The engine does not resolve a credential before the handler runs; the
    /// handler triggers the auth flow only by calling
    /// [`CredentialResolver::resolve`]/[`try_resolve`](CredentialResolver::try_resolve).
    /// Use for commands that should still run when the user is logged out.
    #[must_use]
    pub fn auth_optional(mut self) -> Self {
        self.auth = AuthRequirement::Optional;
        self
    }

    /// Sets the command risk tier.
    #[must_use]
    pub fn with_tier(mut self, tier: Tier) -> Self {
        self.tier = Some(tier);
        self
    }

    /// Declares this command's own feature flag: the key used for policy
    /// overrides and introspection, and the stage at which it becomes visible.
    #[must_use]
    pub fn with_feature_flag(mut self, key: impl Into<String>, stage: Stage) -> Self {
        self.feature_flag = Some(FeatureFlag::new(key, stage));
        self
    }

    /// Opts this command into paginated list output.
    ///
    /// Registers `--limit`/`--offset` for this command only — a command that
    /// never calls this does not get those flags at all, in `--help` or on
    /// the command line. When the user passes neither flag, `config.default_limit`
    /// applies instead of the framework's "pagination disabled" default of
    /// unlimited; an explicit `--limit` above `config.max_limit` (when set) is
    /// rejected before the command runs. See [`PaginationConfig`].
    #[must_use]
    pub fn with_pagination(mut self, config: PaginationConfig) -> Self {
        debug_assert!(
            config.max_limit == 0 || config.default_limit <= config.max_limit,
            "command {:?} has a default_limit ({}) greater than its max_limit ({})",
            self.name,
            config.default_limit,
            config.max_limit
        );
        self.pagination = Some(config);
        self
    }

    /// Adds provider-specific auth metadata.
    #[must_use]
    pub fn with_auth_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.auth_metadata.insert(key.into(), value.into());
        self
    }

    /// Declares the OAuth scopes this command requires.
    ///
    /// Sugar over [`with_auth_metadata`](CommandSpec::with_auth_metadata) with the
    /// `"scopes"` key (whitespace-joined). The scopes surface on
    /// [`CommandMeta::scopes`](crate::CommandMeta) and reach the auth provider via
    /// [`CredentialRequest`](crate::CredentialRequest); a provider that supports
    /// scope step-up re-authenticates when the cached token lacks them.
    #[must_use]
    pub fn with_scopes(mut self, scopes: &[impl AsRef<str>]) -> Self {
        let joined = scopes
            .iter()
            .map(AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(" ");
        // Mirror `CommandMeta::set_scopes`: an empty list clears the key rather
        // than leaving an empty-but-present `auth_metadata["scopes"]`.
        if joined.is_empty() {
            self.auth_metadata.remove("scopes");
        } else {
            self.auth_metadata.insert("scopes".to_owned(), joined);
        }
        self
    }

    /// Adds a `clap` argument or option to this command.
    #[must_use]
    pub fn with_arg(mut self, arg: Arg) -> Self {
        self.args.push(arg);
        self
    }

    /// Adds a `clap` flag or option to this command.
    #[must_use]
    pub fn with_flag(self, flag: Arg) -> Self {
        self.with_arg(flag)
    }

    /// Adds an argument relation (an `ArgGroup`) to this command, e.g. to
    /// express "at least one of" or mutually-exclusive relationships between
    /// arguments added with [`with_arg`](CommandSpec::with_arg)/[`with_flag`](CommandSpec::with_flag).
    ///
    /// The group's `ArgGroup::args([...])` ids must reference args already (or
    /// later) added to this spec, matching `clap`'s own requirement that
    /// referenced arg ids exist on the built `Command`. This replaces
    /// hand-rolled `required_unless_present_any`/`conflicts_with` chains with a
    /// single declarative relation.
    #[must_use]
    pub fn with_arg_group(mut self, group: ArgGroup) -> Self {
        self.arg_groups.push(group);
        self
    }

    /// Registers a compact framework schema from an [`OutputSchema`] type.
    #[must_use]
    pub fn with_output_schema<T: OutputSchema>(mut self) -> Self {
        self.output_schema = Some(SchemaInfo {
            command: String::new(),
            fields: crate::output::fields_for::<T>(),
            schema: None,
        });
        self
    }

    /// Registers JSON Schema generated from a Rust type with `schemars`.
    #[must_use]
    pub fn with_json_schema<T: JsonSchema>(mut self) -> Self {
        self.output_schema = Some(crate::output::json_schema_info::<T>(""));
        self
    }

    /// Marks whether the command should short-circuit under `--dry-run`.
    #[must_use]
    pub fn mutates(mut self, mutates: bool) -> Self {
        self.mutates = mutates;
        self
    }

    /// Opts this command into handler-driven `--dry-run` instead of the
    /// engine's generic short-circuit.
    ///
    /// See [`handles_dry_run`](CommandSpec::handles_dry_run) (the field) for
    /// the contract a handler must follow once it opts in — in particular,
    /// **only use this with a context-aware handler**
    /// ([`RuntimeCommandSpec::new_with_context`],
    /// [`new_streaming`](RuntimeCommandSpec::new_streaming),
    /// [`new_typed_with_context`](RuntimeCommandSpec::new_typed_with_context), or
    /// [`new_typed_streaming`](RuntimeCommandSpec::new_typed_streaming)); a
    /// `new`/`new_typed` handler can't observe `--dry-run` and would execute
    /// its real side effects under it regardless of this flag.
    #[must_use]
    pub fn handles_dry_run(mut self, handles: bool) -> Self {
        self.handles_dry_run = handles;
        self
    }

    /// Forces this command's successful output to print verbatim to stdout.
    #[must_use]
    pub fn raw_output(mut self, raw_output: bool) -> Self {
        self.raw_output = raw_output;
        self
    }

    /// Builds middleware metadata from the spec.
    #[must_use]
    pub fn metadata(&self) -> CommandMeta {
        let mut auth_metadata = self.auth_metadata.clone();
        if let Some(provider) = &self.auth_provider
            && !provider.is_empty()
        {
            auth_metadata.insert("provider".to_owned(), provider.clone());
        }
        if let Some(tier) = self.tier
            && !auth_metadata.contains_key("tier")
        {
            auth_metadata.insert("tier".to_owned(), tier.to_string());
        }
        let scopes = auth_metadata
            .get("scopes")
            .map(|scopes| {
                scopes
                    .split_whitespace()
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        CommandMeta {
            dry_run_prompt: self.mutates || self.tier.is_some_and(Tier::is_mutating),
            handles_dry_run: self.handles_dry_run,
            auth_metadata,
            scopes,
        }
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.name.clone()).about(self.short.clone());
        if let Some(long) = &self.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.aliases {
            command = command.alias(alias.clone());
        }
        if self.hidden {
            command = command.hide(true);
        }
        // Explicit `display_order` (rather than relying on clap's own
        // implicit per-`Command` counter) guarantees these render first, as
        // a block, in declaration order — see `flags::global_flag_order`
        // for why leaving it implicit lets a propagated global flag collide
        // with a low counter value here and interleave with these instead.
        for (index, arg) in self.args.iter().enumerate() {
            command = command.arg(arg.clone().display_order(index));
        }
        for group in &self.arg_groups {
            command = command.group(group.clone());
        }
        command
    }
}

/// Declarative command group metadata.
///
/// Groups are noun-based containers. They do not run business logic directly;
/// when invoked bare, the CLI renders group help.
///
/// Construct with [`GroupSpec::new`], then configure with the `with_*` builder
/// methods — never as a struct literal. `#[non_exhaustive]` enforces this so
/// the engine can add fields later without a breaking release.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct GroupSpec {
    /// Group command name.
    pub name: String,
    /// One-line group description.
    pub short: String,
    /// Optional long help text.
    pub long: Option<String>,
    /// Alternate group names accepted by the parser.
    pub aliases: Vec<String>,
    /// Whether the group runs but is hidden from discovery output.
    pub hidden: bool,
    /// Declarative child commands used for static tree construction.
    pub commands: Vec<CommandSpec>,
    /// Declarative nested groups used for static tree construction.
    pub groups: Vec<GroupSpec>,
    /// This group's own feature-flag declaration, if any.
    ///
    /// `None` means the group has no explicit stage declaration of its own, in
    /// which case it inherits its effective stage from its nearest ancestor
    /// (enclosing group, then module — nearest declaration wins), implicitly
    /// resolving to [`Stage::Ga`] if nothing in the ancestor chain declares a
    /// flag either; see [`Stage`]'s documentation for why that is its default.
    /// Set with [`with_feature_flag`](GroupSpec::with_feature_flag). This field
    /// only records the group's own declaration; cascading resolution against
    /// the ancestor chain happens when a [`Cli`](crate::Cli) mounts the
    /// enclosing module or parent group.
    pub feature_flag: Option<FeatureFlag>,
}

impl GroupSpec {
    /// Creates a command group with the required name and one-line help.
    #[must_use]
    pub fn new(name: impl Into<String>, short: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            short: short.into(),
            ..Self::default()
        }
    }

    /// Sets expanded group help.
    #[must_use]
    pub fn with_long(mut self, long: impl Into<String>) -> Self {
        self.long = Some(long.into());
        self
    }

    /// Adds one group alias.
    #[must_use]
    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
        self.aliases.push(alias.into());
        self
    }

    /// Hides or shows this group in discovery output.
    #[must_use]
    pub fn hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Adds one declarative child command.
    #[must_use]
    pub fn with_command(mut self, command: CommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Adds one declarative nested group.
    #[must_use]
    pub fn with_group(mut self, group: GroupSpec) -> Self {
        self.groups.push(group);
        self
    }

    /// Declares this group's own feature flag: the key used for policy overrides
    /// and introspection, and the stage at which it becomes visible.
    #[must_use]
    pub fn with_feature_flag(mut self, key: impl Into<String>, stage: Stage) -> Self {
        self.feature_flag = Some(FeatureFlag::new(key, stage));
        self
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.name.clone()).about(self.short.clone());
        if let Some(long) = &self.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.aliases {
            command = command.alias(alias.clone());
        }
        if self.hidden {
            command = command.hide(true);
        }
        for group in &self.groups {
            command = command.subcommand(group.clap_command());
        }
        for child in &self.commands {
            command = command.subcommand(child.clap_command());
        }
        command
    }
}

/// Executable leaf command.
///
/// `RuntimeCommandSpec` pairs a [`CommandSpec`] with async business logic.
/// This split keeps metadata inspectable for help/search/schema generation
/// before the handler ever runs.
///
/// Use [`RuntimeCommandSpec::new_streaming`] for commands that emit incremental
/// NDJSON progress events (e.g. long-running deployments with `--follow`).
///
/// Construct with one of the `new*` constructors — never as a struct literal.
/// Literal construction would bypass the `handles_dry_run`/handler-shape
/// misuse checks those constructors debug-assert. `#[non_exhaustive]` also
/// means the engine can add fields without a breaking release.
#[derive(Clone)]
#[non_exhaustive]
pub struct RuntimeCommandSpec {
    /// Declarative command metadata.
    pub spec: CommandSpec,
    /// Async command implementation.
    pub handler: CommandHandler,
    /// Optional streaming handler. When set, the engine writes NDJSON events
    /// to stdout as they arrive instead of collecting a single envelope.
    pub streaming_handler: Option<StreamingCommandHandler>,
}

impl std::fmt::Debug for RuntimeCommandSpec {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RuntimeCommandSpec")
            .field("spec", &self.spec)
            .field("is_streaming", &self.streaming_handler.is_some())
            .finish_non_exhaustive()
    }
}

impl RuntimeCommandSpec {
    /// Creates a runtime command with the common handler shape.
    ///
    /// The handler receives a lazy [`CredentialResolver`] and the effective args.
    /// Call `resolver.resolve().await?` only when the command actually needs a
    /// credential; commands that ignore it never trigger an auth flow. The
    /// handler returns [`CommandResult`], where `data` must be JSON-serializable.
    ///
    /// This handler shape has no [`CommandContext`], so it can never call
    /// [`CommandContext::dry_run`] — do not pair this with
    /// [`CommandSpec::handles_dry_run`] (debug-asserted; see that field's docs).
    #[must_use]
    pub fn new<F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        F: Fn(CredentialResolver, ValueMap) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        debug_assert!(
            !spec.handles_dry_run,
            "command {:?} sets handles_dry_run but RuntimeCommandSpec::new's handler \
             (CredentialResolver, args) has no CommandContext and can never check \
             CommandContext::dry_run(), so it would silently run its real side effects \
             under --dry-run; use RuntimeCommandSpec::new_with_context (or \
             new_typed_with_context to keep typed args) instead",
            spec.name
        );
        Self {
            spec,
            streaming_handler: None,
            handler: Arc::new(move |context| {
                let future = handler(context.credential, context.args);
                Box::pin(async move { future.await.map(Into::into) })
            }),
        }
    }

    /// Creates a runtime command with the full invocation context.
    #[must_use]
    pub fn new_with_context<F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        F: Fn(CommandContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        Self {
            spec,
            streaming_handler: None,
            handler: Arc::new(move |context| {
                let future = handler(context);
                Box::pin(async move { future.await.map(Into::into) })
            }),
        }
    }

    /// Creates a streaming command that emits NDJSON events to stdout.
    ///
    /// The handler receives context and a [`StreamSender`]. It should call
    /// `sender.send(event).await` for each progress event, then return `Ok(())`.
    /// The engine writes each event as a JSON line; stdout is flushed after each.
    #[must_use]
    pub fn new_streaming<F, Fut>(spec: CommandSpec, handler: F) -> Self
    where
        F: Fn(CommandContext, StreamSender) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        debug_assert!(
            !spec.raw_output,
            "command {:?} sets raw_output but RuntimeCommandSpec::new_streaming writes \
             chunked NDJSON events, which does not fit a single-verbatim-string contract; \
             raw_output is only supported on non-streaming commands",
            spec.name
        );
        let streaming: StreamingCommandHandler = Arc::new(move |context, sender| {
            let future = handler(context, sender);
            Box::pin(future)
        });
        Self {
            spec,
            streaming_handler: Some(streaming),
            handler: Arc::new(|_context| Box::pin(async { Ok(CommandResult::new(Value::Null)) })),
        }
    }

    /// Creates a runtime command with typed argument deserialization.
    ///
    /// The handler receives a lazy [`CredentialResolver`] and the deserialized
    /// args struct. Use with `CommandSpec::from_args::<T>()` to get end-to-end
    /// type safety from argument definition through handler consumption.
    ///
    /// If the handler also needs the command path, middleware, or user-supplied
    /// args, use [`RuntimeCommandSpec::new_typed_with_context`] (or
    /// [`RuntimeCommandSpec::new_with_context`] with
    /// [`CommandContext::typed_args`]) instead.
    ///
    /// This handler shape has no [`CommandContext`], so it can never call
    /// [`CommandContext::dry_run`] — do not pair this with
    /// [`CommandSpec::handles_dry_run`] (debug-asserted; see that field's docs).
    #[must_use]
    pub fn new_typed<T, F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        T: clap::FromArgMatches + Send + 'static,
        F: Fn(CredentialResolver, T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        debug_assert!(
            !spec.handles_dry_run,
            "command {:?} sets handles_dry_run but RuntimeCommandSpec::new_typed's handler \
             (CredentialResolver, args) has no CommandContext and can never check \
             CommandContext::dry_run(), so it would silently run its real side effects \
             under --dry-run; use RuntimeCommandSpec::new_with_context (or \
             new_typed_with_context to keep typed args) instead",
            spec.name
        );
        let handler = Arc::new(handler);
        Self {
            spec,
            handler: Arc::new(move |context| {
                let credential = context.credential.clone();
                let parsed = T::from_arg_matches(context.raw_matches.as_ref());
                let handler = handler.clone();
                Box::pin(async move {
                    let args = parsed.map_err(|e| {
                        crate::CliCoreError::Message(format!("argument parse error: {e}"))
                    })?;
                    handler(credential, args).await.map(Into::into)
                })
            }),
            streaming_handler: None,
        }
    }

    /// Creates a runtime command with full context and typed argument
    /// deserialization.
    ///
    /// Combines [`new_with_context`](RuntimeCommandSpec::new_with_context)'s
    /// access to [`CommandContext`] (command path, middleware snapshot,
    /// user-supplied args, [`CommandContext::dry_run`]) with
    /// [`new_typed`](RuntimeCommandSpec::new_typed)'s automatic
    /// deserialization: the engine parses `T` from the raw matches before
    /// invoking the handler, so the handler never needs to call
    /// [`CommandContext::typed_args`] itself.
    ///
    /// Use this instead of `new_with_context` + `context.typed_args::<T>()`
    /// when a command needs full context and wants eager, guaranteed-parsed
    /// typed args rather than parsing on demand. Because the handler receives
    /// a [`CommandContext`], this is a valid pairing with
    /// [`CommandSpec::handles_dry_run`].
    ///
    /// # Errors
    ///
    /// The returned handler surfaces a `CliCoreError::Message` if `T` fails to
    /// deserialize from the parsed matches (this should not happen for args
    /// generated by `CommandSpec::from_args::<T>()`, since `clap` already
    /// validated them during parsing).
    #[must_use]
    pub fn new_typed_with_context<T, F, Fut, Output>(spec: CommandSpec, handler: F) -> Self
    where
        T: clap::FromArgMatches + Send + 'static,
        F: Fn(CommandContext, T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output>> + Send + 'static,
        Output: Into<CommandResult> + Send + 'static,
    {
        let handler = Arc::new(handler);
        Self {
            spec,
            handler: Arc::new(move |context| {
                let parsed = T::from_arg_matches(context.raw_matches.as_ref());
                let handler = handler.clone();
                Box::pin(async move {
                    let args = parsed.map_err(|e| {
                        crate::CliCoreError::Message(format!("argument parse error: {e}"))
                    })?;
                    handler(context, args).await.map(Into::into)
                })
            }),
            streaming_handler: None,
        }
    }

    /// Creates a streaming command with full context and typed argument
    /// deserialization.
    ///
    /// Combines [`new_streaming`](RuntimeCommandSpec::new_streaming)'s NDJSON
    /// event emission with [`new_typed`](RuntimeCommandSpec::new_typed)'s
    /// automatic deserialization: the engine parses `T` from the raw matches
    /// before invoking the handler.
    ///
    /// # Errors
    ///
    /// The returned handler surfaces a `CliCoreError::Message` if `T` fails to
    /// deserialize from the parsed matches.
    #[must_use]
    pub fn new_typed_streaming<T, F, Fut>(spec: CommandSpec, handler: F) -> Self
    where
        T: clap::FromArgMatches + Send + 'static,
        F: Fn(CommandContext, T, StreamSender) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        debug_assert!(
            !spec.raw_output,
            "command {:?} sets raw_output but RuntimeCommandSpec::new_typed_streaming writes \
             chunked NDJSON events, which does not fit a single-verbatim-string contract; \
             raw_output is only supported on non-streaming commands",
            spec.name
        );
        let handler = Arc::new(handler);
        let streaming: StreamingCommandHandler = Arc::new(move |context, sender| {
            let parsed = T::from_arg_matches(context.raw_matches.as_ref());
            let handler = handler.clone();
            Box::pin(async move {
                let args = parsed.map_err(|e| {
                    crate::CliCoreError::Message(format!("argument parse error: {e}"))
                })?;
                handler(context, args, sender).await
            })
        });
        Self {
            spec,
            streaming_handler: Some(streaming),
            handler: Arc::new(|_context| Box::pin(async { Ok(CommandResult::new(Value::Null)) })),
        }
    }
}

/// Executable command group with runtime children.
///
/// Construct with [`RuntimeGroupSpec::new`], then chain `with_*` methods —
/// never as a struct literal. `#[non_exhaustive]` enforces this so the engine
/// can add fields without a breaking release.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RuntimeGroupSpec {
    /// Declarative group metadata.
    pub group: GroupSpec,
    /// Executable leaf commands under this group.
    pub commands: Vec<RuntimeCommandSpec>,
    /// Executable nested groups under this group.
    pub groups: Vec<RuntimeGroupSpec>,
}

impl RuntimeGroupSpec {
    /// Creates a runtime group from declarative group metadata.
    #[must_use]
    pub fn new(group: GroupSpec) -> Self {
        Self {
            group,
            ..Self::default()
        }
    }

    /// Adds one executable leaf command.
    #[must_use]
    pub fn with_command(mut self, command: RuntimeCommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Adds one executable nested group.
    #[must_use]
    pub fn with_group(mut self, group: RuntimeGroupSpec) -> Self {
        self.groups.push(group);
        self
    }

    /// Builds the `clap` command for parser registration.
    #[must_use]
    pub fn clap_command(&self) -> Command {
        let mut command = Command::new(self.group.name.clone()).about(self.group.short.clone());
        if let Some(long) = &self.group.long
            && !long.is_empty()
        {
            command = command.long_about(long.clone());
        }
        for alias in &self.group.aliases {
            command = command.alias(alias.clone());
        }
        if self.group.hidden {
            command = command.hide(true);
        }
        for group in &self.groups {
            command = command.subcommand(group.clap_command());
        }
        for child in &self.commands {
            command = command.subcommand(child.spec.clap_command());
        }
        command
    }

    pub(crate) fn register_commands(
        &self,
        prefix: &mut Vec<String>,
        out: &mut BTreeMap<String, RuntimeCommandSpec>,
    ) {
        prefix.push(self.group.name.clone());
        for group in &self.groups {
            group.register_commands(prefix, out);
        }
        for command in &self.commands {
            prefix.push(command.spec.name.clone());
            out.insert(prefix.join(":"), command.clone());
            prefix.pop();
        }
        prefix.pop();
    }
}

/// Extracts the colon-separated command path from parsed `clap` matches.
#[must_use]
pub fn command_path_from_matches(root_name: &str, matches: &ArgMatches) -> String {
    let mut parts = Vec::new();
    let mut current = matches;
    while let Some((name, submatches)) = current.subcommand() {
        if name != root_name {
            parts.push(name.to_owned());
        }
        current = submatches;
    }
    parts.join(":")
}

/// Builds a colon-separated command path from path parts.
///
/// The optional annotation is used only for isolated single-command tests.
#[must_use]
pub fn command_path_from_parts(parts: &[impl AsRef<str>], path_annotation: Option<&str>) -> String {
    if parts.is_empty() {
        return String::new();
    }
    if parts.len() > 1 {
        return parts[1..]
            .iter()
            .map(AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(":");
    }
    path_annotation
        .filter(|annotation| !annotation.is_empty())
        .map_or_else(|| parts[0].as_ref().to_owned(), ToOwned::to_owned)
}

/// Returns the deepest subcommand matches.
#[must_use]
pub fn leaf_matches(matches: &ArgMatches) -> &ArgMatches {
    let mut current = matches;
    while let Some((_, submatches)) = current.subcommand() {
        current = submatches;
    }
    current
}

/// Converts parsed command arguments into the JSON-ish map consumed by middleware.
///
/// When `changed_only` is true, only arguments that came from the command line
/// are included. This is the user-args map used by authz and audit.
#[must_use]
pub fn command_args_from_matches(
    matches: &ArgMatches,
    spec: &CommandSpec,
    changed_only: bool,
) -> ValueMap {
    let mut args = ValueMap::new();
    for arg in &spec.args {
        let id = arg.get_id().to_string();
        let changed = matches
            .value_source(&id)
            .is_some_and(|source| source == clap::parser::ValueSource::CommandLine);
        if changed_only && !changed {
            continue;
        }
        if let Some(value) = arg_value_from_matches(matches, arg, &id) {
            args.insert(id, value);
        }
    }
    args
}

fn arg_value_from_matches(matches: &ArgMatches, flag: &Arg, id: &str) -> Option<Value> {
    matches.value_source(id)?;

    if matches!(flag.get_action(), ArgAction::SetTrue | ArgAction::SetFalse)
        && let Some(value) = matches.get_one::<bool>(id)
    {
        return Some(Value::Bool(*value));
    }

    if let Some(value) = typed_arg_value_from_matches(matches, id) {
        return Some(value);
    }

    if let Some(values) = matches.get_raw(id) {
        let rendered = values
            .map(|value| value.to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        return match rendered.as_slice() {
            [] => None,
            [single] => Some(Value::String(single.clone())),
            _ => Some(Value::Array(
                rendered.into_iter().map(Value::String).collect(),
            )),
        };
    }

    if let Some(value) = matches.get_one::<String>(id) {
        return Some(Value::String(value.clone()));
    }
    if let Some(value) = matches.get_one::<usize>(id) {
        return Some(serde_json::json!(value));
    }
    if let Some(value) = matches.get_one::<u64>(id) {
        return Some(serde_json::json!(value));
    }
    if let Some(value) = matches.get_one::<i64>(id) {
        return Some(serde_json::json!(value));
    }
    None
}

fn typed_arg_value_from_matches(matches: &ArgMatches, id: &str) -> Option<Value> {
    typed_values::<bool>(matches, id, Value::Bool)
        .or_else(|| typed_values::<i8>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i16>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i64>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<i32>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u8>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u16>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u64>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| typed_values::<u32>(matches, id, |value| Value::Number(value.into())))
        .or_else(|| {
            typed_values::<usize>(matches, id, |value| {
                u64::try_from(value).map_or(Value::Null, |value| Value::Number(value.into()))
            })
        })
        .or_else(|| {
            typed_values::<f64>(matches, id, |value| {
                Number::from_f64(value).map_or(Value::Null, Value::Number)
            })
        })
        .or_else(|| {
            typed_values::<f32>(matches, id, |value| {
                Number::from_f64(f64::from(value)).map_or(Value::Null, Value::Number)
            })
        })
        .or_else(|| typed_values::<String>(matches, id, Value::String))
}

fn typed_values<T>(matches: &ArgMatches, id: &str, to_value: impl Fn(T) -> Value) -> Option<Value>
where
    T: Clone + Send + Sync + 'static,
{
    let Ok(Some(values)) = matches.try_get_many::<T>(id) else {
        return None;
    };
    let values = values.cloned().map(to_value).collect::<Vec<_>>();
    match values.as_slice() {
        [] => None,
        [single] => Some(single.clone()),
        _ => Some(Value::Array(values)),
    }
}

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

    #[test]
    fn command_spec_with_feature_flag_sets_key_and_stage() {
        let spec =
            CommandSpec::new("list", "List things").with_feature_flag("my-flag", Stage::Beta);

        let flag = spec
            .feature_flag
            .as_ref()
            .expect("feature flag should be set");
        assert_eq!(flag.key, "my-flag");
        assert_eq!(flag.stage, Stage::Beta);
    }

    #[test]
    fn command_spec_feature_flag_defaults_to_none() {
        let spec = CommandSpec::new("list", "List things");

        assert!(spec.feature_flag.is_none());
    }

    #[test]
    fn group_spec_with_feature_flag_sets_key_and_stage() {
        let group = GroupSpec::new("project", "Manage projects")
            .with_feature_flag("my-flag", Stage::Experimental);

        let flag = group
            .feature_flag
            .as_ref()
            .expect("feature flag should be set");
        assert_eq!(flag.key, "my-flag");
        assert_eq!(flag.stage, Stage::Experimental);
    }

    #[test]
    fn group_spec_feature_flag_defaults_to_none() {
        let group = GroupSpec::new("project", "Manage projects");

        assert!(group.feature_flag.is_none());
    }

    #[test]
    fn command_spec_with_arg_group_registers_group_on_clap_command() {
        let spec = CommandSpec::new("update", "Update a thing")
            .with_arg(Arg::new("a").long("a"))
            .with_arg(Arg::new("b").long("b"))
            .with_arg_group(ArgGroup::new("ab").args(["a", "b"]).required(true));

        assert!(
            spec.clap_command()
                .try_get_matches_from(["update"])
                .is_err(),
            "neither `a` nor `b` present should fail the required group"
        );
        assert!(
            spec.clap_command()
                .try_get_matches_from(["update", "--a", "x"])
                .is_ok()
        );
    }

    #[test]
    fn command_spec_from_args_preserves_derive_arg_group() {
        #[derive(clap::Args)]
        #[group(required = true, multiple = false)]
        struct ExclusiveArgs {
            #[arg(long)]
            one: bool,
            #[arg(long)]
            two: bool,
        }

        let spec = CommandSpec::from_args::<ExclusiveArgs>("bump", "Bump one thing");

        assert_eq!(spec.arg_groups.len(), 1);
        let group = &spec.arg_groups[0];
        assert!(group.is_required_set());
        assert_eq!(group.get_args().count(), 2);
    }

    #[test]
    fn command_spec_from_args_preserves_version_argument() {
        #[derive(clap::Args)]
        struct ReleaseArgs {
            #[arg(long)]
            version: String,
        }

        let spec = CommandSpec::from_args::<ReleaseArgs>("release", "Create a release");

        assert!(
            spec.clap_command()
                .try_get_matches_from(["release", "--version", "1.0.0"])
                .is_ok(),
            "typed command arguments named `version` must remain available as `--version`"
        );
    }
}