veks-completion 0.25.0

Dynamic shell completion engine for CLI tools
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
// Copyright (c) Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Dynamic shell completion engine for CLI tools.
//!
//! Provides a generic, tree-based completion system that completes one level
//! at a time (no eager subcommand chaining). The caller defines the command
//! tree via [`CommandTree`], and this crate handles:
//!
//! - Walking the tree to find candidates for a given input
//! - Filtering out options already present on the command line
//! - Handling bare `key=value` params alongside `--flag` options
//! - Dynamic option discovery from command-line context (e.g., reading
//!   a workload file to discover its declared parameters)
//! - Generating bash completion scripts
//! - Handling the `_<APP>_COMPLETE=bash` env var callbacks
//!
//! # Usage
//!
//! ```rust,no_run
//! use veks_completion::{CommandTree, Node, complete, print_bash_script, handle_complete_env};
//!
//! let tree = CommandTree::new("myapp")
//!     .command("run", Node::leaf(&["--dry-run", "--threads"]))
//!     .command("check", Node::leaf(&["--all", "--quiet"]))
//!     .group("pipeline", Node::group(vec![
//!         ("compute", Node::group(vec![
//!             ("knn", Node::leaf(&["--base", "--query", "--metric"])),
//!         ])),
//!     ]));
//!
//! // In main():
//! if handle_complete_env("myapp", &tree) {
//!     std::process::exit(0);
//! }
//! ```

use std::collections::BTreeMap;

/// A function that provides dynamic completion values for a specific option.
///
/// Called when the user tabs after an option that has a registered provider.
/// Receives the partial word being typed and the full context of completed
/// words on the command line (excluding the program name and the partial).
/// Heap-allocated, thread-safe closure type so providers can capture
/// data (e.g., a static enum-value list discovered from a
/// `CommandOp::value_completions` map). Function pointers can be
/// promoted to this type via [`ValueProvider::from_fn`] so existing
/// `fn(&str, &[&str]) -> Vec<String>` providers keep working.
pub type ValueProvider = std::sync::Arc<dyn Fn(&str, &[&str]) -> Vec<String> + Send + Sync>;

/// Helper to wrap a `fn`-pointer provider into the closure-typed
/// [`ValueProvider`]. Most existing global providers use plain `fn`
/// pointers and call this when registering.
pub fn fn_provider(f: fn(&str, &[&str]) -> Vec<String>) -> ValueProvider {
    std::sync::Arc::new(f)
}

/// Discovery-tier abstraction symmetric with [`CategoryTag`].
///
/// `veks-completion` doesn't define how many tiers exist or how
/// they're named — each consuming crate decides. Implement
/// `LevelTag` on your own enum to declare a closed set of
/// stratified-completion tiers; commands then return `&'static dyn
/// LevelTag` and the completion engine orders by [`rank`].
///
/// `rank()` is the scalar used by stratified completion (the Nth
/// tab tap reveals everything with `rank <= N`). Lower = more
/// discoverable. Two implementors with the same `rank` are treated
/// as the same tier.
pub trait LevelTag: 'static + Send + Sync + std::fmt::Debug {
    /// Numeric tier; lower values are revealed first by the
    /// stratified-completion tab cycle.
    fn rank(&self) -> u32;

    /// Optional display name (e.g., "primary", "advanced") for
    /// help renderers. Default returns the empty string —
    /// implementors should override for human-friendly listings.
    fn name(&self) -> &'static str { "" }
}

/// Discovery-category abstraction.
///
/// `veks-completion` doesn't define WHICH categories exist — each
/// consuming crate decides. Implement `CategoryTag` on your own
/// enum to declare a closed set of categories specific to your
/// project; commands then return `&'static dyn CategoryTag`
/// references and the completion engine groups by `tag()`.
///
/// Example:
/// ```ignore
/// #[derive(Debug, Clone, Copy)]
/// enum MyCategory { Foo, Bar }
/// impl veks_completion::CategoryTag for MyCategory {
///     fn tag(&self) -> &'static str {
///         match self { Self::Foo => "foo", Self::Bar => "bar" }
///     }
/// }
/// // Static instances per variant for `&'static dyn` returns:
/// static CAT_FOO: MyCategory = MyCategory::Foo;
/// static CAT_BAR: MyCategory = MyCategory::Bar;
/// ```
///
/// `tag()` is the stable, lowercase grouping key. Two implementors
/// returning the same `tag()` are treated as the same group at
/// completion time.
pub trait CategoryTag: 'static + Send + Sync + std::fmt::Debug {
    /// Stable lowercase tag used by completion grouping and help
    /// rendering as the user-visible category name.
    fn tag(&self) -> &'static str;
}

/// A function that provides additional option candidates based on context.
///
/// Called during leaf completion to discover extra `key=` options that
/// aren't statically declared. For example, reading a workload file
/// referenced on the command line and returning its declared parameter
/// names as completable options.
///
/// Receives the partial word being typed and the full context of completed
/// words. Returns additional option names (e.g., `["keyspace=", "table="]`).
pub type DynamicOptionsProvider = fn(partial: &str, context: &[&str]) -> Vec<String>;

/// Default visibility tier when a node doesn't explicitly opt
/// into a higher tier. Tier 1 means "show on the very first
/// tab tap" — preserves the pre-stratification behavior for
/// existing apps that haven't categorized their commands.
pub const DEFAULT_LEVEL: u32 = 1;

/// Errors produced by [`CommandTree::validate`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetadataError {
    /// A registered command lacks a category tag and the tree
    /// was built with [`CommandTree::require_metadata`].
    MissingCategory { command: String },
    /// A registered command lacks an explicit `with_level()`
    /// call and the tree was built with
    /// [`CommandTree::require_metadata`].
    MissingLevel { command: String },
}

