argot-cmd 0.2.0

An agent-first command interface framework for Rust
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
//! Central command registry with lookup and search operations.
//!
//! [`Registry`] is the primary store for the command tree in an argot
//! application. It owns a `Vec<Command>` and exposes several query methods:
//!
//! - **[`Registry::get_command`]** — exact lookup by canonical name.
//! - **[`Registry::get_subcommand`]** — walk a path of canonical names into
//!   the nested subcommand tree.
//! - **[`Registry::list_commands`]** — iterate all top-level commands.
//! - **[`Registry::search`]** — case-insensitive substring search across
//!   canonical name, summary, and description.
//! - **[`Registry::fuzzy_search`]** — fuzzy (skim) search returning results
//!   sorted by score (best match first). Requires the `fuzzy` feature.
//! - **[`Registry::to_json`]** — serialize the command tree to pretty-printed
//!   JSON (handler closures are excluded).
//!
//! Pass `registry.commands()` to [`crate::Parser::new`] to wire the registry
//! into the parsing pipeline.
//!
//! # Example
//!
//! ```
//! # use argot_cmd::{Command, Registry};
//! let registry = Registry::new(vec![
//!     Command::builder("list").summary("List all items").build().unwrap(),
//!     Command::builder("get").summary("Get a single item").build().unwrap(),
//! ]);
//!
//! assert!(registry.get_command("list").is_some());
//! assert_eq!(registry.search("item").len(), 2);
//! ```

#[cfg(feature = "fuzzy")]
use fuzzy_matcher::skim::SkimMatcherV2;
#[cfg(feature = "fuzzy")]
use fuzzy_matcher::FuzzyMatcher;
use thiserror::Error;

use crate::model::{Command, Example};

/// A command paired with its canonical path from the registry root.
///
/// Produced by [`Registry::iter_all_recursive`].
#[derive(Debug, Clone)]
pub struct CommandEntry<'a> {
    /// Canonical names from root to this command, e.g. `["remote", "add"]`.
    pub path: Vec<String>,
    /// The command at this path.
    pub command: &'a Command,
}

impl<'a> CommandEntry<'a> {
    /// The canonical name of this command (last element of `path`).
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("remote")
    ///         .subcommand(Command::builder("add").build().unwrap())
    ///         .build()
    ///         .unwrap(),
    /// ]);
    /// let entries = registry.iter_all_recursive();
    /// assert_eq!(entries[0].name(), "remote");
    /// assert_eq!(entries[1].name(), "add");
    /// ```
    pub fn name(&self) -> &str {
        self.path.last().map(String::as_str).unwrap_or("")
    }

    /// The full dotted path string, e.g. `"remote.add"`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("remote")
    ///         .subcommand(Command::builder("add").build().unwrap())
    ///         .build()
    ///         .unwrap(),
    /// ]);
    /// let entries = registry.iter_all_recursive();
    /// assert_eq!(entries[0].path_str(), "remote");
    /// assert_eq!(entries[1].path_str(), "remote.add");
    /// ```
    pub fn path_str(&self) -> String {
        self.path.join(".")
    }
}

/// Errors produced by [`Registry`] methods.
#[derive(Debug, Error)]
pub enum QueryError {
    /// JSON serialization failed.
    ///
    /// Wraps the underlying [`serde_json::Error`].
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
}

/// Owns the registered command tree and provides query/search operations.
///
/// Create a `Registry` with [`Registry::new`], passing the fully-built list of
/// top-level commands. The registry takes ownership of the command list and
/// makes it available through a variety of lookup and search methods.
///
/// # Examples
///
/// ```
/// # use argot_cmd::{Command, Registry};
/// let registry = Registry::new(vec![
///     Command::builder("deploy").summary("Deploy the app").build().unwrap(),
/// ]);
///
/// let cmd = registry.get_command("deploy").unwrap();
/// assert_eq!(cmd.summary, "Deploy the app");
/// ```
pub struct Registry {
    commands: Vec<Command>,
}

impl Registry {
    /// Create a new `Registry` owning the given command list.
    ///
    /// # Arguments
    ///
    /// - `commands` — The top-level command list. Subcommands are nested
    ///   inside the respective [`Command::subcommands`] fields.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("run").build().unwrap(),
    /// ]);
    /// assert_eq!(registry.list_commands().len(), 1);
    /// ```
    pub fn new(commands: Vec<Command>) -> Self {
        Self { commands }
    }

    /// Append a command to the registry.
    ///
    /// Used internally by [`crate::Cli::with_query_support`] to inject the
    /// built-in `query` meta-command.
    pub(crate) fn push(&mut self, cmd: Command) {
        self.commands.push(cmd);
    }

