apcore-cli 0.7.0

Command-line interface for apcore modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! Built-in Command Group (FE-13).
//!
//! Encapsulates visibility resolution and subcommand filtering for the
//! reserved `apcli` group. Instantiated once by the CLI bootstrap and
//! attached to the root command.
//!
//! Shape mirrors [`crate::exposure::ExposureFilter`]: a private constructor
//! with named factories and a small set of predicate methods.
//!
//! Protocol spec: FE-13 — see `../apcore-cli/docs/features/builtin-group.md`
//! sections §4.2–§4.7 and §4.14 for authoritative semantics.

use thiserror::Error;

use crate::EXIT_INVALID_INPUT;

// ---------------------------------------------------------------------------
// Public constants
// ---------------------------------------------------------------------------

/// Canonical set of apcli subcommand names.
///
/// Declarative mirror of the registration table wired in `main.rs`. Used by
/// the internal list normalizer to warn on unknown entries in include/exclude
/// lists (spec §7 error table / T-APCLI-25). Keep in sync if subcommands are
/// added or removed.
pub const APCLI_SUBCOMMAND_NAMES: &[&str] = &[
    "list",
    "describe",
    "exec",
    "validate",
    "init",
    "health",
    "usage",
    "enable",
    "disable",
    "reload",
    "config",
    "completion",
    "describe-pipeline",
];

/// Group names reserved by apcore-cli (checked in `cli.rs`).
pub const RESERVED_GROUP_NAMES: &[&str] = &["apcli"];

// Valid user-supplied mode strings. Note: `"auto"` is an internal sentinel
// and is rejected from user-supplied config.
const VALID_USER_MODES: &[&str] = &["all", "none", "include", "exclude"];

// ---------------------------------------------------------------------------
// Public config types (spec §4.14)
// ---------------------------------------------------------------------------

/// User-facing apcli visibility mode.
///
/// The `Auto` variant is an internal sentinel meaning "fall through to
/// auto-detect"; it is never returned from [`ApcliGroup::resolve_visibility`]
/// and is rejected when supplied via user config.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum ApcliMode {
    /// Default: auto-detect based on registry-injection (Tier 4).
    #[default]
    Auto,
    /// Show all apcli subcommands.
    All,
    /// Hide the entire apcli group.
    None,
    /// Whitelist of subcommand names to expose.
    Include(Vec<String>),
    /// Blacklist of subcommand names to hide.
    Exclude(Vec<String>),
}

/// User-facing apcli config consumed by [`ApcliGroup::from_cli_config`].
///
/// Boolean shorthand (handled at the yaml/builder layer) maps to
/// `mode = All` / `mode = None`.
#[derive(Clone, Debug, Default)]
pub struct ApcliConfig {
    /// Visibility mode.
    pub mode: ApcliMode,
    /// When true, the `APCORE_CLI_APCLI` env var (Tier 2) is ignored.
    pub disable_env: bool,
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors surfaced by the fallible `from_yaml` builder.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ApcliGroupError {
    /// apcli config was neither a boolean nor a mapping.
    #[error("Error: apcli config must be a boolean or object; got {0}.")]
    InvalidShape(String),

    /// `mode` was not a string.
    #[error(
        "Error: apcli.mode must be a string; got {0}. \
         Expected one of all|none|include|exclude."
    )]
    ModeNotString(String),

    /// `mode` was a string but not one of the allowed values.
    #[error(
        "Error: apcli.mode '{0}' is invalid. \
         Expected one of all|none|include|exclude."
    )]
    ModeInvalid(String),
}

// ---------------------------------------------------------------------------
// ApcliGroup
// ---------------------------------------------------------------------------

/// Visibility configuration for the built-in `apcli` command group.
///
/// Instantiated via [`ApcliGroup::from_cli_config`] (Tier 1) or
/// [`ApcliGroup::from_yaml`] (Tier 3). The constructor is private to
/// preserve the Tier-1-vs-Tier-3 flag distinction.
#[derive(Debug)]
pub struct ApcliGroup {
    mode: InternalMode,
    include: Vec<String>,
    exclude: Vec<String>,
    disable_env: bool,
    registry_injected: bool,
    from_cli_config: bool,
}