impl std::fmt::Display for MetadataError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MetadataError::MissingCategory { command } =>
                write!(f, "command '{command}' is missing a category — call \
                    Node::with_category(...) when registering"),
            MetadataError::MissingLevel { command } =>
                write!(f, "command '{command}' is missing an explicit level — \
                    call Node::with_level(N) when registering"),
        }
    }
}

impl std::error::Error for MetadataError {}

/// A node in the command tree.
///
/// Carries two metadata fields used by stratified
/// (multi-tap) completion:
///
/// - `category` — free-form display tag. Apps can group root
///   commands by category in expanded help / future renderers
///   (e.g. `workloads`, `documentation`, `tools`).
/// - `level` — visibility tier. The Nth tab tap reveals every
///   root-level node with `level <= N`. Default
///   [`DEFAULT_LEVEL`] (= 1) means "always shown from the
///   first tap." Use a higher level (2, 3, …) for
///   less-discoverable commands so the first tap stays focused
///   on a small set the user wants by default.
///
/// Existing callers that didn't set these fields get the
/// pre-existing behavior automatically (everything visible at
/// tap 1, no category metadata).
#[derive(Clone)]
pub enum Node {
    /// A leaf command with option names and optional value providers.
    Leaf {
        options: Vec<String>,
        /// Options that are boolean flags (no value expected).
        flags: std::collections::HashSet<String>,
        /// Dynamic value providers keyed by option name (e.g., "--dataset").
        value_providers: BTreeMap<String, ValueProvider>,
        /// Optional provider that discovers additional options from context.
        dynamic_options: Option<DynamicOptionsProvider>,
        /// Display group tag — see type-level docs for usage.
        category: Option<String>,
        /// Tap-tier visibility — see type-level docs for
        /// usage. `None` means "never explicitly set"; the
        /// effective level resolves to [`DEFAULT_LEVEL`] but
        /// strict-metadata mode treats `None` as missing.
        level: Option<u32>,
    },
    /// A group containing named child nodes.
    Group {
        children: BTreeMap<String, Node>,
        category: Option<String>,
        level: Option<u32>,
    },
}

impl std::fmt::Debug for Node {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Node::Leaf { options, flags, value_providers, dynamic_options, category, level } => {
                f.debug_struct("Leaf")
                    .field("options", options)
                    .field("flags", flags)
                    .field("value_providers", &value_providers.keys().collect::<Vec<_>>())
                    .field("has_dynamic_options", &dynamic_options.is_some())
                    .field("category", category)
                    .field("level", level)
                    .finish()
            }
            Node::Group { children, category, level } => {
                f.debug_struct("Group")
                    .field("children", children)
                    .field("category", category)
                    .field("level", level)
                    .finish()
            }
        }
    }
}

impl Node {
    /// Create a leaf node with the given option names (all assumed to take values).
    pub fn leaf(options: &[&str]) -> Self {
        Node::Leaf {
            options: options.iter().map(|s| s.to_string()).collect(),
            flags: std::collections::HashSet::new(),
            value_providers: BTreeMap::new(),
            dynamic_options: None,
            category: None,
            level: None,
        }
    }

    /// Create a leaf node with separate value-options and boolean flags.
    pub fn leaf_with_flags(options: &[&str], flags: &[&str]) -> Self {
        Node::Leaf {
            options: options.iter().chain(flags.iter()).map(|s| s.to_string()).collect(),
            flags: flags.iter().map(|s| s.to_string()).collect(),
            value_providers: BTreeMap::new(),
            dynamic_options: None,
            category: None,
            level: None,
        }
    }

    /// Attach a dynamic value provider to an option on this leaf node.
    pub fn with_value_provider(mut self, option: &str, provider: ValueProvider) -> Self {
        if let Node::Leaf { ref mut value_providers, .. } = self {
            value_providers.insert(option.to_string(), provider);
        }
        self
    }

    /// Attach a dynamic options provider to this leaf node.
    ///
    /// The provider is called during completion to discover additional
    /// `key=` options from context (e.g., workload file parameters).
    pub fn with_dynamic_options(mut self, provider: DynamicOptionsProvider) -> Self {
        if let Node::Leaf { ref mut dynamic_options, .. } = self {
            *dynamic_options = Some(provider);
        }
        self
    }

    /// Tag this node with a display category (e.g. `"workloads"`,
    /// `"documentation"`). Categories are free-form strings used by
    /// renderers to group commands; they don't affect completion
    /// candidate ordering directly.
    pub fn with_category(mut self, cat: &str) -> Self {
        match &mut self {
            Node::Leaf { category, .. } => *category = Some(cat.to_string()),
            Node::Group { category, .. } => *category = Some(cat.to_string()),
        }
        self
    }

    /// Set the tap-tier visibility for this node. The Nth tab
    /// tap reveals every root-level node with `level <= N`.
    /// Default (when `with_level` is not called) is
    /// [`DEFAULT_LEVEL`] (= 1) — but strict-metadata mode (see
    /// [`CommandTree::require_metadata`]) treats the absence
    /// of an explicit call as a registration error.
    pub fn with_level(mut self, lvl: u32) -> Self {
        match &mut self {
            Node::Leaf { level, .. } => *level = Some(lvl),
            Node::Group { level, .. } => *level = Some(lvl),
        }
        self
    }

    /// Get the node's category tag, if any.
    pub fn category(&self) -> Option<&str> {
        match self {
            Node::Leaf { category, .. } => category.as_deref(),
            Node::Group { category, .. } => category.as_deref(),
        }
    }

    /// Get the node's effective tap-tier level — explicit
    /// value if set, otherwise [`DEFAULT_LEVEL`].
    pub fn level(&self) -> u32 {
        self.level_explicit().unwrap_or(DEFAULT_LEVEL)
    }

    /// Get the node's *explicit* tap-tier level — `None` when
    /// `with_level` was never called. Used by strict-metadata
    /// validation to distinguish "user picked level 1" from
    /// "user forgot to set a level."
    pub fn level_explicit(&self) -> Option<u32> {
        match self {
            Node::Leaf { level, .. } => *level,
            Node::Group { level, .. } => *level,
        }
    }