    /// Borrow the raw command slice (useful for constructing a [`Parser`][crate::parser::Parser]).
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry, Parser};
    /// let registry = Registry::new(vec![Command::builder("ping").build().unwrap()]);
    /// let parser = Parser::new(registry.commands());
    /// let parsed = parser.parse(&["ping"]).unwrap();
    /// assert_eq!(parsed.command.canonical, "ping");
    /// ```
    pub fn commands(&self) -> &[Command] {
        &self.commands
    }

    /// Return references to all top-level commands.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("a").build().unwrap(),
    ///     Command::builder("b").build().unwrap(),
    /// ]);
    /// assert_eq!(registry.list_commands().len(), 2);
    /// ```
    pub fn list_commands(&self) -> Vec<&Command> {
        self.commands.iter().collect()
    }

    /// Look up a top-level command by its exact canonical name.
    ///
    /// Returns `None` if no command with that canonical name exists. Does not
    /// match aliases or spellings — use [`crate::Resolver`] for fuzzy/prefix
    /// matching.
    ///
    /// # Arguments
    ///
    /// - `canonical` — The exact canonical name to look up.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy").alias("d").build().unwrap(),
    /// ]);
    ///
    /// assert!(registry.get_command("deploy").is_some());
    /// assert!(registry.get_command("d").is_none()); // alias, not canonical
    /// ```
    pub fn get_command(&self, canonical: &str) -> Option<&Command> {
        self.commands.iter().find(|c| c.canonical == canonical)
    }

    /// Walk a path of canonical names into the subcommand tree.
    ///
    /// `path = &["remote", "add"]` returns the `add` subcommand of `remote`.
    /// Each path segment must be an *exact canonical* name at that level of
    /// the tree.
    ///
    /// Returns `None` if any segment fails to match or if `path` is empty.
    ///
    /// # Arguments
    ///
    /// - `path` — Ordered slice of canonical command names from top-level down.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("remote")
    ///         .subcommand(Command::builder("add").build().unwrap())
    ///         .build()
    ///         .unwrap(),
    /// ]);
    ///
    /// let sub = registry.get_subcommand(&["remote", "add"]).unwrap();
    /// assert_eq!(sub.canonical, "add");
    ///
    /// assert!(registry.get_subcommand(&[]).is_none());
    /// assert!(registry.get_subcommand(&["remote", "nope"]).is_none());
    /// ```
    pub fn get_subcommand(&self, path: &[&str]) -> Option<&Command> {
        if path.is_empty() {
            return None;
        }
        let mut current = self.get_command(path[0])?;
        for &segment in &path[1..] {
            current = current
                .subcommands
                .iter()
                .find(|c| c.canonical == segment)?;
        }
        Some(current)
    }

    /// Return the examples slice for a top-level command, or `None` if the
    /// command does not exist.
    ///
    /// An empty examples list returns `Some(&[])`.
    ///
    /// # Arguments
    ///
    /// - `canonical` — The exact canonical name of the command.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Example, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("run")
    ///         .example(Example::new("basic run", "myapp run"))
    ///         .build()
    ///         .unwrap(),
    /// ]);
    ///
    /// assert_eq!(registry.get_examples("run").unwrap().len(), 1);
    /// assert!(registry.get_examples("missing").is_none());
    /// ```
    pub fn get_examples(&self, canonical: &str) -> Option<&[Example]> {
        self.get_command(canonical).map(|c| c.examples.as_slice())
    }

    /// Substring search across canonical name, summary, and description.
    ///
    /// The search is case-insensitive. Returns all top-level commands for
    /// which the query appears in at least one of the three text fields.
    ///
    /// # Arguments
    ///
    /// - `query` — The substring to search for (case-insensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("list").summary("List all records").build().unwrap(),
    ///     Command::builder("get").summary("Get a single record").build().unwrap(),
    /// ]);
    ///
    /// let results = registry.search("record");
    /// assert_eq!(results.len(), 2);
    /// assert!(registry.search("zzz").is_empty());
    /// ```
    pub fn search(&self, query: &str) -> Vec<&Command> {
        let q = query.to_lowercase();
        self.commands
            .iter()
            .filter(|c| {
                c.canonical.to_lowercase().contains(&q)
                    || c.summary.to_lowercase().contains(&q)
                    || c.description.to_lowercase().contains(&q)
            })
            .collect()
    }

    /// Fuzzy search across canonical name, summary, and description.
    ///
    /// Uses the skim fuzzy-matching algorithm (requires the `fuzzy` feature).
    /// Returns matches sorted descending by score (best match first).
    /// Commands that produce no fuzzy match are excluded.
    ///
    /// # Arguments
    ///
    /// - `query` — The fuzzy query string.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "fuzzy")] {
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy").summary("Deploy a service").build().unwrap(),
    ///     Command::builder("delete").summary("Delete a resource").build().unwrap(),
    ///     Command::builder("describe").summary("Describe a resource").build().unwrap(),
    /// ]);
    ///
    /// // Fuzzy-matches all commands starting with 'de'
    /// let results = registry.fuzzy_search("dep");
    /// assert!(!results.is_empty());
    /// // Results are sorted by match score descending
    /// assert_eq!(results[0].0.canonical, "deploy");
    /// // Scores are positive integers — higher is a better match
    /// assert!(results[0].1 > 0);
    /// # }
    /// ```
    #[cfg(feature = "fuzzy")]
    pub fn fuzzy_search(&self, query: &str) -> Vec<(&Command, i64)> {
        let matcher = SkimMatcherV2::default();
        let mut results: Vec<(&Command, i64)> = self
            .commands
            .iter()
            .filter_map(|cmd| {
                let text = format!("{} {} {}", cmd.canonical, cmd.summary, cmd.description);
                matcher.fuzzy_match(&text, query).map(|score| (cmd, score))
            })
            .collect();
        results.sort_by(|a, b| b.1.cmp(&a.1));
        results
    }

    /// Match commands by natural-language intent phrase.
    ///
    /// Scores each command by how many words from `phrase` appear in its
    /// combined text (canonical name, aliases, semantic aliases, summary,
    /// description). Returns matches sorted by score descending.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy")
    ///         .summary("Deploy a service to an environment")
    ///         .semantic_alias("release to production")
    ///         .semantic_alias("push to environment")
    ///         .build().unwrap(),
    ///     Command::builder("status")
    ///         .summary("Check service status")
    ///         .build().unwrap(),
    /// ]);
    ///
    /// let results = registry.match_intent("deploy to production");
    /// assert!(!results.is_empty());
    /// assert_eq!(results[0].0.canonical, "deploy");
    /// ```
    pub fn match_intent(&self, phrase: &str) -> Vec<(&Command, u32)> {
        let phrase_lower = phrase.to_lowercase();
        let words: Vec<&str> = phrase_lower
            .split_whitespace()
            .filter(|w| !w.is_empty())
            .collect();

        if words.is_empty() {
            return vec![];
        }

        let mut results: Vec<(&Command, u32)> = self
            .commands
            .iter()
            .filter_map(|cmd| {
                let combined = format!(
                    "{} {} {} {} {}",
                    cmd.canonical.to_lowercase(),
                    cmd.aliases
                        .iter()
                        .map(|s| s.to_lowercase())
                        .collect::<Vec<_>>()
                        .join(" "),
                    cmd.semantic_aliases
                        .iter()
                        .map(|s| s.to_lowercase())
                        .collect::<Vec<_>>()
                        .join(" "),
                    cmd.summary.to_lowercase(),
                    cmd.description.to_lowercase(),
                );
                let score = words.iter().filter(|&&w| combined.contains(w)).count() as u32;
                if score > 0 {
                    Some((cmd, score))
                } else {
                    None
                }
            })
            .collect();

        results.sort_by(|a, b| b.1.cmp(&a.1));
        results
    }

    /// Serialize the entire command tree to a pretty-printed JSON string.
    ///
    /// Handler closures are excluded from the output (they are skipped by the
    /// `serde` configuration on [`Command`]).
    ///
    /// # Errors
    ///
    /// Returns [`QueryError::Serialization`] if `serde_json` fails (in
    /// practice this should not happen for well-formed command trees).
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy").summary("Deploy").build().unwrap(),
    /// ]);
    ///
    /// let json = registry.to_json().unwrap();
    /// assert!(json.contains("deploy"));
    /// ```
    pub fn to_json(&self) -> Result<String, QueryError> {
        serde_json::to_string_pretty(&self.commands).map_err(QueryError::Serialization)
    }

    /// Serialize the entire command tree to a pretty-printed JSON string,
    /// filtering each command object to only include the requested top-level
    /// fields.
    ///
    /// Each command object (including nested subcommands at any depth) is
    /// filtered so that only keys listed in `fields` are retained. The
    /// `subcommands` key is always walked recursively even if it is not in
    /// `fields`; its entries are filtered before being emitted.
    ///
    /// If `fields` is empty the method falls back to the same output as
    /// [`Registry::to_json`].
    ///
    /// Field names that do not exist in the serialized command are silently
    /// ignored (no error is returned for missing fields).
    ///
    /// Valid field names correspond to the top-level keys of the serialized
    /// [`Command`] object: `canonical`, `aliases`, `spellings`,
    /// `semantic_aliases`, `summary`, `description`, `arguments`, `flags`,
    /// `examples`, `best_practices`, `anti_patterns`, `subcommands`, `meta`,
    /// `mutating`, etc.
    ///
    /// # Errors
    ///
    /// Returns [`QueryError::Serialization`] if `serde_json` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy")
    ///         .summary("Deploy the app")
    ///         .build()
    ///         .unwrap(),
    /// ]);
    ///
    /// let json = registry.to_json_with_fields(&["canonical", "summary"]).unwrap();
    /// let v: serde_json::Value = serde_json::from_str(&json).unwrap();
    /// let obj = &v[0];
    /// assert_eq!(obj["canonical"], "deploy");
    /// assert_eq!(obj["summary"], "Deploy the app");
    /// // fields not requested are absent
    /// assert!(obj.get("examples").is_none());
    /// ```
    pub fn to_json_with_fields(&self, fields: &[&str]) -> Result<String, QueryError> {
        if fields.is_empty() {
            return self.to_json();
        }
        let value = serde_json::to_value(&self.commands).map_err(QueryError::Serialization)?;
        let filtered = filter_commands_value(value, fields);
        serde_json::to_string_pretty(&filtered).map_err(QueryError::Serialization)
    }

    /// Serialize the command tree as NDJSON (one compact JSON object per line).
    ///
    /// Commands are emitted depth-first using [`Registry::iter_all_recursive`].
    /// Each line is a single, self-contained JSON object representing one
    /// command (handler closures excluded). Subcommands appear as their own
    /// lines rather than being nested inside their parent, which lets agents
    /// process the registry incrementally without buffering the entire tree.
    ///
    /// An empty registry returns an empty string (no trailing newline).
    /// A non-empty registry ends with a trailing newline.
    ///
    /// # Errors
    ///
    /// Returns [`QueryError::Serialization`] if serialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("remote")
    ///         .subcommand(Command::builder("add").build().unwrap())
    ///         .build()
    ///         .unwrap(),
    /// ]);
    ///
    /// let ndjson = registry.to_ndjson().unwrap();
    /// let lines: Vec<&str> = ndjson.trim_end_matches('\n').split('\n').collect();
    /// assert_eq!(lines.len(), 2); // "remote" + "remote add"
    /// // Every line must be valid JSON.
    /// for line in &lines {
    ///     assert!(serde_json::from_str::<serde_json::Value>(line).is_ok());
    /// }
    /// ```
    pub fn to_ndjson(&self) -> Result<String, QueryError> {
        self.to_ndjson_with_fields(&[])
    }

    /// Serialize the command tree as NDJSON, filtering each object to the
    /// given field names.
    ///
    /// Behaves identically to [`Registry::to_ndjson`] except that each JSON
    /// object is filtered to include only the keys listed in `fields`. When
    /// `fields` is empty, all fields are included (equivalent to
    /// [`Registry::to_ndjson`]).
    ///
    /// # Arguments
    ///
    /// - `fields` — Field names to keep in each output object. Pass `&[]` to
    ///   include all fields.
    ///
    /// # Errors
    ///
    /// Returns [`QueryError::Serialization`] if serialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("deploy").summary("Deploy the app").build().unwrap(),
    /// ]);
    ///
    /// let ndjson = registry.to_ndjson_with_fields(&["canonical", "summary"]).unwrap();
    /// let val: serde_json::Value = serde_json::from_str(ndjson.trim_end_matches('\n')).unwrap();
    /// assert!(val.get("canonical").is_some());
    /// assert!(val.get("summary").is_some());
    /// assert!(val.get("description").is_none());
    /// ```
    pub fn to_ndjson_with_fields(&self, fields: &[&str]) -> Result<String, QueryError> {
        let entries = self.iter_all_recursive();
        if entries.is_empty() {
            return Ok(String::new());
        }
        let mut lines = Vec::with_capacity(entries.len());
        for entry in &entries {
            let line = command_to_ndjson_with_fields(entry.command, fields)?;
            lines.push(line);
        }
        let mut output = lines.join("\n");
        output.push('\n');
        Ok(output)
    }

    /// Iterate over every command in the tree depth-first, including all
    /// nested subcommands at any depth.
    ///
    /// Each entry carries the [`CommandEntry::path`] (canonical names from the
    /// registry root to the command) and a reference to the [`Command`].
    ///
    /// Commands are yielded in depth-first order: a parent command appears
    /// immediately before all of its descendants. Within each level, commands
    /// appear in registration order.
    ///
    /// # Examples
    ///
    /// ```
    /// # use argot_cmd::{Command, Registry};
    /// let registry = Registry::new(vec![
    ///     Command::builder("remote")
    ///         .subcommand(Command::builder("add").build().unwrap())
    ///         .subcommand(Command::builder("remove").build().unwrap())
    ///         .build()
    ///         .unwrap(),
    ///     Command::builder("status").build().unwrap(),
    /// ]);
    ///
    /// let all: Vec<_> = registry.iter_all_recursive();
    /// let names: Vec<String> = all.iter().map(|e| e.path_str()).collect();
    ///
    /// assert_eq!(names, ["remote", "remote.add", "remote.remove", "status"]);
    /// ```
    pub fn iter_all_recursive(&self) -> Vec<CommandEntry<'_>> {
        let mut out = Vec::new();
        for cmd in &self.commands {
            collect_recursive(cmd, vec![], &mut out);
        }
        out
    }
}