/// Internal flat mode sentinel. Unlike [`ApcliMode`], this does not carry
/// the list payload — `include` / `exclude` vectors live on the struct.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InternalMode {
    Auto,
    All,
    None,
    Include,
    Exclude,
}

impl InternalMode {
    fn as_str(self) -> &'static str {
        match self {
            InternalMode::Auto => "auto",
            InternalMode::All => "all",
            InternalMode::None => "none",
            InternalMode::Include => "include",
            InternalMode::Exclude => "exclude",
        }
    }
}

impl ApcliGroup {
    // -------------------------------------------------------------------------
    // Factories
    // -------------------------------------------------------------------------

    /// Tier 1 constructor — config came from a programmatic embedder
    /// (i.e. an `ApcliConfig` value passed to a future embedding API).
    ///
    /// A non-auto mode from this tier wins over env var and yaml. Because
    /// `ApcliConfig` is strongly typed, no validation is needed here.
    pub fn from_cli_config(config: Option<ApcliConfig>, registry_injected: bool) -> Self {
        let (mode, include, exclude, disable_env) = match config {
            None => (InternalMode::Auto, Vec::new(), Vec::new(), false),
            Some(cfg) => {
                let disable_env = cfg.disable_env;
                match cfg.mode {
                    ApcliMode::Auto => (InternalMode::Auto, Vec::new(), Vec::new(), disable_env),
                    ApcliMode::All => (InternalMode::All, Vec::new(), Vec::new(), disable_env),
                    ApcliMode::None => (InternalMode::None, Vec::new(), Vec::new(), disable_env),
                    ApcliMode::Include(list) => {
                        Self::warn_unknown_entries(&list, "include");
                        (InternalMode::Include, list, Vec::new(), disable_env)
                    }
                    ApcliMode::Exclude(list) => {
                        Self::warn_unknown_entries(&list, "exclude");
                        (InternalMode::Exclude, Vec::new(), list, disable_env)
                    }
                }
            }
        };

        Self {
            mode,
            include,
            exclude,
            disable_env,
            registry_injected,
            from_cli_config: true,
        }
    }

    /// Tier 3 constructor — config came from `apcore.yaml`.
    ///
    /// Env var (Tier 2) may override the yaml-supplied mode unless
    /// `disable_env` is true. On validation error, prints a message to stderr
    /// and calls [`std::process::exit`] with [`EXIT_INVALID_INPUT`]; the
    /// fallible variant [`ApcliGroup::try_from_yaml`] is available for tests.
    pub fn from_yaml(yaml_value: Option<serde_yaml::Value>, registry_injected: bool) -> Self {
        match Self::try_from_yaml(yaml_value, registry_injected) {
            Ok(group) => group,
            Err(e) => {
                eprintln!("{e}");
                std::process::exit(EXIT_INVALID_INPUT);
            }
        }
    }

    /// Fallible sibling of [`ApcliGroup::from_yaml`]. Used by tests; the
    /// production wrapper prints the error and exits.
    pub fn try_from_yaml(
        yaml_value: Option<serde_yaml::Value>,
        registry_injected: bool,
    ) -> Result<Self, ApcliGroupError> {
        use serde_yaml::Value;

        // Missing / null → auto.
        let value = match yaml_value {
            None => return Ok(Self::auto(registry_injected, false)),
            Some(v) => v,
        };

        match value {
            Value::Null => Ok(Self::auto(registry_injected, false)),
            Value::Bool(true) => Ok(Self {
                mode: InternalMode::All,
                include: Vec::new(),
                exclude: Vec::new(),
                disable_env: false,
                registry_injected,
                from_cli_config: false,
            }),
            Value::Bool(false) => Ok(Self {
                mode: InternalMode::None,
                include: Vec::new(),
                exclude: Vec::new(),
                disable_env: false,
                registry_injected,
                from_cli_config: false,
            }),
            Value::Mapping(map) => Self::build_from_mapping(map, registry_injected),
            Value::Sequence(_) => Err(ApcliGroupError::InvalidShape("array".to_string())),
            Value::String(_) => Err(ApcliGroupError::InvalidShape("string".to_string())),
            Value::Number(_) => Err(ApcliGroupError::InvalidShape("number".to_string())),
            Value::Tagged(_) => Err(ApcliGroupError::InvalidShape("tagged".to_string())),
        }
    }

