dynamic-cli 0.5.0

A framework for building configurable CLI and REPL applications from YAML/JSON configuration files
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
//! Command registry implementation
//!
//! This module provides the central registry for storing and retrieving
//! command definitions and their associated handlers.
//!
//! # Architecture
//!
//! The registry maintains two main data structures:
//! - A map of command names to their definitions and handlers
//! - A map of aliases to canonical command names
//!
//! This design allows O(1) lookup by both command name and alias.
//!
//! # Example
//!
//! ```
//! use dynamic_cli::registry::CommandRegistry;
//! use dynamic_cli::config::schema::CommandDefinition;
//! use dynamic_cli::executor::CommandHandler;
//! use std::collections::HashMap;
//!
//! // Create a registry
//! let mut registry = CommandRegistry::new();
//!
//! // Define a command
//! let definition = CommandDefinition {
//!     name: "hello".to_string(),
//!     aliases: vec!["hi".to_string(), "greet".to_string()],
//!     description: "Say hello".to_string(),
//!     required: false,
//!     arguments: vec![],
//!     options: vec![],
//!     implementation: "hello_handler".to_string(),
//! };
//!
//! // Create a handler
//! struct HelloCommand;
//! impl CommandHandler for HelloCommand {
//!     fn execute(
//!         &self,
//!         _ctx: &mut dyn dynamic_cli::context::ExecutionContext,
//!         _args: &HashMap<String, String>,
//!     ) -> dynamic_cli::Result<()> {
//!         println!("Hello!");
//!         Ok(())
//!     }
//! }
//!
//! // Register the command
//! registry.register_sync(definition, Box::new(HelloCommand))?;
//!
//! // Retrieve by name
//! assert!(registry.get_handler_sync("hello").is_some());
//!
//! // Retrieve by alias
//! assert_eq!(registry.resolve_name("hi"), Some("hello"));
//! # Ok::<(), dynamic_cli::error::DynamicCliError>(())
//! ```

use crate::config::schema::CommandDefinition;
use crate::error::{RegistryError, Result};
use crate::executor::{AsyncCommandHandler, CommandHandler};
use std::collections::HashMap;

/// Internal storage for a single registered command's handler.
///
/// Private — never leaks into the public API. `get_handler_sync()` /
/// `get_handler_async()` return `None` when queried against the wrong
/// variant, so callers never need to know this enum exists. See DD-022 for
/// the rationale behind unifying sync and async storage in one map instead
/// of two parallel `HashMap`s.
enum StoredHandler {
    Sync(Box<dyn CommandHandler>),
    Async(Box<dyn AsyncCommandHandler>),
}
/// Central registry for commands and their handlers
///
/// The registry stores all registered commands along with their definitions
/// and handlers. It provides efficient lookup by both command name and alias.
///
/// # Thread Safety
///
/// The registry is designed to be constructed once during application startup
/// and then shared immutably across the application. For multi-threaded access,
/// wrap it in `Arc<CommandRegistry>`.
///
/// # Example
///
/// ```
/// use dynamic_cli::registry::CommandRegistry;
/// use dynamic_cli::config::schema::CommandDefinition;
/// use dynamic_cli::executor::CommandHandler;
/// use std::collections::HashMap;
///
/// let mut registry = CommandRegistry::new();
///
/// // Register commands during initialization
/// # let definition = CommandDefinition {
/// #     name: "test".to_string(),
/// #     aliases: vec![],
/// #     description: "Test".to_string(),
/// #     required: false,
/// #     arguments: vec![],
/// #     options: vec![],
/// #     implementation: "test_handler".to_string(),
/// # };
/// # struct TestCommand;
/// # impl CommandHandler for TestCommand {
/// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
/// # }
/// registry.register_sync(definition, Box::new(TestCommand))?;
///
/// // Use throughout the application
/// if let Some(handler) = registry.get_handler_sync("test") {
///     // Execute the command
/// }
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
pub struct CommandRegistry {
    /// Map of command names to their data
    /// Key: canonical command name
    /// Value: (CommandDefinition, Box<dyn CommandHandler>)
    commands: HashMap<String, (CommandDefinition, StoredHandler)>,

    /// Map of aliases to canonical command names
    /// Key: alias
    /// Value: canonical command name
    ///
    /// This allows O(1) resolution of aliases to command names.
    aliases: HashMap<String, String>,
}