/// Serialize a single [`Command`] to a pretty-printed JSON string, filtering
/// the output to only include the requested top-level fields.
///
/// Behaves like [`Registry::to_json_with_fields`] but for a single command
/// rather than the whole registry.
///
/// If `fields` is empty the method serializes the full command (equivalent to
/// `serde_json::to_string_pretty(cmd)`).
///
/// # Errors
///
/// Returns [`QueryError::Serialization`] if `serde_json` fails.
///
/// # Examples
///
/// ```
/// # use argot_cmd::{Command, Registry};
/// # use argot_cmd::query::command_to_json_with_fields;
/// let cmd = Command::builder("deploy")
///     .summary("Deploy the app")
///     .build()
///     .unwrap();
///
/// let json = command_to_json_with_fields(&cmd, &["canonical", "summary"]).unwrap();
/// let v: serde_json::Value = serde_json::from_str(&json).unwrap();
/// assert_eq!(v["canonical"], "deploy");
/// assert_eq!(v["summary"], "Deploy the app");
/// assert!(v.get("examples").is_none());
/// ```
pub fn command_to_json_with_fields(cmd: &Command, fields: &[&str]) -> Result<String, QueryError> {
    if fields.is_empty() {
        return serde_json::to_string_pretty(cmd).map_err(QueryError::Serialization);
    }
    let value = serde_json::to_value(cmd).map_err(QueryError::Serialization)?;
    let filtered = filter_command_object(value, fields);
    serde_json::to_string_pretty(&filtered).map_err(QueryError::Serialization)
}