    /// Check if an option is a boolean flag (no value expected).
    pub fn is_flag(&self, option: &str) -> bool {
        match self {
            Node::Leaf { flags, .. } => flags.contains(option),
            _ => false,
        }
    }

    /// Create a group node from a list of `(name, child)` pairs.
    pub fn group(children: Vec<(&str, Node)>) -> Self {
        Node::Group {
            children: children.into_iter()
                .map(|(k, v)| (k.to_string(), v))
                .collect(),
            category: None,
            level: None,
        }
    }

    /// Create an empty group node.
    pub fn empty_group() -> Self {
        Node::Group {
            children: BTreeMap::new(),
            category: None,
            level: None,
        }
    }

    /// Add a child to a group node. Panics if called on a leaf.
    pub fn with_child(mut self, name: &str, child: Node) -> Self {
        match &mut self {
            Node::Group { children, .. } => { children.insert(name.to_string(), child); }
            Node::Leaf { .. } => panic!("cannot add child to leaf node"),
        }
        self
    }

    /// Get child names (empty for leaves).
    pub fn child_names(&self) -> Vec<&str> {
        match self {
            Node::Group { children, .. } => children.keys().map(|k| k.as_str()).collect(),
            Node::Leaf { .. } => Vec::new(),
        }
    }

    /// Get a child by name.
    pub fn child(&self, name: &str) -> Option<&Node> {
        match self {
            Node::Group { children, .. } => children.get(name),
            Node::Leaf { .. } => None,
        }
    }

    /// Get option names (empty for groups).
    pub fn options(&self) -> Vec<&str> {
        match self {
            Node::Leaf { options, .. } => options.iter().map(|s| s.as_str()).collect(),
            Node::Group { .. } => Vec::new(),
        }
    }
}

// =====================================================================
// Strict-metadata builder (compile-time enforcement)
// =====================================================================

/// Type-state wrapper around [`Node`] that tracks at the type
/// level whether the node has been given a category and an
/// explicit tap-tier level.
///
/// Used together with [`CommandTree::strict_command`] /
/// [`CommandTree::strict_group`] to force compile-time
/// enforcement of the stratified completion contract: an app
/// that opts into strict mode cannot register an uncategorized
/// or unleveled command, because the registration call itself
/// will not type-check unless both fields have been provided.
///
/// The two `bool` const generics flip from `false` to `true`
/// when the matching builder method is called:
///
/// - `with_category("…")` → `HAS_CATEGORY = true`
/// - `with_level(N)`     → `HAS_LEVEL    = true`
///
/// Apps that don't want the compile-time check can keep using
/// the regular [`Node`] API and call
/// [`CommandTree::require_metadata`] to get an equivalent
/// runtime check at registration time.
///
/// # Successful registration (compiles)
///
/// ```
/// use veks_completion::{CommandTree, StrictNode};
/// let tree = CommandTree::new("myapp")
///     .strict_command(
///         "run",
///         StrictNode::leaf(&["--cycles=", "--threads="])
///             .with_category("workloads")
///             .with_level(1),
///     );
/// # let _ = tree;
/// ```
///
/// # Missing category (compile error)
///
/// ```compile_fail
/// use veks_completion::{CommandTree, StrictNode};
/// let _tree = CommandTree::new("myapp").strict_command(
///     "bad",
///     StrictNode::leaf(&[]).with_level(1),  // missing with_category
/// );
/// ```
///
/// # Missing level (compile error)
///
/// ```compile_fail
/// use veks_completion::{CommandTree, StrictNode};
/// let _tree = CommandTree::new("myapp").strict_command(
///     "bad",
///     StrictNode::leaf(&[]).with_category("x"),  // missing with_level
/// );
/// ```
pub struct StrictNode<const HAS_CATEGORY: bool, const HAS_LEVEL: bool> {
    inner: Node,
}

impl StrictNode<false, false> {
    /// Begin building a strict leaf node. Both `with_category`
    /// and `with_level` must be called before this can be
    /// passed to [`CommandTree::strict_command`].
    pub fn leaf(options: &[&str]) -> Self {
        Self { inner: Node::leaf(options) }
    }

    /// Same as [`Node::leaf_with_flags`] but type-state-checked.
    pub fn leaf_with_flags(options: &[&str], flags: &[&str]) -> Self {
        Self { inner: Node::leaf_with_flags(options, flags) }
    }

    /// Begin building a strict group node.
    pub fn group(children: Vec<(&str, Node)>) -> Self {
        Self { inner: Node::group(children) }
    }

    /// Begin from an already-constructed [`Node`]. Useful when
    /// migrating an existing tree to strict mode incrementally.
    pub fn from_node(node: Node) -> Self {
        Self { inner: node }
    }
}

impl<const C: bool, const L: bool> StrictNode<C, L> {
    /// Tag with a category. Flips `HAS_CATEGORY` to `true`.
    pub fn with_category(self, cat: &str) -> StrictNode<true, L> {
        StrictNode { inner: self.inner.with_category(cat) }
    }

    /// Set the tap-tier level. Flips `HAS_LEVEL` to `true`.
    pub fn with_level(self, lvl: u32) -> StrictNode<C, true> {
        StrictNode { inner: self.inner.with_level(lvl) }
    }

    /// Forward through to the inner node's value-provider
    /// builder.
    pub fn with_value_provider(mut self, option: &str, provider: ValueProvider) -> Self {
        self.inner = self.inner.with_value_provider(option, provider);
        self
    }

    /// Forward through to the inner node's dynamic-options
    /// builder.
    pub fn with_dynamic_options(mut self, provider: DynamicOptionsProvider) -> Self {
        self.inner = self.inner.with_dynamic_options(provider);
        self
    }
}