    fn auto(registry_injected: bool, from_cli_config: bool) -> Self {
        Self {
            mode: InternalMode::Auto,
            include: Vec::new(),
            exclude: Vec::new(),
            disable_env: false,
            registry_injected,
            from_cli_config,
        }
    }

    fn build_from_mapping(
        map: serde_yaml::Mapping,
        registry_injected: bool,
    ) -> Result<Self, ApcliGroupError> {
        use serde_yaml::Value;

        // Look up by string key. Skip (with warning) keys that are not
        // scalar strings — uncommon in yaml but technically legal.
        let get = |name: &str| -> Option<Value> {
            for (k, v) in &map {
                match k {
                    Value::String(s) if s == name => return Some(v.clone()),
                    _ => continue,
                }
            }
            None
        };

        // Warn once if there are any non-string keys.
        for (k, _) in &map {
            if !matches!(k, Value::String(_)) {
                tracing::warn!("apcli config has a non-string key; ignoring.");
                break;
            }
        }

        // Mode. Missing/null → Auto. Non-string or unknown string → error.
        let mode = match get("mode") {
            None | Some(Value::Null) => InternalMode::Auto,
            Some(Value::String(s)) => {
                if !VALID_USER_MODES.contains(&s.as_str()) {
                    return Err(ApcliGroupError::ModeInvalid(s));
                }
                match s.as_str() {
                    "all" => InternalMode::All,
                    "none" => InternalMode::None,
                    "include" => InternalMode::Include,
                    "exclude" => InternalMode::Exclude,
                    _ => unreachable!("VALID_USER_MODES check above"),
                }
            }
            Some(other) => {
                return Err(ApcliGroupError::ModeNotString(
                    yaml_type_name(&other).into(),
                ));
            }
        };

        let include = Self::normalize_list(get("include"), "include");
        let exclude = Self::normalize_list(get("exclude"), "exclude");

        // disable_env accepts both snake_case and camelCase.
        let raw_disable_env = get("disable_env").or_else(|| get("disableEnv"));
        let disable_env = match raw_disable_env {
            None | Some(Value::Null) => false,
            Some(Value::Bool(b)) => b,
            Some(other) => {
                tracing::warn!(
                    "apcli.disable_env must be boolean; got {}. Treating as false.",
                    yaml_type_name(&other)
                );
                false
            }
        };

        Ok(Self {
            mode,
            include,
            exclude,
            disable_env,
            registry_injected,
            from_cli_config: false,
        })
    }

    /// Normalize a yaml include/exclude list. Non-array → warn + empty.
    /// Unknown-but-well-formed entries emit a warning but are retained for
    /// forward compatibility (spec §7 / T-APCLI-25).
    fn normalize_list(raw: Option<serde_yaml::Value>, label: &str) -> Vec<String> {
        use serde_yaml::Value;
        let raw = match raw {
            None | Some(Value::Null) => return Vec::new(),
            Some(v) => v,
        };
        let seq = match raw {
            Value::Sequence(s) => s,
            other => {
                tracing::warn!(
                    "apcli.{} must be a list; got {}. Ignoring.",
                    label,
                    yaml_type_name(&other)
                );
                return Vec::new();
            }
        };
        let mut out = Vec::with_capacity(seq.len());
        for entry in seq {
            match entry {
                Value::String(s) if !s.is_empty() => {
                    if !APCLI_SUBCOMMAND_NAMES.contains(&s.as_str()) {
                        tracing::warn!(
                            "Unknown apcli subcommand '{}' in {} list -- ignoring.",
                            s,
                            label
                        );
                    }
                    out.push(s);
                }
                _ => {
                    tracing::warn!("apcli.{} contains non-string entry; skipping.", label);
                }
            }
        }
        out
    }