/// Filter a JSON array of command objects to only include the requested fields
/// in each entry.
fn filter_commands_value(value: serde_json::Value, fields: &[&str]) -> serde_json::Value {
    match value {
        serde_json::Value::Array(arr) => {
            serde_json::Value::Array(
                arr.into_iter()
                    .map(|v| filter_command_object(v, fields))
                    .collect(),
            )
        }
        other => other,
    }
}

/// Filter a single command JSON object to only include the requested fields.
///
/// The `subcommands` value (if present and requested) has its entries
/// recursively filtered as well.
fn filter_command_object(value: serde_json::Value, fields: &[&str]) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => {
            let mut out = serde_json::Map::new();
            for field in fields {
                if let Some(v) = map.get(*field) {
                    // If this field is `subcommands`, recursively filter its entries.
                    let filtered_v = if *field == "subcommands" {
                        filter_commands_value(v.clone(), fields)
                    } else {
                        v.clone()
                    };
                    out.insert((*field).to_owned(), filtered_v);
                }
            }
            serde_json::Value::Object(out)
        }
        other => other,
    }
}

fn collect_recursive<'a>(cmd: &'a Command, mut path: Vec<String>, out: &mut Vec<CommandEntry<'a>>) {
    path.push(cmd.canonical.clone());
    out.push(CommandEntry {
        path: path.clone(),
        command: cmd,
    });
    for sub in &cmd.subcommands {
        collect_recursive(sub, path.clone(), out);
    }
}