impl StrictNode<true, true> {
    /// Unwrap a fully-qualified strict node into a plain
    /// [`Node`]. The compile-time guarantee carries through to
    /// the moment of unwrapping: only nodes that have set both
    /// category and level can be downgraded.
    pub fn into_node(self) -> Node { self.inner }
}

/// The top-level command tree for an application.
pub struct CommandTree {
    /// Application name (used for env var naming).
    pub app_name: String,
    /// Root node (always a group).
    pub root: Node,
    /// Commands that exist but are hidden from root-level listing.
    pub hidden: std::collections::HashSet<String>,
    /// Global value providers keyed by option name.
    pub global_value_providers: BTreeMap<String, ValueProvider>,
    /// When true, every registered command must declare both a
    /// category (via [`Node::with_category`]) and an explicit
    /// level (via [`Node::with_level`]). [`Self::command`] /
    /// [`Self::group`] / [`Self::hidden_command`] panic on
    /// registration of an undertagged node, surfacing the
    /// problem at the call site rather than producing a
    /// silently-uncategorized completion tree at runtime.
    /// Opt-in for apps that want their stratified completion
    /// UX enforced at compile-test time.
    pub strict_metadata: bool,
}

impl CommandTree {
    /// Create a new command tree with an empty root group.
    ///
    /// The `app_name` is used to construct the environment variable name
    /// for completion callbacks (e.g., `_MYAPP_COMPLETE=bash`).
    pub fn new(app_name: &str) -> Self {
        CommandTree {
            app_name: app_name.to_string(),
            root: Node::empty_group(),
            hidden: std::collections::HashSet::new(),
            global_value_providers: BTreeMap::new(),
            strict_metadata: false,
        }
    }

    /// Opt-in to strict-metadata mode. Every subsequent call
    /// to [`Self::command`] / [`Self::group`] /
    /// [`Self::hidden_command`] checks that the node has both
    /// a category and an explicit level — registration panics
    /// if either is missing, with a message naming the
    /// offending command.
    ///
    /// Use this in apps that have committed to a stratified
    /// completion model and want the build to break if a new
    /// command is added without categorizing it.
    pub fn require_metadata(mut self) -> Self {
        self.strict_metadata = true;
        self
    }

    /// Walk every registered command and check for missing
    /// category / level metadata. Returns `Ok(())` when every
    /// node satisfies the contract; `Err(Vec<MetadataError>)`
    /// otherwise with one entry per offending command.
    ///
    /// Always available regardless of `strict_metadata` — apps
    /// that want validation as a one-shot post-build check
    /// (CI test, debug-assert, etc.) can call this directly
    /// without enabling the panic-at-registration mode.
    pub fn validate(&self) -> Result<(), Vec<MetadataError>> {
        let mut errors = Vec::new();
        if let Node::Group { children, .. } = &self.root {
            for (name, node) in children {
                if node.category().is_none() {
                    errors.push(MetadataError::MissingCategory {
                        command: name.clone(),
                    });
                }
                if node.level_explicit().is_none() {
                    errors.push(MetadataError::MissingLevel {
                        command: name.clone(),
                    });
                }
            }
        }
        if errors.is_empty() { Ok(()) } else { Err(errors) }
    }

    /// Internal: panic if `strict_metadata` is set and `node`
    /// is missing required metadata. Called from every
    /// `command`-style registration helper so the error fires
    /// at the source line that registered the bad node.
    fn check_strict(&self, name: &str, node: &Node) {
        if !self.strict_metadata { return; }
        if node.category().is_none() {
            panic!("veks-completion: app '{}' has require_metadata() set, \
                    but command '{name}' was registered without \
                    Node::with_category(...). Add a category tag.",
                self.app_name);
        }
        if node.level_explicit().is_none() {
            panic!("veks-completion: app '{}' has require_metadata() set, \
                    but command '{name}' was registered without \
                    Node::with_level(...). Pick a tap-tier level (1, 2, 3, ...).",
                self.app_name);
        }
    }

    /// Add a top-level command (leaf or group) to the tree.
    ///
    /// This is a builder method — it consumes and returns `self` for chaining.
    pub fn command(mut self, name: &str, node: Node) -> Self {
        self.check_strict(name, &node);
        self.root = self.root.with_child(name, node);
        self
    }

    /// Add a top-level command using the type-state-checked
    /// [`StrictNode`] API. The signature requires
    /// `StrictNode<true, true>`, so calling this with a node
    /// missing either `with_category(...)` or `with_level(...)`
    /// is a **compile-time** error — no runtime panic, no
    /// silent skip. Recommended entry point for apps that want
    /// the stratified completion model strictly enforced.
    pub fn strict_command(
        mut self,
        name: &str,
        node: StrictNode<true, true>,
    ) -> Self {
        self.root = self.root.with_child(name, node.into_node());
        self
    }

    /// Type-state-checked alias for grouping. Same compile-time
    /// guarantee as [`Self::strict_command`].
    pub fn strict_group(self, name: &str, node: StrictNode<true, true>) -> Self {
        self.strict_command(name, node)
    }

    /// Type-state-checked variant of [`Self::hidden_command`].
    pub fn strict_hidden_command(
        mut self,
        name: &str,
        node: StrictNode<true, true>,
    ) -> Self {
        self.hidden.insert(name.to_string());
        self.root = self.root.with_child(name, node.into_node());
        self
    }

    /// Add a top-level group to the tree. Alias for [`command`](Self::command).
    pub fn group(self, name: &str, node: Node) -> Self {
        self.command(name, node)
    }

    /// Add a command that is registered but hidden from root-level listing.
    ///
    /// Hidden commands are still completable if the user types the name
    /// prefix directly — they are just excluded from the initial empty-prefix
    /// candidate list. Useful for aliases and shorthands.
    pub fn hidden_command(mut self, name: &str, node: Node) -> Self {
        self.check_strict(name, &node);
        self.hidden.insert(name.to_string());
        self.command(name, node)
    }