impl CommandRegistry {
    /// Create a new empty registry
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    ///
    /// let registry = CommandRegistry::new();
    /// assert_eq!(registry.list_commands().len(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            commands: HashMap::new(),
            aliases: HashMap::new(),
        }
    }

    /// Checks that `name` is free to use as a command name or alias.
    ///
    /// Shared by [`register_sync`][Self::register_sync] and
    /// [`register_async`][Self::register_async] — a name can never belong
    /// to both a sync and an async handler, nor be duplicated as a command
    /// or an alias. Checked against the single unified `commands` map, so
    /// this one call covers both storage kinds.
    ///
    /// # Errors
    ///
    /// - [`RegistryError::DuplicateRegistration`] if `name` is already a
    ///   registered command (sync or async).
    /// - [`RegistryError::DuplicateAlias`] if `name` is already registered
    ///   as an alias of another command.
    fn check_name_available(&self, name: &str) -> Result<()> {
        if self.commands.contains_key(name) {
            return Err(RegistryError::DuplicateRegistration {
                name: name.to_string(),
                suggestion: None,
            }
            .into());
        }

        if let Some(existing_cmd) = self.aliases.get(name) {
            return Err(RegistryError::DuplicateAlias {
                alias: name.to_string(),
                existing_command: existing_cmd.clone(),
                suggestion: None,
            }
            .into());
        }

        Ok(())
    }

    /// Registers every alias declared in `definition` as pointing to
    /// `definition.name`. Called by both `register_sync` and
    /// `register_async` after `check_name_available` has confirmed there is
    /// no conflict.
    fn insert_aliases(&mut self, definition: CommandDefinition) {
        for alias in &definition.aliases {
            self.aliases.insert(alias.clone(), definition.name.clone());
        }
    }

    /// Register a command with its (sync) handler
    ///
    /// This method registers a command definition along with its handler.
    /// It also registers all aliases for the command.
    ///
    /// Renamed from `register()` in v0.5.0 for symmetry with
    /// [`register_async`][Self::register_async]. `register()` remains
    /// available as a deprecated alias until v1.0.0 (DD-022).
    ///
    /// # Arguments
    ///
    /// * `definition` - The command definition from the configuration
    /// * `handler` - The handler implementation for this command
    ///
    /// # Returns
    ///
    /// - `Ok(())` if registration succeeds
    /// - `Err(RegistryError)` if:
    ///   - A command with the same name is already registered (sync or async)
    ///   - An alias conflicts with an existing command or alias
    ///
    /// # Errors
    ///
    /// - [`RegistryError::DuplicateRegistration`] if the command name already exists
    /// - [`RegistryError::DuplicateAlias`] if an alias is already in use
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    /// use dynamic_cli::config::schema::CommandDefinition;
    /// use dynamic_cli::executor::CommandHandler;
    /// use std::collections::HashMap;
    ///
    /// let mut registry = CommandRegistry::new();
    ///
    /// let definition = CommandDefinition {
    ///     name: "simulate".to_string(),
    ///     aliases: vec!["sim".to_string(), "run".to_string()],
    ///     description: "Run simulation".to_string(),
    ///     required: false,
    ///     arguments: vec![],
    ///     options: vec![],
    ///     implementation: "sim_handler".to_string(),
    /// };
    ///
    /// struct SimCommand;
    /// impl CommandHandler for SimCommand {
    ///     fn execute(
    ///         &self,
    ///         _: &mut dyn dynamic_cli::context::ExecutionContext,
    ///         _: &HashMap<String, String>,
    ///     ) -> dynamic_cli::Result<()> {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// // Register the command
    /// registry.register_sync(definition, Box::new(SimCommand))?;
    ///
    /// // Can now access by name or alias
    /// assert!(registry.get_handler_sync("simulate").is_some());
    /// assert_eq!(registry.resolve_name("sim"), Some("simulate"));
    /// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
    /// ```
    pub fn register_sync(
        &mut self,
        definition: CommandDefinition,
        handler: Box<dyn CommandHandler>,
    ) -> Result<()> {
        self.check_name_available(&definition.name)?;
        for alias in &definition.aliases {
            self.check_name_available(alias)?;
        }
        self.insert_aliases(definition.clone());
        self.commands.insert(
            definition.name.clone(),
            (definition, StoredHandler::Sync(handler)),
        );
        Ok(())
    }

    /// Deprecated alias for [`register_sync`][Self::register_sync].
    ///
    /// Kept for backward compatibility with pre-0.5.0 consumers (e.g.
    /// `chrom-rs`). Scheduled for removal in v1.0.0, batched with the other
    /// breaking changes tracked in the v1.0.0 API cleanup issue.
    #[deprecated(
        since = "0.5.0",
        note = "renamed to `register_sync` for symmetry with `register_async`; \
                will be removed in 1.0.0"
    )]
    pub fn register(
        &mut self,
        definition: CommandDefinition,
        handler: Box<dyn CommandHandler>,
    ) -> Result<()> {
        self.register_sync(definition, handler)
    }

    /// Register a command with its async handler (DD-022)
    ///
    /// Additive counterpart of [`register_sync`][Self::register_sync] —
    /// same conflict-detection rules (checked against both sync and async
    /// registrations sharing the unified internal storage, plus aliases),
    /// same alias handling.
    ///
    /// # Errors
    ///
    /// - [`RegistryError::DuplicateRegistration`] if the command name already exists
    /// - [`RegistryError::DuplicateAlias`] if an alias is already in use
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    /// use dynamic_cli::config::schema::CommandDefinition;
    /// use dynamic_cli::executor::AsyncCommandHandler;
    /// use std::collections::HashMap;
    /// use async_trait::async_trait;
    ///
    /// let mut registry = CommandRegistry::new();
    ///
    /// let definition = CommandDefinition {
    ///     name: "fetch".to_string(),
    ///     aliases: vec![],
    ///     description: "Fetch remote data".to_string(),
    ///     required: false,
    ///     arguments: vec![],
    ///     options: vec![],
    ///     implementation: "fetch_handler".to_string(),
    /// };
    ///
    /// struct FetchCommand;
    /// #[async_trait]
    /// impl AsyncCommandHandler for FetchCommand {
    ///     async fn execute(
    ///         &self,
    ///         _: &mut dyn dynamic_cli::context::ExecutionContext,
    ///         _: &HashMap<String, String>,
    ///     ) -> dynamic_cli::Result<()> {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// registry.register_async(definition, Box::new(FetchCommand))?;
    /// assert!(registry.get_handler_async("fetch").is_some());
    /// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
    /// ```
    pub fn register_async(
        &mut self,
        definition: CommandDefinition,
        handler: Box<dyn AsyncCommandHandler>,
    ) -> Result<()> {
        self.check_name_available(&definition.name)?;
        for alias in &definition.aliases {
            self.check_name_available(alias)?;
        }
        self.insert_aliases(definition.clone());
        self.commands.insert(
            definition.name.clone(),
            (definition, StoredHandler::Async(handler)),
        );
        Ok(())
    }

    /// Resolve a name (command or alias) to the canonical command name
    ///
    /// This method checks if the given name is either:
    /// - A registered command name (returns the name itself)
    /// - An alias (returns the canonical command name)
    ///
    /// # Arguments
    ///
    /// * `name` - The name or alias to resolve
    ///
    /// # Returns
    ///
    /// - `Some(&str)` - The canonical command name
    /// - `None` - If the name is not registered
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::CommandHandler;
    /// # use std::collections::HashMap;
    ///
    /// let mut registry = CommandRegistry::new();
    ///
    /// # let definition = CommandDefinition {
    /// #     name: "hello".to_string(),
    /// #     aliases: vec!["hi".to_string()],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct TestCmd;
    /// # impl CommandHandler for TestCmd {
    /// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_sync(definition, Box::new(TestCmd)).unwrap();
    /// // Resolve command name
    /// assert_eq!(registry.resolve_name("hello"), Some("hello"));
    ///
    /// // Resolve alias
    /// assert_eq!(registry.resolve_name("hi"), Some("hello"));
    ///
    /// // Unknown name
    /// assert_eq!(registry.resolve_name("unknown"), None);
    /// ```
    pub fn resolve_name(&self, name: &str) -> Option<&str> {
        // First check if it's a command name
        // Return reference to the stored name, not the parameter
        if let Some((cmd_def, _)) = self.commands.get(name) {
            return Some(cmd_def.name.as_str());
        }

        // Then check if it's an alias
        self.aliases.get(name).map(|s| s.as_str())
    }

    /// Get the definition of a command by name or alias
    ///
    /// # Arguments
    ///
    /// * `name` - The command name or alias
    ///
    /// # Returns
    ///
    /// - `Some(&CommandDefinition)` if the command exists
    /// - `None` if the command is not registered
    ///
    /// # Example
    ///
    /// ```
    /// # use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::CommandHandler;
    /// # use std::collections::HashMap;
    /// # let mut registry = CommandRegistry::new();
    /// # let definition = CommandDefinition {
    /// #     name: "test".to_string(),
    /// #     aliases: vec!["t".to_string()],
    /// #     description: "Test command".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct TestCmd;
    /// # impl CommandHandler for TestCmd {
    /// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_sync(definition, Box::new(TestCmd)).unwrap();
    /// // Get by name
    /// if let Some(def) = registry.get_definition("test") {
    ///     assert_eq!(def.name, "test");
    ///     assert_eq!(def.description, "Test command");
    /// }
    ///
    /// // Get by alias
    /// if let Some(def) = registry.get_definition("t") {
    ///     assert_eq!(def.name, "test");
    /// }
    /// ```
    pub fn get_definition(&self, name: &str) -> Option<&CommandDefinition> {
        let canonical_name = self.resolve_name(name)?;
        self.commands.get(canonical_name).map(|(def, _)| def)
    }

    /// Get the (sync) handler of a command by name or alias
    ///
    /// This is the primary method used during CLI/REPL dispatch to
    /// retrieve the handler that will execute the command. Returns `None`
    /// both when the name isn't registered at all, and when it resolves to
    /// an *async* handler (query [`get_handler_async`][Self::get_handler_async]
    /// instead in that case) — dispatch sites try both in sequence.
    ///
    /// Renamed from `get_handler()` in v0.5.0 for symmetry with
    /// [`get_handler_async`][Self::get_handler_async]. `get_handler()`
    /// remains available as a deprecated alias until v1.0.0 (DD-022).
    ///
    /// # Arguments
    ///
    /// * `name` - The command name or alias
    ///
    /// # Returns
    ///
    /// - `Some(&dyn CommandHandler)` if a sync handler is registered under this name
    /// - `None` if unregistered, or if registered as an async handler
    ///
    /// # Example
    ///
    /// ```
    /// # use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::CommandHandler;
    /// # use std::collections::HashMap;
    /// # let mut registry = CommandRegistry::new();
    /// # let definition = CommandDefinition {
    /// #     name: "exec".to_string(),
    /// #     aliases: vec!["x".to_string()],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct ExecCmd;
    /// # impl CommandHandler for ExecCmd {
    /// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_sync(definition, Box::new(ExecCmd)).unwrap();
    /// // Get handler by name
    /// if let Some(handler) = registry.get_handler_sync("exec") {
    ///     // Use handler for execution
    /// }
    ///
    /// // Get handler by alias
    /// if let Some(handler) = registry.get_handler_sync("x") {
    ///     // Same handler
    /// }
    /// ```
    // The return type &dyn CommandHandler is intentional: callers receive a
    // reference to the handler, which preserves the indirection needed for
    // dynamic dispatch without transferring ownership.
    pub fn get_handler_sync(&self, name: &str) -> Option<&dyn CommandHandler> {
        let canonical = self.resolve_name(name)?;
        match &self.commands.get(canonical)?.1 {
            StoredHandler::Sync(h) => Some(h.as_ref()),
            StoredHandler::Async(_) => None,
        }
    }

    /// Deprecated alias for [`get_handler_sync`][Self::get_handler_sync].
    /// Scheduled for removal in v1.0.0.
    #[deprecated(
        since = "0.5.0",
        note = "renamed to `get_handler_sync` for symmetry with `get_handler_async`; \
                will be removed in 1.0.0"
    )]
    pub fn get_handler(&self, name: &str) -> Option<&dyn CommandHandler> {
        self.get_handler_sync(name)
    }

    /// Get the async handler of a command by name or alias (DD-022)
    ///
    /// Additive counterpart of [`get_handler_sync`][Self::get_handler_sync].
    /// Returns `None` both when the name isn't registered at all, and when
    /// it resolves to a *sync* handler.
    ///
    /// # Example
    ///
    /// ```
    /// # use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::AsyncCommandHandler;
    /// # use std::collections::HashMap;
    /// # use async_trait::async_trait;
    /// # let mut registry = CommandRegistry::new();
    /// # let definition = CommandDefinition {
    /// #     name: "fetch".to_string(),
    /// #     aliases: vec![],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct FetchCmd;
    /// # #[async_trait]
    /// # impl AsyncCommandHandler for FetchCmd {
    /// #     async fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_async(definition, Box::new(FetchCmd)).unwrap();
    /// assert!(registry.get_handler_async("fetch").is_some());
    /// assert!(registry.get_handler_sync("fetch").is_none()); // wrong accessor
    /// ```
    pub fn get_handler_async(&self, name: &str) -> Option<&dyn AsyncCommandHandler> {
        let canonical = self.resolve_name(name)?;
        match &self.commands.get(canonical)?.1 {
            StoredHandler::Async(h) => Some(h.as_ref()),
            StoredHandler::Sync(_) => None,
        }
    }

    /// List all registered command definitions
    ///
    /// Returns a vector of references to all command definitions in the registry.
    /// The order is not guaranteed.
    ///
    /// # Returns
    ///
    /// Vector of command definition references
    ///
    /// # Example
    ///
    /// ```
    /// # use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::CommandHandler;
    /// # use std::collections::HashMap;
    /// # let mut registry = CommandRegistry::new();
    /// # let def1 = CommandDefinition {
    /// #     name: "cmd1".to_string(),
    /// #     aliases: vec![],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # let def2 = CommandDefinition {
    /// #     name: "cmd2".to_string(),
    /// #     aliases: vec![],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct TestCmd;
    /// # impl CommandHandler for TestCmd {
    /// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_sync(def1, Box::new(TestCmd)).unwrap();
    /// # registry.register_sync(def2, Box::new(TestCmd)).unwrap();
    /// let commands = registry.list_commands();
    /// assert_eq!(commands.len(), 2);
    ///
    /// // Use for help text, command completion, etc.
    /// for cmd in commands {
    ///     println!("{}: {}", cmd.name, cmd.description);
    /// }
    /// ```
    pub fn list_commands(&self) -> Vec<&CommandDefinition> {
        self.commands.values().map(|(def, _)| def).collect()
    }

    /// Get the number of registered commands
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    ///
    /// let registry = CommandRegistry::new();
    /// assert_eq!(registry.len(), 0);
    /// ```
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Check if the registry is empty
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_cli::registry::CommandRegistry;
    ///
    /// let registry = CommandRegistry::new();
    /// assert!(registry.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Check if a command is registered (by name or alias)
    ///
    /// # Example
    ///
    /// ```
    /// # use dynamic_cli::registry::CommandRegistry;
    /// # use dynamic_cli::config::schema::CommandDefinition;
    /// # use dynamic_cli::executor::CommandHandler;
    /// # use std::collections::HashMap;
    /// # let mut registry = CommandRegistry::new();
    /// # let definition = CommandDefinition {
    /// #     name: "test".to_string(),
    /// #     aliases: vec!["t".to_string()],
    /// #     description: "".to_string(),
    /// #     required: false,
    /// #     arguments: vec![],
    /// #     options: vec![],
    /// #     implementation: "".to_string(),
    /// # };
    /// # struct TestCmd;
    /// # impl CommandHandler for TestCmd {
    /// #     fn execute(&self, _: &mut dyn dynamic_cli::context::ExecutionContext, _: &HashMap<String, String>) -> dynamic_cli::Result<()> { Ok(()) }
    /// # }
    /// # registry.register_sync(definition, Box::new(TestCmd)).unwrap();
    /// assert!(registry.contains("test"));
    /// assert!(registry.contains("t"));
    /// assert!(!registry.contains("unknown"));
    /// ```
    pub fn contains(&self, name: &str) -> bool {
        self.resolve_name(name).is_some()
    }
}