/// Serialize a single [`Command`] to a compact (single-line) JSON string.
///
/// The output contains no trailing newline. Handler closures are excluded.
/// This is the single-command companion to [`Registry::to_ndjson`].
///
/// # Errors
///
/// Returns [`QueryError::Serialization`] if serialization fails.
///
/// # Examples
///
/// ```
/// # use argot_cmd::{Command, command_to_ndjson};
/// let cmd = Command::builder("deploy").summary("Deploy").build().unwrap();
/// let line = command_to_ndjson(&cmd).unwrap();
/// // No trailing newline.
/// assert!(!line.ends_with('\n'));
/// // Must be valid compact JSON on one line.
/// assert!(!line.contains('\n'));
/// let val: serde_json::Value = serde_json::from_str(&line).unwrap();
/// assert_eq!(val["canonical"], "deploy");
/// ```
pub fn command_to_ndjson(cmd: &Command) -> Result<String, QueryError> {
    command_to_ndjson_with_fields(cmd, &[])
}

/// Internal helper: serialize a command to compact JSON, optionally filtering
/// to the given set of field names. When `fields` is empty all fields are kept.
fn command_to_ndjson_with_fields(cmd: &Command, fields: &[&str]) -> Result<String, QueryError> {
    let mut value = serde_json::to_value(cmd).map_err(QueryError::Serialization)?;
    if !fields.is_empty() {
        if let serde_json::Value::Object(ref mut map) = value {
            let keys_to_remove: Vec<String> = map
                .keys()
                .filter(|k| !fields.contains(&k.as_str()))
                .cloned()
                .collect();
            for key in keys_to_remove {
                map.remove(&key);
            }
        }
    }
    serde_json::to_string(&value).map_err(QueryError::Serialization)
}

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

    fn registry() -> Registry {
        let sub = Command::builder("push")
            .summary("Push changes")
            .build()
            .unwrap();
        let remote = Command::builder("remote")
            .summary("Manage remotes")
            .subcommand(sub)
            .build()
            .unwrap();
        let list = Command::builder("list")
            .summary("List all items in the store")
            .build()
            .unwrap();
        Registry::new(vec![remote, list])
    }

    #[test]
    fn test_list_commands() {
        let r = registry();
        let cmds = r.list_commands();
        assert_eq!(cmds.len(), 2);
    }

    #[test]
    fn test_get_command() {
        let r = registry();
        assert!(r.get_command("remote").is_some());
        assert!(r.get_command("missing").is_none());
    }

    #[test]
    fn test_get_subcommand() {
        let r = registry();
        assert_eq!(
            r.get_subcommand(&["remote", "push"]).unwrap().canonical,
            "push"
        );
        assert!(r.get_subcommand(&["remote", "nope"]).is_none());
        assert!(r.get_subcommand(&[]).is_none());
    }

    #[test]
    fn test_get_examples_empty() {
        let r = registry();
        assert_eq!(r.get_examples("list"), Some([].as_slice()));
    }

    #[test]
    fn test_search_match() {
        let r = registry();
        let results = r.search("store");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].canonical, "list");
    }

    #[test]
    fn test_search_no_match() {
        let r = registry();
        assert!(r.search("zzz").is_empty());
    }

    #[cfg(feature = "fuzzy")]
    #[test]
    fn test_fuzzy_search_match() {
        let r = registry();
        let results = r.fuzzy_search("lst");
        assert!(!results.is_empty());
        assert!(results.iter().any(|(cmd, _)| cmd.canonical == "list"));
    }

    #[cfg(feature = "fuzzy")]
    #[test]
    fn test_fuzzy_search_no_match() {
        let r = registry();
        assert!(r.fuzzy_search("zzzzz").is_empty());
    }

    #[cfg(feature = "fuzzy")]
    #[test]
    fn test_fuzzy_search_sorted_by_score() {
        let exact = Command::builder("list")
            .summary("List all items")
            .build()
            .unwrap();
        let weak = Command::builder("remote")
            .summary("Manage remotes")
            .build()
            .unwrap();
        let r = Registry::new(vec![weak, exact]);
        let results = r.fuzzy_search("list");
        assert!(!results.is_empty());
        assert_eq!(results[0].0.canonical, "list");
        for window in results.windows(2) {
            assert!(window[0].1 >= window[1].1);
        }
    }

    #[test]
    fn test_to_json() {
        let r = registry();
        let json = r.to_json().unwrap();
        assert!(json.contains("remote"));
        assert!(json.contains("list"));
        let _: serde_json::Value = serde_json::from_str(&json).unwrap();
    }

    // ── NDJSON tests ──────────────────────────────────────────────────────────

    #[test]
    fn test_to_ndjson_empty_registry_returns_empty_string() {
        let r = Registry::new(vec![]);
        let ndjson = r.to_ndjson().unwrap();
        assert_eq!(ndjson, "");
    }

    #[test]
    fn test_to_ndjson_one_line_per_command_including_subcommands() {
        // registry() has: remote (with push subcommand) + list = 3 total entries
        let r = registry();
        let ndjson = r.to_ndjson().unwrap();
        assert!(ndjson.ends_with('\n'), "should end with trailing newline");
        let lines: Vec<&str> = ndjson
            .trim_end_matches('\n')
            .split('\n')
            .filter(|l| !l.is_empty())
            .collect();
        assert_eq!(lines.len(), 3, "remote + push + list = 3 lines, got: {:?}", lines);
    }

    #[test]
    fn test_to_ndjson_each_line_is_valid_json() {
        let r = registry();
        let ndjson = r.to_ndjson().unwrap();
        for line in ndjson.trim_end_matches('\n').split('\n') {
            let result: Result<serde_json::Value, _> = serde_json::from_str(line);
            assert!(result.is_ok(), "line is not valid JSON: {:?}", line);
        }
    }

    #[test]
    fn test_to_ndjson_depth_first_order() {
        let r = registry();
        let ndjson = r.to_ndjson().unwrap();
        let lines: Vec<&str> = ndjson.trim_end_matches('\n').split('\n').collect();
        // depth-first: remote, push (subcommand of remote), list
        let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
        let third: serde_json::Value = serde_json::from_str(lines[2]).unwrap();
        assert_eq!(first["canonical"], "remote");
        assert_eq!(second["canonical"], "push");
        assert_eq!(third["canonical"], "list");
    }

    #[test]
    fn test_to_ndjson_with_fields_filters_correctly() {
        let r = registry();
        let ndjson = r.to_ndjson_with_fields(&["canonical", "summary"]).unwrap();
        for line in ndjson.trim_end_matches('\n').split('\n') {
            let val: serde_json::Value = serde_json::from_str(line).unwrap();
            assert!(val.get("canonical").is_some(), "missing 'canonical' in line: {}", line);
            assert!(val.get("summary").is_some(), "missing 'summary' in line: {}", line);
            assert!(
                val.get("description").is_none(),
                "'description' should be filtered out: {}",
                line
            );
            assert!(
                val.get("examples").is_none(),
                "'examples' should be filtered out: {}",
                line
            );
        }
    }

    #[test]
    fn test_to_ndjson_with_empty_fields_includes_all() {
        let r = registry();
        let ndjson_all = r.to_ndjson().unwrap();
        let ndjson_empty_fields = r.to_ndjson_with_fields(&[]).unwrap();
        assert_eq!(ndjson_all, ndjson_empty_fields);
    }

    #[test]
    fn test_command_to_ndjson_single_compact_line() {
        let cmd = Command::builder("deploy").summary("Deploy").build().unwrap();
        let line = super::command_to_ndjson(&cmd).unwrap();
        assert!(
            !line.ends_with('\n'),
            "command_to_ndjson should have no trailing newline"
        );
        assert!(
            !line.contains('\n'),
            "command_to_ndjson should be a single line"
        );
        let val: serde_json::Value = serde_json::from_str(&line).unwrap();
        assert_eq!(val["canonical"], "deploy");
        assert_eq!(val["summary"], "Deploy");
    }

    #[test]
    fn test_command_to_ndjson_compact_not_pretty() {
        let cmd = Command::builder("run").build().unwrap();
        let line = super::command_to_ndjson(&cmd).unwrap();
        // Compact JSON has no newlines and is not pretty-printed.
        assert!(!line.contains('\n'));
        // Compact JSON should not have extra whitespace after colons (serde_json compact).
        assert!(!line.contains(": "), "should be compact, not pretty-printed");
    }

    #[test]
    fn test_to_json_with_fields_filters_keys() {
        let r = Registry::new(vec![
            Command::builder("deploy")
                .summary("Deploy the app")
                .description("Deploys to production")
                .build()
                .unwrap(),
        ]);
        let json = r.to_json_with_fields(&["canonical", "summary"]).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let obj = &v[0];
        assert_eq!(obj["canonical"], "deploy");
        assert_eq!(obj["summary"], "Deploy the app");
        // fields not in the filter must be absent
        assert!(obj.get("description").is_none());
        assert!(obj.get("examples").is_none());
        assert!(obj.get("aliases").is_none());
    }

    #[test]
    fn test_to_json_with_fields_empty_falls_back_to_full() {
        let r = Registry::new(vec![
            Command::builder("deploy")
                .summary("Deploy the app")
                .build()
                .unwrap(),
        ]);
        let full = r.to_json().unwrap();
        let filtered = r.to_json_with_fields(&[]).unwrap();
        assert_eq!(full, filtered);
    }

    #[test]
    fn test_to_json_with_fields_missing_field_silently_omitted() {
        let r = Registry::new(vec![
            Command::builder("deploy").build().unwrap(),
        ]);
        // "nonexistent_key" does not exist — should produce an object with only "canonical"
        let json = r
            .to_json_with_fields(&["canonical", "nonexistent_key"])
            .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let obj = &v[0];
        assert_eq!(obj["canonical"], "deploy");
        assert!(obj.get("nonexistent_key").is_none());
    }

    #[test]
    fn test_to_json_with_fields_subcommands_filtered_recursively() {
        let r = Registry::new(vec![
            Command::builder("remote")
                .summary("Manage remotes")
                .subcommand(
                    Command::builder("add")
                        .summary("Add a remote")
                        .description("Detailed add docs")
                        .build()
                        .unwrap(),
                )
                .build()
                .unwrap(),
        ]);
        let json = r
            .to_json_with_fields(&["canonical", "summary", "subcommands"])
            .unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let obj = &v[0];
        assert_eq!(obj["canonical"], "remote");
        assert!(obj.get("description").is_none());
        // subcommands array should be present
        let subs = obj["subcommands"].as_array().unwrap();
        assert_eq!(subs.len(), 1);
        // the subcommand entry should also be filtered
        assert_eq!(subs[0]["canonical"], "add");
        assert_eq!(subs[0]["summary"], "Add a remote");
        assert!(subs[0].get("description").is_none());
    }

    #[test]
    fn test_to_json_with_fields_subcommands_not_requested_absent() {
        let r = Registry::new(vec![
            Command::builder("remote")
                .subcommand(Command::builder("add").build().unwrap())
                .build()
                .unwrap(),
        ]);
        // "subcommands" not in requested fields → key should be absent
        let json = r.to_json_with_fields(&["canonical"]).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let obj = &v[0];
        assert_eq!(obj["canonical"], "remote");
        assert!(obj.get("subcommands").is_none());
    }

    #[test]
    fn test_command_to_json_with_fields() {
        let cmd = Command::builder("deploy")
            .summary("Deploy the app")
            .description("Long description")
            .build()
            .unwrap();
        let json = command_to_json_with_fields(&cmd, &["canonical", "summary"]).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["canonical"], "deploy");
        assert_eq!(v["summary"], "Deploy the app");
        assert!(v.get("description").is_none());
    }

    #[test]
    fn test_command_to_json_with_fields_empty_falls_back_to_full() {
        let cmd = Command::builder("deploy")
            .summary("Deploy the app")
            .build()
            .unwrap();
        let full = serde_json::to_string_pretty(&cmd).unwrap();
        let filtered = command_to_json_with_fields(&cmd, &[]).unwrap();
        assert_eq!(full, filtered);
    }

    #[test]
    fn test_match_intent_single_word() {
        let r = Registry::new(vec![
            Command::builder("deploy")
                .summary("Deploy a service")
                .build()
                .unwrap(),
            Command::builder("status")
                .summary("Check service status")
                .build()
                .unwrap(),
        ]);
        let results = r.match_intent("deploy");
        assert!(!results.is_empty());
        assert_eq!(results[0].0.canonical, "deploy");
    }

    #[test]
    fn test_match_intent_phrase() {
        let r = Registry::new(vec![
            Command::builder("deploy")
                .summary("Deploy a service to an environment")
                .semantic_alias("release to production")
                .semantic_alias("push to environment")
                .build()
                .unwrap(),
            Command::builder("status")
                .summary("Check service status")
                .build()
                .unwrap(),
        ]);
        let results = r.match_intent("release to production");
        assert!(!results.is_empty());
        assert_eq!(results[0].0.canonical, "deploy");
    }

    #[test]
    fn test_match_intent_no_match() {
        let r = Registry::new(vec![Command::builder("deploy")
            .summary("Deploy a service")
            .build()
            .unwrap()]);
        let results = r.match_intent("zzz xyzzy foobar");
        assert!(results.is_empty());
    }

    #[test]
    fn test_match_intent_sorted_by_score() {
        let r = Registry::new(vec![
            Command::builder("status")
                .summary("Check service status")
                .build()
                .unwrap(),
            Command::builder("deploy")
                .summary("Deploy a service to an environment")
                .semantic_alias("release to production")
                .semantic_alias("push to environment")
                .build()
                .unwrap(),
        ]);
        // "deploy to production" matches deploy on "deploy", "to", "production"
        // and matches status only on "to" (if present in summary)
        let results = r.match_intent("deploy to production");
        assert!(!results.is_empty());
        // deploy should score higher than status
        assert_eq!(results[0].0.canonical, "deploy");
        // scores are descending
        for window in results.windows(2) {
            assert!(window[0].1 >= window[1].1);
        }
    }

    #[test]
    fn test_iter_all_recursive_flat() {
        let r = Registry::new(vec![
            Command::builder("a").build().unwrap(),
            Command::builder("b").build().unwrap(),
        ]);
        let entries = r.iter_all_recursive();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].path_str(), "a");
        assert_eq!(entries[1].path_str(), "b");
    }

    #[test]
    fn test_iter_all_recursive_nested() {
        let registry = Registry::new(vec![
            Command::builder("remote")
                .subcommand(Command::builder("add").build().unwrap())
                .subcommand(Command::builder("remove").build().unwrap())
                .build()
                .unwrap(),
            Command::builder("status").build().unwrap(),
        ]);

        let names: Vec<String> = registry
            .iter_all_recursive()
            .iter()
            .map(|e| e.path_str())
            .collect();

        assert_eq!(names, ["remote", "remote.add", "remote.remove", "status"]);
    }

    #[test]
    fn test_iter_all_recursive_deep_nesting() {
        let leaf = Command::builder("blue-green").build().unwrap();
        let mid = Command::builder("strategy")
            .subcommand(leaf)
            .build()
            .unwrap();
        let top = Command::builder("deploy").subcommand(mid).build().unwrap();
        let r = Registry::new(vec![top]);

        let names: Vec<String> = r
            .iter_all_recursive()
            .iter()
            .map(|e| e.path_str())
            .collect();

        assert_eq!(
            names,
            ["deploy", "deploy.strategy", "deploy.strategy.blue-green"]
        );
    }

    #[test]
    fn test_iter_all_recursive_entry_helpers() {
        let registry = Registry::new(vec![Command::builder("remote")
            .subcommand(Command::builder("add").build().unwrap())
            .build()
            .unwrap()]);
        let entries = registry.iter_all_recursive();
        assert_eq!(entries[1].name(), "add");
        assert_eq!(entries[1].path, vec!["remote", "add"]);
        assert_eq!(entries[1].path_str(), "remote.add");
    }

    #[test]
    fn test_iter_all_recursive_empty() {
        let r = Registry::new(vec![]);
        assert!(r.iter_all_recursive().is_empty());
    }
}