    /// Register a value provider that applies to an option name across all
    /// leaf commands in the tree.
    ///
    /// When the user types `--dataset <TAB>`, the provider is called regardless
    /// of which leaf command is active. Per-leaf providers registered via
    /// [`Node::with_value_provider`] take precedence over global providers.
    pub fn global_value_provider(mut self, option: &str, provider: ValueProvider) -> Self {
        self.global_value_providers.insert(option.to_string(), provider);
        self
    }
}

/// Check if a word on the command line matches (and thus consumes) a
/// defined option. Handles exact flags, `key=value`, `--key=value`,
/// and cross-style equivalence.
fn word_matches_option(word: &str, option: &str) -> bool {
    if word == option { return true; }

    if let Some(key) = option.strip_suffix('=') {
        if word.starts_with(key) && word[key.len()..].starts_with('=') {
            return true;
        }
        let dashed = format!("--{key}");
        if word.starts_with(&dashed) && word[dashed.len()..].starts_with('=') {
            return true;
        }
    }

    if option.starts_with("--") && !option.ends_with('=') {
        if word.starts_with(option) && word[option.len()..].starts_with('=') {
            return true;
        }
        let bare = &option[2..];
        if word.starts_with(bare) && word[bare.len()..].starts_with('=') {
            return true;
        }
    }

    false
}

/// Collect canonical keys for options already present on the command line.
fn consumed_keys(words: &[&str], options: &[String]) -> std::collections::HashSet<String> {
    let mut consumed = std::collections::HashSet::new();
    for &word in words {
        for opt in options {
            if word_matches_option(word, opt) {
                let key = opt.trim_start_matches('-').trim_end_matches('=');
                consumed.insert(key.to_string());
            }
        }
    }
    consumed
}

/// Check if an option's canonical key is in the consumed set.
fn is_consumed(option: &str, consumed: &std::collections::HashSet<String>) -> bool {
    let key = option.trim_start_matches('-').trim_end_matches('=');
    consumed.contains(key)
}

/// Compute completion candidates for the given input words.
///
/// Options already present on the command line are excluded. Both
/// `--flag` and bare `key=` styles are supported and deduplicated.
/// Dynamic options from context providers are included.
///
/// Always operates at tap level 1. For stratified completion
/// where successive tabs reveal more candidates, use
/// [`complete_at_tap`].
pub fn complete(tree: &CommandTree, words: &[&str]) -> Vec<String> {
    complete_at_tap(tree, words, 1)
}

/// Stratified completion: returns root-level candidates with
/// `Node::level() <= tap_count`, so the Nth tab tap reveals
/// progressively more commands. Inside a subcommand or with a
/// non-empty partial, behaves identically to [`complete`] —
/// the level filter applies only when the user is at the
/// root prompt with no prefix typed.
///
/// Default Node level is [`DEFAULT_LEVEL`] (= 1), so apps that
/// haven't categorized their commands see the same single-tap
/// behavior they did before stratification.
pub fn complete_at_tap(tree: &CommandTree, words: &[&str], tap_count: u32) -> Vec<String> {
    if words.len() <= 1 {
        let mut cmds: Vec<String> = tree.root.child_names().iter()
            .filter(|s| !tree.hidden.contains(**s))
            .filter(|s| {
                tree.root.child(s)
                    .map(|n| n.level() <= tap_count)
                    .unwrap_or(true)
            })
            .map(|s| s.to_string())
            .collect();
        cmds.sort_by(|a, b| {
            a.starts_with('-').cmp(&b.starts_with('-')).then_with(|| a.cmp(b))
        });
        return cmds;
    }

    let partial = words.last().unwrap_or(&"");
    let completed = &words[1..words.len() - 1];
    let at_root = completed.is_empty();

    // Walk the tree following completed words.
    let mut node = &tree.root;
    let mut remaining_start = 0;
    for (i, &word) in completed.iter().enumerate() {
        match node.child(word) {
            Some(child) => { node = child; remaining_start = i + 1; }
            None => break,
        }
    }
    let remaining = &completed[remaining_start..];

    // Check global value providers for the previous word.
    if let Some(&prev_word) = completed.last()
        && let Some(provider) = tree.global_value_providers.get(prev_word) {
        return provider(partial, remaining);
    }

    match node {
        Node::Group { children, .. } => {
            let mut candidates: Vec<String> = children.iter()
                .filter(|(k, _)| k.starts_with(partial))
                .filter(|(k, _)| !at_root || !partial.is_empty() || !tree.hidden.contains(k.as_str()))
                // Level filter only applies at root with an
                // empty partial — once the user has started
                // typing a specific name, return matching
                // commands regardless of tap tier so a
                // partially-typed level-2 command (e.g.
                // `--ins<TAB>`) still completes on tap 1.
                .filter(|(_, child)| {
                    !at_root || !partial.is_empty() || child.level() <= tap_count
                })
                .map(|(k, _)| k.to_string())
                .collect();
            candidates.sort_by(|a, b| {
                a.starts_with('-').cmp(&b.starts_with('-')).then_with(|| a.cmp(b))
            });
            candidates
        }
        Node::Leaf { options, flags, value_providers, dynamic_options, .. } => {
            // Check if the previous word is a --option expecting a separate value.
            if let Some(&prev_word) = remaining.last()
                && prev_word.starts_with("--") && !prev_word.contains('=') && !flags.contains(prev_word) {
                if let Some(provider) = value_providers.get(prev_word) {
                    return provider(partial, remaining);
                }
                if let Some(provider) = tree.global_value_providers.get(prev_word) {
                    return provider(partial, remaining);
                }
                return Vec::new();
            }

            // Check if partial is "key=value_prefix" — call value provider for that key.
            if let Some(eq_pos) = partial.find('=') {
                let key = &partial[..eq_pos];
                let value_partial = &partial[eq_pos + 1..];
                let key_eq = format!("{key}=");
                let dashed_key = format!("--{key}");
                // Try value provider by "key=" or "--key"
                if let Some(provider) = value_providers.get(&key_eq)
                    .or_else(|| value_providers.get(&dashed_key))
                    .or_else(|| tree.global_value_providers.get(&key_eq))
                    .or_else(|| tree.global_value_providers.get(&dashed_key))
                {
                    let values = provider(value_partial, remaining);
                    return values.into_iter()
                        .map(|v| format!("{key}={v}"))
                        .collect();
                }
            }

            // Collect all available options: static + dynamic from context.
            let mut all_options: Vec<String> = options.clone();
            if let Some(provider) = dynamic_options {
                let dynamic = provider(partial, remaining);
                for opt in dynamic {
                    if !all_options.contains(&opt) {
                        all_options.push(opt);
                    }
                }
            }

            // Filter out already-consumed options.
            let consumed = consumed_keys(remaining, &all_options);

            let mut candidates: Vec<String> = all_options.iter()
                .filter(|o| o.starts_with(partial) && !is_consumed(o, &consumed))
                .map(|o| o.to_string())
                .collect();

            // Also offer global provider options.
            for global_opt in tree.global_value_providers.keys() {
                if global_opt.starts_with(partial) && !candidates.contains(global_opt) {
                    candidates.push(global_opt.clone());
                }
            }

            // Sort: bare params first, then --flags.
            candidates.sort_by(|a, b| {
                a.starts_with('-').cmp(&b.starts_with('-')).then_with(|| a.cmp(b))
            });
            candidates
        }
    }
}