// Implement Default for convenience
impl Default for CommandRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    // Test fixtures
    #[derive(Default)]
    struct TestContext;

    impl crate::context::ExecutionContext for TestContext {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }
    }

    struct TestHandler;

    impl CommandHandler for TestHandler {
        fn execute(
            &self,
            _context: &mut dyn crate::context::ExecutionContext,
            _args: &HashMap<String, String>,
        ) -> crate::error::Result<()> {
            Ok(())
        }
    }

    struct TestAsyncHandler;

    #[async_trait::async_trait]
    impl AsyncCommandHandler for TestAsyncHandler {
        async fn execute(
            &self,
            _context: &mut dyn crate::context::ExecutionContext,
            _args: &HashMap<String, String>,
        ) -> crate::error::Result<()> {
            Ok(())
        }
    }

    fn create_test_definition(name: &str, aliases: Vec<&str>) -> CommandDefinition {
        CommandDefinition {
            name: name.to_string(),
            aliases: aliases.iter().map(|s| s.to_string()).collect(),
            description: format!("{} command", name),
            required: false,
            arguments: vec![],
            options: vec![],
            implementation: format!("{}_handler", name),
        }
    }

    // Basic functionality tests
    #[test]
    fn test_new_registry_is_empty() {
        let registry = CommandRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
        assert_eq!(registry.list_commands().len(), 0);
    }

    #[test]
    fn test_register_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        let result = registry.register_sync(definition, Box::new(TestHandler));

        assert!(result.is_ok());
        assert_eq!(registry.len(), 1);
        assert!(!registry.is_empty());
    }

    /// Deprecated-alias coverage (DD-022 companion issue): `register()` and
    /// `get_handler()` must keep behaving exactly like `register_sync()` /
    /// `get_handler_sync()` until they're removed in v1.0.0. This is the
    /// only place in the crate allowed to call them directly.
    #[test]
    #[allow(deprecated)]
    fn test_deprecated_register_alias_still_works() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("legacy", vec!["old"]);

        let result = registry.register(definition, Box::new(TestHandler));

        assert!(result.is_ok());
        assert!(registry.get_handler("legacy").is_some());
        assert!(registry.get_handler("old").is_some());
        assert_eq!(registry.resolve_name("old"), Some("legacy"));
    }

    #[test]
    fn test_register_command_with_aliases() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("hello", vec!["hi", "greet"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        assert_eq!(registry.len(), 1);
        assert!(registry.contains("hello"));
        assert!(registry.contains("hi"));
        assert!(registry.contains("greet"));
    }

    #[test]
    fn test_register_duplicate_command_fails() {
        let mut registry = CommandRegistry::new();
        let def1 = create_test_definition("test", vec![]);
        let def2 = create_test_definition("test", vec![]);

        registry.register_sync(def1, Box::new(TestHandler)).unwrap();
        let result = registry.register_sync(def2, Box::new(TestHandler));

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Registry(RegistryError::DuplicateRegistration {
                name,
                ..
            }) => {
                assert_eq!(name, "test");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_register_duplicate_alias_fails() {
        let mut registry = CommandRegistry::new();
        let def1 = create_test_definition("cmd1", vec!["c"]);
        let def2 = create_test_definition("cmd2", vec!["c"]);

        registry.register_sync(def1, Box::new(TestHandler)).unwrap();
        let result = registry.register_sync(def2, Box::new(TestHandler));

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Registry(RegistryError::DuplicateAlias {
                alias,
                existing_command,
                ..
            }) => {
                assert_eq!(alias, "c");
                assert_eq!(existing_command, "cmd1");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_alias_conflicts_with_command_name() {
        let mut registry = CommandRegistry::new();
        let def1 = create_test_definition("test", vec![]);
        let def2 = create_test_definition("other", vec!["test"]);

        registry.register_sync(def1, Box::new(TestHandler)).unwrap();
        let result = registry.register_sync(def2, Box::new(TestHandler));

        assert!(result.is_err());
    }

    #[test]
    fn test_command_name_conflicts_with_alias() {
        let mut registry = CommandRegistry::new();
        let def1 = create_test_definition("cmd1", vec!["other"]);
        let def2 = create_test_definition("other", vec![]);

        registry.register_sync(def1, Box::new(TestHandler)).unwrap();
        let result = registry.register_sync(def2, Box::new(TestHandler));

        assert!(result.is_err());
    }

    // Resolve name tests
    #[test]
    fn test_resolve_command_name() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        assert_eq!(registry.resolve_name("test"), Some("test"));
    }

    #[test]
    fn test_resolve_alias() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("hello", vec!["hi", "greet"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        assert_eq!(registry.resolve_name("hi"), Some("hello"));
        assert_eq!(registry.resolve_name("greet"), Some("hello"));
    }

    #[test]
    fn test_resolve_unknown_name() {
        let registry = CommandRegistry::new();
        assert_eq!(registry.resolve_name("unknown"), None);
    }

    // Get definition tests
    #[test]
    fn test_get_definition_by_name() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        let retrieved = registry.get_definition("test");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "test");
    }

    #[test]
    fn test_get_definition_by_alias() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("hello", vec!["hi"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        let retrieved = registry.get_definition("hi");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "hello");
    }

    #[test]
    fn test_get_definition_unknown() {
        let registry = CommandRegistry::new();
        assert!(registry.get_definition("unknown").is_none());
    }

    // Get handler tests
    #[test]
    fn test_get_handler_by_name() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        let handler = registry.get_handler_sync("test");
        assert!(handler.is_some());
    }

    #[test]
    fn test_get_handler_sync_by_name() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        let handler = registry.get_handler_sync("test");
        assert!(handler.is_some());
    }

    #[test]
    fn test_get_handler_by_alias() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("hello", vec!["hi"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        let handler = registry.get_handler_sync("hi");
        assert!(handler.is_some());
    }

    #[test]
    fn test_get_handler_unknown() {
        let registry = CommandRegistry::new();
        assert!(registry.get_handler_sync("unknown").is_none());
    }

    // List commands tests
    #[test]
    fn test_list_commands_empty() {
        let registry = CommandRegistry::new();
        let commands = registry.list_commands();
        assert_eq!(commands.len(), 0);
    }

    #[test]
    fn test_list_commands_multiple() {
        let mut registry = CommandRegistry::new();

        registry
            .register_sync(
                create_test_definition("cmd1", vec![]),
                Box::new(TestHandler),
            )
            .unwrap();
        registry
            .register_sync(
                create_test_definition("cmd2", vec![]),
                Box::new(TestHandler),
            )
            .unwrap();
        registry
            .register_sync(
                create_test_definition("cmd3", vec![]),
                Box::new(TestHandler),
            )
            .unwrap();

        let commands = registry.list_commands();
        assert_eq!(commands.len(), 3);

        let names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
        assert!(names.contains(&"cmd1"));
        assert!(names.contains(&"cmd2"));
        assert!(names.contains(&"cmd3"));
    }

    // Integration tests
    #[test]
    fn test_complete_workflow() {
        let mut registry = CommandRegistry::new();

        // Register multiple commands with aliases
        let def1 = create_test_definition("simulate", vec!["sim", "run"]);
        let def2 = create_test_definition("validate", vec!["val", "check"]);
        let def3 = create_test_definition("help", vec!["h", "?"]);

        registry.register_sync(def1, Box::new(TestHandler)).unwrap();
        registry.register_sync(def2, Box::new(TestHandler)).unwrap();
        registry.register_sync(def3, Box::new(TestHandler)).unwrap();

        // Verify registry state
        assert_eq!(registry.len(), 3);

        // Verify all names resolve correctly
        assert_eq!(registry.resolve_name("simulate"), Some("simulate"));
        assert_eq!(registry.resolve_name("sim"), Some("simulate"));
        assert_eq!(registry.resolve_name("validate"), Some("validate"));
        assert_eq!(registry.resolve_name("val"), Some("validate"));

        // Verify handlers are accessible
        assert!(registry.get_handler_sync("simulate").is_some());
        assert!(registry.get_handler_sync("sim").is_some());
        assert!(registry.get_handler_sync("h").is_some());

        // Verify definitions are accessible
        let sim_def = registry.get_definition("sim");
        assert!(sim_def.is_some());
        assert_eq!(sim_def.unwrap().name, "simulate");
    }

    #[test]
    fn test_default_trait() {
        let registry: CommandRegistry = Default::default();
        assert!(registry.is_empty());
    }

    #[test]
    fn test_contains_method() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec!["t"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        assert!(registry.contains("test"));
        assert!(registry.contains("t"));
        assert!(!registry.contains("unknown"));
    }

    #[test]
    fn test_multiple_aliases_same_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("command", vec!["c", "cmd", "com"]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        // All aliases should resolve to the same command
        assert_eq!(registry.resolve_name("c"), Some("command"));
        assert_eq!(registry.resolve_name("cmd"), Some("command"));
        assert_eq!(registry.resolve_name("com"), Some("command"));

        // All should return the same handler
        let handler1 = registry.get_handler_sync("c");
        let handler2 = registry.get_handler_sync("cmd");
        assert!(handler1.is_some());
        assert!(handler2.is_some());
    }

    #[test]
    fn test_case_sensitivity() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("Test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        // Case matters
        assert!(registry.contains("Test"));
        assert!(!registry.contains("test"));
        assert!(!registry.contains("TEST"));
    }

    #[test]
    fn test_empty_alias_list() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        let result = registry.register_sync(definition, Box::new(TestHandler));

        assert!(result.is_ok());
        assert!(registry.contains("test"));
    }

    // ============================================================================
    // AsyncCommandHandler / register_async / get_handler_async TESTS (DD-022)
    // ============================================================================

    #[test]
    fn test_register_async_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("fetch", vec![]);

        let result = registry.register_async(definition, Box::new(TestAsyncHandler));

        assert!(result.is_ok());
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_register_async_command_with_aliases() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("fetch", vec!["f", "get-remote"]);

        registry
            .register_async(definition, Box::new(TestAsyncHandler))
            .unwrap();

        assert!(registry.contains("fetch"));
        assert!(registry.contains("f"));
        assert!(registry.contains("get-remote"));
        assert_eq!(registry.resolve_name("f"), Some("fetch"));
    }

    #[test]
    fn test_get_handler_async_by_name_and_alias() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("fetch", vec!["f"]);

        registry
            .register_async(definition, Box::new(TestAsyncHandler))
            .unwrap();

        assert!(registry.get_handler_async("fetch").is_some());
        assert!(registry.get_handler_async("f").is_some());
        assert!(registry.get_handler_async("unknown").is_none());
    }

    /// The core cross-accessor guarantee DD-022 depends on: querying an
    /// async-registered command through the *sync* accessor returns `None`
    /// (not the wrong handler, not a panic) — dispatch sites rely on this
    /// to fall through from `get_handler_sync` to `get_handler_async`.
    #[test]
    fn test_sync_accessor_returns_none_for_async_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("fetch", vec![]);

        registry
            .register_async(definition, Box::new(TestAsyncHandler))
            .unwrap();

        assert!(registry.get_handler_sync("fetch").is_none());
        assert!(registry.get_handler_async("fetch").is_some());
    }

    /// Symmetric case: querying a sync-registered command through the
    /// *async* accessor returns `None`.
    #[test]
    fn test_async_accessor_returns_none_for_sync_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("test", vec![]);

        registry
            .register_sync(definition, Box::new(TestHandler))
            .unwrap();

        assert!(registry.get_handler_async("test").is_none());
        assert!(registry.get_handler_sync("test").is_some());
    }

    /// A command name already taken by a sync handler must be rejected for
    /// async registration — the unified storage means one name, one kind.
    #[test]
    fn test_register_async_conflicts_with_existing_sync_name() {
        let mut registry = CommandRegistry::new();
        let sync_def = create_test_definition("dual", vec![]);
        let async_def = create_test_definition("dual", vec![]);

        registry
            .register_sync(sync_def, Box::new(TestHandler))
            .unwrap();
        let result = registry.register_async(async_def, Box::new(TestAsyncHandler));

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Registry(RegistryError::DuplicateRegistration {
                name,
                ..
            }) => {
                assert_eq!(name, "dual");
            }
            other => panic!("Expected DuplicateRegistration, got: {:?}", other),
        }
    }

    /// Symmetric case: a name already taken by an async handler must be
    /// rejected for sync registration.
    #[test]
    fn test_register_sync_conflicts_with_existing_async_name() {
        let mut registry = CommandRegistry::new();
        let async_def = create_test_definition("dual", vec![]);
        let sync_def = create_test_definition("dual", vec![]);

        registry
            .register_async(async_def, Box::new(TestAsyncHandler))
            .unwrap();
        let result = registry.register_sync(sync_def, Box::new(TestHandler));

        assert!(result.is_err());
    }

    /// An async command's alias must not collide with an existing sync
    /// command's alias, and vice versa — conflict detection is shared
    /// across both kinds via `check_name_available`.
    #[test]
    fn test_async_alias_conflicts_with_sync_alias() {
        let mut registry = CommandRegistry::new();
        let sync_def = create_test_definition("cmd1", vec!["shared"]);
        let async_def = create_test_definition("cmd2", vec!["shared"]);

        registry
            .register_sync(sync_def, Box::new(TestHandler))
            .unwrap();
        let result = registry.register_async(async_def, Box::new(TestAsyncHandler));

        assert!(result.is_err());
    }

    #[test]
    fn test_get_definition_works_for_async_command() {
        let mut registry = CommandRegistry::new();
        let definition = create_test_definition("fetch", vec!["f"]);

        registry
            .register_async(definition, Box::new(TestAsyncHandler))
            .unwrap();

        let retrieved = registry.get_definition("f");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "fetch");
    }

    #[test]
    fn test_list_commands_includes_both_sync_and_async() {
        let mut registry = CommandRegistry::new();

        registry
            .register_sync(
                create_test_definition("sync-cmd", vec![]),
                Box::new(TestHandler),
            )
            .unwrap();
        registry
            .register_async(
                create_test_definition("async-cmd", vec![]),
                Box::new(TestAsyncHandler),
            )
            .unwrap();

        let commands = registry.list_commands();
        assert_eq!(commands.len(), 2);
        let names: Vec<&str> = commands.iter().map(|c| c.name.as_str()).collect();
        assert!(names.contains(&"sync-cmd"));
        assert!(names.contains(&"async-cmd"));
    }

    #[test]
    fn test_mixed_registry_workflow() {
        // End-to-end: a registry with both sync and async commands behaves
        // consistently across resolve_name / get_definition / len / contains.
        let mut registry = CommandRegistry::new();

        registry
            .register_sync(
                create_test_definition("simulate", vec!["sim"]),
                Box::new(TestHandler),
            )
            .unwrap();
        registry
            .register_async(
                create_test_definition("fetch", vec!["f"]),
                Box::new(TestAsyncHandler),
            )
            .unwrap();

        assert_eq!(registry.len(), 2);
        assert!(registry.contains("sim"));
        assert!(registry.contains("f"));

        assert!(registry.get_handler_sync("simulate").is_some());
        assert!(registry.get_handler_async("fetch").is_some());
        assert!(registry.get_handler_sync("fetch").is_none());
        assert!(registry.get_handler_async("simulate").is_none());
    }
}