#[cfg(test)]
#[cfg(feature = "fuzzy")]
mod fuzzy_tests {
    use super::*;
    use crate::model::Command;

    #[test]
    fn test_fuzzy_search_returns_matches() {
        let r = Registry::new(vec![
            Command::builder("deploy").build().unwrap(),
            Command::builder("delete").build().unwrap(),
            Command::builder("status").build().unwrap(),
        ]);
        let results = r.fuzzy_search("dep");
        assert!(!results.is_empty(), "should find matches for 'dep'");
        // "deploy" should be the top match
        assert_eq!(results[0].0.canonical, "deploy");
    }

    #[test]
    fn test_fuzzy_search_sorted_by_score_descending() {
        let r = Registry::new(vec![
            Command::builder("deploy").build().unwrap(),
            Command::builder("delete").build().unwrap(),
        ]);
        let results = r.fuzzy_search("deploy");
        assert!(!results.is_empty());
        // Scores should be in descending order
        for i in 1..results.len() {
            assert!(
                results[i - 1].1 >= results[i].1,
                "results should be sorted by score desc"
            );
        }
    }

    #[test]
    fn test_fuzzy_search_no_match_returns_empty() {
        let r = Registry::new(vec![Command::builder("run").build().unwrap()]);
        let results = r.fuzzy_search("zzzzzzz");
        // No match should return empty (or very low score filtered out)
        // The fuzzy matcher may return low-score matches, so just verify
        // that "run" is NOT the top result for a nonsense query, or it returns empty
        if !results.is_empty() {
            // If it returns anything, score must be positive
            assert!(results.iter().all(|(_, score)| *score > 0));
        }
    }

    #[test]
    fn test_fuzzy_search_score_type() {
        let r = Registry::new(vec![Command::builder("deploy").build().unwrap()]);
        let results = r.fuzzy_search("deploy");
        assert!(!results.is_empty());
        // Score is i64
        let score: i64 = results[0].1;
        assert!(score > 0);
    }
}