/// Generate a bash completion script that calls back into the app.
pub fn print_bash_script(app_name: &str) {
    let env_var = format!("_{}_COMPLETE", app_name.to_uppercase().replace('-', "_"));

    let completer = std::env::args_os()
        .next()
        .and_then(|p| {
            let path = std::path::PathBuf::from(&p);
            if path.components().count() > 1 {
                std::env::current_dir().ok().map(|cwd| cwd.join(path))
            } else {
                Some(path)
            }
        })
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| app_name.to_string());

    print!(r#"_{app}_complete() {{
    COMP_WORDBREAKS="${{COMP_WORDBREAKS//:}}"
    local line="${{COMP_LINE:0:$COMP_POINT}}"
    local -a words=()
    local word=""
    local in_quote=""
    local i=0
    while [ $i -lt ${{#line}} ]; do
        local ch="${{line:$i:1}}"
        if [ -n "$in_quote" ]; then
            if [ "$ch" = "$in_quote" ]; then
                in_quote=""
            else
                word+="$ch"
            fi
        elif [ "$ch" = "'" ] || [ "$ch" = '"' ]; then
            in_quote="$ch"
        elif [ "$ch" = " " ] || [ "$ch" = $'\t' ]; then
            if [ -n "$word" ]; then
                words+=("$word")
                word=""
            fi
        else
            word+="$ch"
        fi
        i=$((i + 1))
    done
    words+=("$word")

    local IFS=$'\n'
    COMPREPLY=($({env_var}=bash _COMP_SHELL_PID=$$ "{completer}" -- "${{words[@]}}" 2>/dev/tty))
}}
if [[ "${{BASH_VERSINFO[0]}}" -eq 4 && "${{BASH_VERSINFO[1]}}" -ge 4 || "${{BASH_VERSINFO[0]}}" -gt 4 ]]; then
    complete -o default -o bashdefault -o nosort -F _{app}_complete {app}
else
    complete -o default -o bashdefault -F _{app}_complete {app}
fi
"#,
        app = app_name,
        env_var = env_var,
        completer = completer,
    );
}

/// Check for completion env vars and handle them.
pub fn handle_complete_env(app_name: &str, tree: &CommandTree) -> bool {
    let env_var = format!("_{}_COMPLETE", app_name.to_uppercase().replace('-', "_"));
    let is_ours = std::env::var(&env_var).ok().as_deref() == Some("bash");
    let is_legacy = std::env::var("COMPLETE").ok().as_deref() == Some("bash");
    if !is_ours && !is_legacy {
        return false;
    }

    let args: Vec<String> = std::env::args().collect();
    let words_start = args.iter().position(|a| a == "--").map(|i| i + 1).unwrap_or(1);
    let words: Vec<&str> = args[words_start..].iter().map(|s| s.as_str()).collect();

    let input_key = words[1..].join(" ");
    let tap_count = tap_detect(app_name, &input_key);

    // Stratified completion: tap N reveals every command with
    // `Node::level() <= N`. The legacy "tap 3+ shows the full
    // expanded `group cmd` view" behavior is still reachable
    // — when no node opts into a level above 1, all root
    // commands appear from tap 1 onward, matching the
    // pre-stratification behavior, and tap 3 reaches
    // `complete_expanded` for hierarchical group/command
    // pairs.
    let candidates = if tap_count >= 3 && tap_count % 2 == 1 {
        // Odd-numbered tap >= 3 still reaches the expanded
        // hierarchical view as a final fallback for trees
        // with deep groups. For flat trees this returns the
        // same as the level filter at tap_count.
        let expanded = complete_expanded(tree, &words);
        if !expanded.is_empty() {
            expanded
        } else {
            complete_at_tap(tree, &words, tap_count)
        }
    } else {
        complete_at_tap(tree, &words, tap_count)
    };

    for candidate in candidates {
        println!("{}", candidate);
    }

    true
}