    /// Emit the unknown-subcommand warnings for a strongly-typed list from
    /// `ApcliConfig` (Tier 1). Mirrors the yaml-path warnings so behaviour
    /// is identical regardless of where the config originated.
    fn warn_unknown_entries(list: &[String], label: &str) {
        for entry in list {
            if !APCLI_SUBCOMMAND_NAMES.contains(&entry.as_str()) {
                tracing::warn!(
                    "Unknown apcli subcommand '{}' in {} list -- ignoring.",
                    entry,
                    label
                );
            }
        }
    }

    // -------------------------------------------------------------------------
    // Public API
    // -------------------------------------------------------------------------

    /// Resolve effective visibility after applying the four-tier precedence.
    ///
    /// Returns one of `"all" | "none" | "include" | "exclude"` — never
    /// `"auto"`. Tier order (spec §4.4):
    ///
    /// 1. `from_cli_config` with a non-auto mode wins outright.
    /// 2. `APCORE_CLI_APCLI` env var (unless sealed by `disable_env`).
    /// 3. yaml non-auto mode.
    /// 4. Auto-detect: `registry_injected ? "none" : "all"`.
    pub fn resolve_visibility(&self) -> &'static str {
        // Tier 1 — programmatic embedder config (non-auto).
        if self.from_cli_config && self.mode != InternalMode::Auto {
            return self.mode.as_str();
        }

        // Tier 2 — env var (unless sealed).
        if !self.disable_env {
            if let Some(env_mode) = Self::parse_env(std::env::var("APCORE_CLI_APCLI").ok()) {
                return env_mode;
            }
        }

        // Tier 3 — yaml non-auto.
        if self.mode != InternalMode::Auto {
            return self.mode.as_str();
        }