fn tap_detect(app_name: &str, input_key: &str) -> u32 {
    use std::io::Write;

    let ppid = std::env::var("_COMP_SHELL_PID")
        .or_else(|_| std::env::var("PPID"))
        .unwrap_or_else(|_| "0".to_string());
    let tap_file = std::path::PathBuf::from(format!("/tmp/.{}_tap_{}", app_name, ppid));
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let mut count = 1u32;

    if let Ok(content) = std::fs::read_to_string(&tap_file) {
        let mut parts = content.splitn(3, ' ');
        let prev_time: u64 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
        let prev_count: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
        let prev_key = parts.next().unwrap_or("").trim();

        if prev_key == input_key && now.saturating_sub(prev_time) < 5 {
            count = prev_count + 1;
        }
    }

    if let Ok(mut f) = std::fs::File::create(&tap_file) {
        let _ = write!(f, "{} {} {}", now, count, input_key);
    }

    count
}

/// Expanded completion: show all `group command` pairs.
pub fn complete_expanded(tree: &CommandTree, words: &[&str]) -> Vec<String> {
    let partial = if words.len() > 1 { words.last().unwrap_or(&"") } else { &"" };
    let completed = if words.len() > 2 { &words[1..words.len() - 1] } else { &[] };

    if !completed.is_empty() || !partial.is_empty() {
        return complete(tree, words);
    }

    let mut results = Vec::new();
    if let Node::Group { children, .. } = &tree.root {
        for (name, node) in children {
            if name == "help" || name.starts_with('-') {
                continue;
            }
            match node {
                Node::Group { children: sub, .. } if !sub.is_empty() => {
                    for sub_name in sub.keys() {
                        results.push(format!("{} {}", name, sub_name));
                    }
                }
                _ => {
                    if !tree.hidden.contains(name.as_str()) {
                        results.push(name.to_string());
                    }
                }
            }
        }
    }
    results
}

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

    fn test_tree() -> CommandTree {
        CommandTree::new("testapp")
            .command("run", Node::leaf_with_flags(
                &["cycles=", "threads=", "adapter=", "workload="],
                &["--strict", "--tui"],
            ).with_dynamic_options(dynamic_workload_params))
            .command("bench", Node::group(vec![
                ("gk", Node::leaf_with_flags(
                    &["cycles=", "threads=", "--cycles", "--threads"],
                    &["--explain"],
                )),
            ]))
    }

    /// Test dynamic options provider: if workload=X is on the line,
    /// return extra params that the workload declares.
    fn dynamic_workload_params(_partial: &str, context: &[&str]) -> Vec<String> {
        // Find workload= on the context
        for word in context {
            if let Some(path) = word.strip_prefix("workload=") {
                if path == "test_keyvalue.yaml" {
                    return vec!["keyspace=".into(), "table=".into(), "keycount=".into()];
                }
            }
        }
        Vec::new()
    }

    #[test]
    fn root_completions() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", ""]);
        assert!(candidates.contains(&"bench".to_string()));
        assert!(candidates.contains(&"run".to_string()));
    }

    #[test]
    fn run_shows_all_options() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", ""]);
        assert!(candidates.contains(&"cycles=".to_string()));
        assert!(candidates.contains(&"--strict".to_string()));
        assert!(candidates.contains(&"adapter=".to_string()));
    }

    #[test]
    fn run_filters_consumed_bare_param() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", "cycles=1000", ""]);
        assert!(!candidates.contains(&"cycles=".to_string()));
        assert!(candidates.contains(&"threads=".to_string()));
        assert!(candidates.contains(&"--strict".to_string()));
    }

    #[test]
    fn run_filters_consumed_flag() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", "--strict", ""]);
        assert!(!candidates.contains(&"--strict".to_string()));
        assert!(candidates.contains(&"cycles=".to_string()));
    }

    #[test]
    fn bench_gk_filters_consumed() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "bench", "gk", "expr", "--cycles=1000000", "--threads=20", ""]);
        assert!(!candidates.contains(&"--cycles".to_string()));
        assert!(!candidates.contains(&"cycles=".to_string()));
        assert!(!candidates.contains(&"--threads".to_string()));
        assert!(!candidates.contains(&"threads=".to_string()));
        assert!(candidates.contains(&"--explain".to_string()));
    }

    #[test]
    fn partial_match_bare_param() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", "cy"]);
        assert!(candidates.contains(&"cycles=".to_string()));
        assert!(!candidates.contains(&"--strict".to_string()));
    }

    #[test]
    fn dynamic_options_from_workload() {
        let tree = test_tree();
        // When workload=test_keyvalue.yaml is on the line, dynamic params appear
        let candidates = complete(&tree, &["testapp", "run", "workload=test_keyvalue.yaml", ""]);
        assert!(candidates.contains(&"keyspace=".to_string()), "dynamic param 'keyspace=' should appear");
        assert!(candidates.contains(&"table=".to_string()), "dynamic param 'table=' should appear");
        assert!(candidates.contains(&"keycount=".to_string()), "dynamic param 'keycount=' should appear");
        // Static options should still be present
        assert!(candidates.contains(&"--strict".to_string()));
        // workload= should be consumed
        assert!(!candidates.contains(&"workload=".to_string()));
    }

    #[test]
    fn dynamic_options_filtered_when_consumed() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", "workload=test_keyvalue.yaml", "keyspace=mykeyspace", ""]);
        assert!(!candidates.contains(&"keyspace=".to_string()), "keyspace= already used");
        assert!(candidates.contains(&"table=".to_string()), "table= still available");
    }

    #[test]
    fn dynamic_options_partial_match() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", "workload=test_keyvalue.yaml", "key"]);
        assert!(candidates.contains(&"keyspace=".to_string()));
        assert!(candidates.contains(&"keycount=".to_string()));
        assert!(!candidates.contains(&"table=".to_string()), "table= doesn't start with 'key'");
    }

    #[test]
    fn no_dynamic_options_without_workload() {
        let tree = test_tree();
        let candidates = complete(&tree, &["testapp", "run", ""]);
        assert!(!candidates.contains(&"keyspace=".to_string()), "no workload= means no dynamic params");
    }

    #[test]
    fn word_matches_exact_flag() {
        assert!(word_matches_option("--strict", "--strict"));
        assert!(!word_matches_option("--strict", "--tui"));
    }

    #[test]
    fn word_matches_bare_key_value() {
        assert!(word_matches_option("cycles=1000", "cycles="));
        assert!(!word_matches_option("threads=4", "cycles="));
    }

    #[test]
    fn word_matches_dashed_to_bare_equivalence() {
        assert!(word_matches_option("--cycles=1000", "cycles="));
        assert!(word_matches_option("cycles=1000", "--cycles"));
    }

    // ---- stratified tap completion ----

    fn stratified_tree() -> CommandTree {
        CommandTree::new("nbrs")
            .command("run",
                Node::leaf(&["--cycles="])
                    .with_category("workloads").with_level(1))
            .command("--inspector",
                Node::leaf(&[])
                    .with_category("tools").with_level(2))
            .command("--summary",
                Node::leaf(&[])
                    .with_category("tools").with_level(2))
            .command("describe",
                Node::leaf(&[])
                    .with_category("documentation").with_level(3))
            .command("bench",
                Node::leaf(&[])
                    .with_category("benchmark").with_level(3))
    }

    #[test]
    fn tap1_shows_only_level1_commands() {
        let tree = stratified_tree();
        let cands = complete_at_tap(&tree, &["nbrs"], 1);
        assert_eq!(cands, vec!["run".to_string()]);
    }

    #[test]
    fn tap2_adds_level2_commands() {
        let tree = stratified_tree();
        let cands = complete_at_tap(&tree, &["nbrs"], 2);
        assert!(cands.contains(&"run".to_string()));
        assert!(cands.contains(&"--inspector".to_string()));
        assert!(cands.contains(&"--summary".to_string()));
        assert!(!cands.contains(&"describe".to_string()),
            "level-3 'describe' should not appear at tap 2");
    }

    #[test]
    fn tap3_shows_everything() {
        let tree = stratified_tree();
        let cands = complete_at_tap(&tree, &["nbrs"], 3);
        assert!(cands.contains(&"run".to_string()));
        assert!(cands.contains(&"--inspector".to_string()));
        assert!(cands.contains(&"describe".to_string()));
        assert!(cands.contains(&"bench".to_string()));
    }

    #[test]
    fn level_filter_does_not_block_partial_match() {
        // Typing `--ins` should still complete to `--inspector`
        // even at tap 1, where level-2 commands aren't shown
        // empty-prefix. Once the user has typed a prefix,
        // they've signaled intent for that specific command.
        let tree = stratified_tree();
        let cands = complete_at_tap(&tree, &["nbrs", "--ins"], 1);
        assert!(cands.contains(&"--inspector".to_string()),
            "partial-prefix matches should bypass the tap-tier filter");
    }

    #[test]
    fn nodes_without_level_default_to_visible() {
        // Backward-compat: a node that never called
        // `with_level` resolves to DEFAULT_LEVEL = 1 and is
        // visible from tap 1. Apps that haven't migrated to
        // categorized completion see no behavior change.
        let tree = CommandTree::new("legacy")
            .command("run", Node::leaf(&[]))
            .command("describe", Node::leaf(&[]));
        let cands = complete_at_tap(&tree, &["legacy"], 1);
        assert!(cands.contains(&"run".to_string()));
        assert!(cands.contains(&"describe".to_string()));
    }

    // ---- strict-metadata: type-state enforcement ----

    #[test]
    fn strict_node_with_full_metadata_compiles() {
        // The success case — adding a fully-tagged node
        // through `strict_command` is the canonical strict
        // mode usage. The compiler doesn't reject this.
        let _tree = CommandTree::new("app")
            .strict_command(
                "run",
                StrictNode::leaf(&["--cycles="])
                    .with_category("workloads")
                    .with_level(1),
            );
    }

    // The next two are intentionally `#[ignore]`d compile-fail
    // demonstrations. They live here as documentation rather
    // than tests, since `cargo test` won't try to build them
    // unless explicitly invoked, but a reader can uncomment to
    // verify the gate fires.
    //
    // ```compile_fail,ignore
    // CommandTree::new("app").strict_command(
    //     "bad",
    //     StrictNode::leaf(&[]).with_category("x"),  // missing with_level
    // );
    // ```
    //
    // ```compile_fail,ignore
    // CommandTree::new("app").strict_command(
    //     "bad",
    //     StrictNode::leaf(&[]).with_level(1),  // missing with_category
    // );
    // ```

    // ---- runtime-validation path ----

    #[test]
    fn runtime_validate_reports_missing_metadata() {
        let tree = CommandTree::new("app")
            .command("run",
                Node::leaf(&[]).with_category("workloads").with_level(1))
            .command("undertagged", Node::leaf(&[]));
        let errors = tree.validate().unwrap_err();
        assert!(errors.iter().any(|e| matches!(e,
            MetadataError::MissingCategory { command } if command == "undertagged")));
        assert!(errors.iter().any(|e| matches!(e,
            MetadataError::MissingLevel { command } if command == "undertagged")));
        // The properly-tagged 'run' should not appear in errors.
        assert!(!errors.iter().any(|e| matches!(e,
            MetadataError::MissingCategory { command } if command == "run")));
    }

    #[test]
    fn runtime_validate_passes_when_all_tagged() {
        let tree = CommandTree::new("app")
            .command("run",
                Node::leaf(&[]).with_category("workloads").with_level(1))
            .command("describe",
                Node::leaf(&[]).with_category("docs").with_level(3));
        assert!(tree.validate().is_ok());
    }

    #[test]
    #[should_panic(expected = "without Node::with_category")]
    fn require_metadata_panics_on_undertagged_command() {
        let _tree = CommandTree::new("app")
            .require_metadata()
            .command("bad", Node::leaf(&[])); // missing both
    }
}