        // Tier 4 — auto-detect.
        if self.registry_injected {
            "none"
        } else {
            "all"
        }
    }

    /// Return true iff `subcommand` passes the include/exclude filter.
    ///
    /// Callers MUST first check [`ApcliGroup::resolve_visibility`] — this
    /// method panics if called under modes `"all"` or `"none"` (caller bug
    /// per spec §4.6).
    pub fn is_subcommand_included(&self, subcommand: &str) -> bool {
        match self.resolve_visibility() {
            "include" => self.include.iter().any(|s| s == subcommand),
            "exclude" => !self.exclude.iter().any(|s| s == subcommand),
            other => unreachable!(
                "is_subcommand_included called under mode '{other}'; caller should bypass."
            ),
        }
    }

    /// True iff the `apcli` group itself should appear in root `--help`.
    pub fn is_group_visible(&self) -> bool {
        self.resolve_visibility() != "none"
    }

    /// Enumerate the effective include list. Empty unless resolved mode is
    /// `"include"`.
    pub fn include(&self) -> &[String] {
        &self.include
    }

    /// Enumerate the effective exclude list. Empty unless resolved mode is
    /// `"exclude"`.
    pub fn exclude(&self) -> &[String] {
        &self.exclude
    }

    /// True iff Tier 2 env-var lookup is sealed.
    pub fn disable_env(&self) -> bool {
        self.disable_env
    }

    // -------------------------------------------------------------------------
    // Env parser (Tier 2) — co-located per spec §4.4
    // -------------------------------------------------------------------------

    /// Parse `APCORE_CLI_APCLI`. Case-insensitive.
    ///
    /// - `show` / `1` / `true` → `Some("all")`
    /// - `hide` / `0` / `false` → `Some("none")`
    /// - Empty / unset → `None`
    /// - Anything else → warn and return `None`
    fn parse_env(raw: Option<String>) -> Option<&'static str> {
        let raw = raw?;
        if raw.is_empty() {
            return None;
        }
        let normalized = raw.to_lowercase();
        match normalized.as_str() {
            "show" | "1" | "true" => Some("all"),
            "hide" | "0" | "false" => Some("none"),
            _ => {
                tracing::warn!(
                    "Unknown APCORE_CLI_APCLI value '{}', ignoring. \
                     Expected: show, hide, 1, 0, true, false.",
                    raw
                );
                None
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn yaml_type_name(v: &serde_yaml::Value) -> &'static str {
    use serde_yaml::Value;
    match v {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Sequence(_) => "array",
        Value::Mapping(_) => "object",
        Value::Tagged(_) => "tagged",
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_yaml::Value;
    use std::sync::Mutex;

    /// Serializes tests that set/unset `APCORE_CLI_APCLI`. Same pattern as
    /// the `resolve_log_level` tests in `main.rs`.
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    fn clear_env() {
        // SAFETY: test-only env manipulation, serialized via ENV_MUTEX.
        unsafe {
            std::env::remove_var("APCORE_CLI_APCLI");
        }
    }

    fn set_env(val: &str) {
        // SAFETY: test-only env manipulation, serialized via ENV_MUTEX.
        unsafe {
            std::env::set_var("APCORE_CLI_APCLI", val);
        }
    }

    // ----- Constants -----

    #[test]
    fn apcli_subcommand_names_has_13_entries() {
        assert_eq!(APCLI_SUBCOMMAND_NAMES.len(), 13);
    }

    #[test]
    fn apcli_subcommand_names_contents() {
        for expected in &[
            "list",
            "describe",
            "exec",
            "validate",
            "init",
            "health",
            "usage",
            "enable",
            "disable",
            "reload",
            "config",
            "completion",
            "describe-pipeline",
        ] {
            assert!(
                APCLI_SUBCOMMAND_NAMES.contains(expected),
                "missing: {expected}"
            );
        }
    }

    #[test]
    fn reserved_group_names_contents() {
        assert_eq!(RESERVED_GROUP_NAMES, &["apcli"]);
    }

    // ----- Tier 1: from_cli_config -----

    #[test]
    fn from_cli_config_all_wins_in_embedded() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::All,
                disable_env: false,
            }),
            /*registry_injected*/ true,
        );
        assert_eq!(group.resolve_visibility(), "all");
    }

    #[test]
    fn from_cli_config_none_default_standalone_autodetect_all() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_cli_config(None, /*registry_injected*/ false);
        assert_eq!(group.resolve_visibility(), "all");
    }

    #[test]
    fn from_cli_config_none_default_embedded_autodetect_none() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_cli_config(None, /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "none");
    }

    #[test]
    fn from_cli_config_none_mode_beats_env_show() {
        // Tier 1 (None) > Tier 2 (env=show). Even without disable_env, an
        // explicit Tier-1 (programmatic) mode wins — defence in depth.
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("show");
        let group = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::None,
                disable_env: false,
            }),
            /*registry_injected*/ false,
        );
        assert_eq!(group.resolve_visibility(), "none");
        clear_env();
    }

    // ----- Tier 3: from_yaml (bool shorthand) -----

    #[test]
    fn from_yaml_bool_true_embedded_all() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_yaml(Some(Value::Bool(true)), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "all");
    }

    #[test]
    fn from_yaml_bool_false_standalone_none() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group =
            ApcliGroup::from_yaml(Some(Value::Bool(false)), /*registry_injected*/ false);
        assert_eq!(group.resolve_visibility(), "none");
    }

    #[test]
    fn from_yaml_null_value_auto() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_yaml(Some(Value::Null), /*registry_injected*/ false);
        assert_eq!(group.resolve_visibility(), "all");
    }

    #[test]
    fn from_yaml_none_auto() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_yaml(None, /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "none");
    }

    // ----- Tier 2: env var overrides -----

    #[test]
    fn from_yaml_null_env_show_all() {
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("show");
        let group = ApcliGroup::from_yaml(None, /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "all");
        clear_env();
    }

    #[test]
    fn from_yaml_null_env_hide_none() {
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("hide");
        let group = ApcliGroup::from_yaml(None, /*registry_injected*/ false);
        assert_eq!(group.resolve_visibility(), "none");
        clear_env();
    }

    #[test]
    fn from_yaml_mode_none_env_show_env_wins() {
        // Tier 2 > Tier 3 when disable_env is false.
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("show");
        let yaml: Value = serde_yaml::from_str("mode: none").unwrap();
        let group = ApcliGroup::from_yaml(Some(yaml), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "all");
        clear_env();
    }

    #[test]
    fn from_yaml_mode_none_disable_env_env_show_yaml_wins() {
        // disable_env: true seals Tier 2 — yaml mode:none wins.
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("show");
        let yaml: Value = serde_yaml::from_str("mode: none\ndisable_env: true").unwrap();
        let group = ApcliGroup::from_yaml(Some(yaml), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "none");
        clear_env();
    }

    #[test]
    fn from_yaml_disable_env_camel_case_also_accepted() {
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("show");
        let yaml: Value = serde_yaml::from_str("mode: none\ndisableEnv: true").unwrap();
        let group = ApcliGroup::from_yaml(Some(yaml), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "none");
        clear_env();
    }

    #[test]
    fn env_case_insensitive_show() {
        let _g = ENV_MUTEX.lock().unwrap();
        for raw in &["SHOW", "Show", "sHoW"] {
            set_env(raw);
            let group = ApcliGroup::from_yaml(None, true);
            assert_eq!(group.resolve_visibility(), "all", "raw={raw}");
        }
        clear_env();
    }

    #[test]
    fn env_case_insensitive_true_hide_false_numeric() {
        let _g = ENV_MUTEX.lock().unwrap();
        for (raw, expected) in &[
            ("True", "all"),
            ("TRUE", "all"),
            ("HIDE", "none"),
            ("False", "none"),
            ("1", "all"),
            ("0", "none"),
        ] {
            set_env(raw);
            let group = ApcliGroup::from_yaml(None, true);
            assert_eq!(group.resolve_visibility(), *expected, "raw={raw}");
        }
        clear_env();
    }

    #[test]
    fn env_unknown_value_falls_through() {
        // parse_env with a bogus value returns None (after warning) — so
        // Tier 4 auto-detect takes over.
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("bogus");
        let group = ApcliGroup::from_yaml(None, /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "none");
        clear_env();
    }

    #[test]
    fn env_empty_string_treated_as_unset() {
        let _g = ENV_MUTEX.lock().unwrap();
        set_env("");
        let group = ApcliGroup::from_yaml(None, /*registry_injected*/ false);
        assert_eq!(group.resolve_visibility(), "all");
        clear_env();
    }

    // ----- Include / Exclude semantics -----

    #[test]
    fn include_mode_filters_correctly() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let yaml: Value =
            serde_yaml::from_str("mode: include\ninclude:\n  - list\n  - describe").unwrap();
        let group = ApcliGroup::from_yaml(Some(yaml), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "include");
        assert!(group.is_subcommand_included("list"));
        assert!(group.is_subcommand_included("describe"));
        assert!(!group.is_subcommand_included("init"));
        assert!(!group.is_subcommand_included("exec"));
        assert_eq!(group.include(), &["list", "describe"]);
        assert!(group.exclude().is_empty());
    }

    #[test]
    fn exclude_mode_filters_correctly() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let yaml: Value = serde_yaml::from_str("mode: exclude\nexclude:\n  - init").unwrap();
        let group = ApcliGroup::from_yaml(Some(yaml), /*registry_injected*/ true);
        assert_eq!(group.resolve_visibility(), "exclude");
        assert!(!group.is_subcommand_included("init"));
        assert!(group.is_subcommand_included("list"));
        assert!(group.is_subcommand_included("describe"));
        assert!(group.include().is_empty());
        assert_eq!(group.exclude(), &["init"]);
    }

    #[test]
    fn from_cli_config_include_variant_filters_correctly() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let group = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::Include(vec!["list".into(), "describe".into()]),
                disable_env: false,
            }),
            /*registry_injected*/ true,
        );
        assert_eq!(group.resolve_visibility(), "include");
        assert!(group.is_subcommand_included("list"));
        assert!(!group.is_subcommand_included("init"));
    }

    // ----- Group visibility -----

    #[test]
    fn is_group_visible_false_only_for_none_mode() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let hidden = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::None,
                disable_env: false,
            }),
            true,
        );
        assert!(!hidden.is_group_visible());

        let shown = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::All,
                disable_env: false,
            }),
            true,
        );
        assert!(shown.is_group_visible());

        let include = ApcliGroup::from_cli_config(
            Some(ApcliConfig {
                mode: ApcliMode::Include(vec!["list".into()]),
                disable_env: false,
            }),
            true,
        );
        assert!(include.is_group_visible());
    }

    // ----- Validation errors -----

    #[test]
    fn try_from_yaml_rejects_mode_auto() {
        // Even though Auto is the internal default, user-supplied "auto"
        // is rejected per spec §4.2.
        let yaml: Value = serde_yaml::from_str("mode: auto").unwrap();
        let err = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap_err();
        assert!(matches!(err, ApcliGroupError::ModeInvalid(ref s) if s == "auto"));
    }

    #[test]
    fn try_from_yaml_rejects_unknown_mode() {
        let yaml: Value = serde_yaml::from_str("mode: whitelist").unwrap();
        let err = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap_err();
        assert!(matches!(err, ApcliGroupError::ModeInvalid(_)));
    }

    #[test]
    fn try_from_yaml_rejects_non_string_mode() {
        let yaml: Value = serde_yaml::from_str("mode: 42").unwrap();
        let err = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap_err();
        assert!(matches!(err, ApcliGroupError::ModeNotString(_)));
    }

    #[test]
    fn try_from_yaml_rejects_array_shape() {
        let yaml: Value = serde_yaml::from_str("- a\n- b").unwrap();
        let err = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap_err();
        assert!(matches!(err, ApcliGroupError::InvalidShape(ref s) if s == "array"));
    }

    #[test]
    fn try_from_yaml_rejects_string_shape() {
        let yaml = Value::String("oops".into());
        let err = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap_err();
        assert!(matches!(err, ApcliGroupError::InvalidShape(ref s) if s == "string"));
    }

    // ----- Tier-3 object form with extras -----

    #[test]
    fn try_from_yaml_object_without_mode_is_auto() {
        let _g = ENV_MUTEX.lock().unwrap();
        clear_env();
        let yaml: Value = serde_yaml::from_str("disable_env: true").unwrap();
        let group = ApcliGroup::try_from_yaml(Some(yaml), /*registry_injected*/ false).unwrap();
        // Tier 3 falls to Tier 4 auto-detect → standalone → "all".
        assert_eq!(group.resolve_visibility(), "all");
        assert!(group.disable_env());
    }

    #[test]
    fn try_from_yaml_include_non_array_warns_and_empty() {
        let yaml: Value = serde_yaml::from_str("mode: include\ninclude: not-a-list").unwrap();
        let group = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap();
        assert_eq!(group.resolve_visibility(), "include");
        assert!(group.include().is_empty());
    }

    #[test]
    fn try_from_yaml_unknown_include_entry_retained() {
        let yaml: Value =
            serde_yaml::from_str("mode: include\ninclude:\n  - list\n  - bogus").unwrap();
        let group = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap();
        // Unknown entry is retained for forward-compat.
        assert_eq!(group.include(), &["list", "bogus"]);
    }

    #[test]
    fn try_from_yaml_disable_env_non_bool_treated_as_false() {
        let yaml: Value = serde_yaml::from_str("mode: none\ndisable_env: \"yes-please\"").unwrap();
        let group = ApcliGroup::try_from_yaml(Some(yaml), true).unwrap();
        assert!(!group.disable_env());
    }
}