trait-kit 0.2.3

Module Standard Interface and Capability Management Center — A lightweight Rust library that provides a standard interface for module definition and Kit capability management.
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
use std::sync::Arc;

use static_assertions::assert_not_impl_any;
use trait_kit::prelude::*;

// Compile-time guarantee: Kit is !Sync by design (uses RefCell for interior
// mutability on single-threaded typestate builds).
assert_not_impl_any!(Kit<Unbuilt>: Sync);
assert_not_impl_any!(Kit<Ready>: Sync);

struct StdoutLogger;
impl StdoutLogger {
    fn info(&self, msg: &str) {
        println!("[LOG] {msg}");
    }
}

struct LoggerModule;
impl ModuleMeta for LoggerModule {
    const NAME: &'static str = "logger";
    fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
        &[]
    }
}
impl AutoBuilder for LoggerModule {
    type Capability = Arc<StdoutLogger>;
    type Error = KitError;

    fn build(_kit: &Kit) -> Result<Self::Capability, Self::Error> {
        Ok(Arc::new(StdoutLogger))
    }
}

#[derive(Clone, Debug)]
struct DbConfig {
    #[allow(dead_code)]
    url: String,
    max_connections: u32,
}

struct DbPool {
    _logger: Arc<StdoutLogger>,
    config: DbConfig,
}

struct DbPoolModule;
impl ModuleMeta for DbPoolModule {
    const NAME: &'static str = "db_pool";
    fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
        static DEPS: &[(&str, std::any::TypeId)] =
            &[("logger", std::any::TypeId::of::<LoggerModule>())];
        DEPS
    }
}
impl AutoBuilder for DbPoolModule {
    type Capability = Arc<DbPool>;
    type Error = KitError;

    fn build(kit: &Kit) -> Result<Self::Capability, Self::Error> {
        let logger = kit.require::<LoggerModule>()?;
        let config: DbConfig = kit.config()?;
        Ok(Arc::new(DbPool {
            _logger: logger,
            config,
        }))
    }
}

#[test]
fn test_basic_build_and_require() {
    let mut kit = Kit::new();
    kit.register::<LoggerModule>().unwrap();
    let kit = kit.build().unwrap();

    let logger = kit.require::<LoggerModule>().unwrap();
    logger.info("hello from test");
    assert!(kit.contains::<LoggerModule>());
}

#[test]
fn test_dependency_resolution() {
    let mut kit = Kit::new();
    kit.set_config(DbConfig {
        url: "postgres://localhost".into(),
        max_connections: 10,
    });
    kit.register::<LoggerModule>().unwrap();
    kit.register::<DbPoolModule>().unwrap();
    let kit = kit.build().unwrap();

    let pool = kit.require::<DbPoolModule>().unwrap();
    assert_eq!(pool.config.max_connections, 10);
}

#[test]
fn test_missing_config_error() {
    let mut kit = Kit::new();
    kit.register::<LoggerModule>().unwrap();
    kit.register::<DbPoolModule>().unwrap();
    let result = kit.build();

    assert!(result.is_err());
    match result.unwrap_err() {
        KitError::BuildFailed { context, .. } => assert_eq!(context, "db_pool"),
        other => panic!("expected BuildFailed, got: {other}"),
    }
}

#[test]
fn test_missing_dependency_error() {
    let mut kit = Kit::new();
    kit.register::<DbPoolModule>().unwrap();
    let result = kit.build();

    assert!(result.is_err());
    match result.unwrap_err() {
        KitError::DependencyMissing { module, missing } => {
            assert_eq!(module, "db_pool");
            assert_eq!(missing, "logger");
        }
        other => panic!("expected DependencyMissing, got: {other}"),
    }
}

#[test]
fn test_duplicate_registration_error() {
    let mut kit = Kit::new();
    kit.register::<LoggerModule>().unwrap();
    let result = kit.register::<LoggerModule>();

    assert!(result.is_err());
    match result.unwrap_err() {
        KitError::AlreadyRegistered { module } => assert_eq!(module, "logger"),
        other => panic!("expected AlreadyRegistered, got: {other}"),
    }
}

#[test]
fn test_config_retrieval() {
    let mut kit = Kit::new();
    kit.set_config(DbConfig {
        url: "postgres://localhost".into(),
        max_connections: 5,
    });
    kit.register::<LoggerModule>().unwrap();
    let kit = kit.build().unwrap();

    let config: DbConfig = kit.config().unwrap();
    assert_eq!(config.max_connections, 5);
}

#[test]
fn test_missing_config_retrieval() {
    let mut kit = Kit::new();
    kit.register::<LoggerModule>().unwrap();
    let kit = kit.build().unwrap();

    let result = kit.config::<DbConfig>();
    assert!(result.is_err());
}

#[test]
fn test_optional_missing() {
    let mut kit = Kit::new();
    kit.register::<LoggerModule>().unwrap();
    let kit = kit.build().unwrap();

    let result = kit.optional::<DbPoolModule>();
    assert!(result.is_none());
}

#[test]
fn test_cycle_detection() {
    // This test needs two modules that depend on each other.
    // We can't easily create a cycle with ModuleMeta since dependencies
    // are static. Instead, test that the graph validator catches cycles.
    use trait_kit::kit::graph::DependencyGraph;
    use trait_kit::kit::graph::ModuleEntry;

    let mut graph = DependencyGraph::new();
    graph
        .add(ModuleEntry {
            type_id: std::any::TypeId::of::<LoggerModule>(),
            name: "a",
            dependencies: vec![("b", std::any::TypeId::of::<DbPoolModule>())],
        })
        .unwrap();
    graph
        .add(ModuleEntry {
            type_id: std::any::TypeId::of::<DbPoolModule>(),
            name: "b",
            dependencies: vec![("a", std::any::TypeId::of::<LoggerModule>())],
        })
        .unwrap();

    let result = graph.validate();
    assert!(result.is_err());
}

#[test]
fn kit_error_display_and_source_behavior() {
    use std::error::Error;

    // Display: NotReady (deprecated — typestate pattern makes it unreachable)
    #[allow(deprecated)]
    let not_ready = KitError::NotReady;
    assert_eq!(
        not_ready.to_string(),
        "kit is not ready; call build() first"
    );

    // Display: CycleDetected
    let cycle = KitError::CycleDetected {
        cycle: vec!["a", "b", "a"],
    };
    assert_eq!(cycle.to_string(), "dependency cycle detected: a → b → a");

    // Display: DependencyMissing
    let dep = KitError::DependencyMissing {
        module: "db",
        missing: "logger",
    };
    assert_eq!(
        dep.to_string(),
        "module `db` depends on `logger` which is not registered"
    );

    // Display: AlreadyRegistered
    let dup = KitError::AlreadyRegistered { module: "logger" };
    assert_eq!(dup.to_string(), "module `logger` is already registered");

    // Display: MissingCapability
    let cap = KitError::MissingCapability { key: "logger" };
    assert_eq!(cap.to_string(), "missing capability `logger`");

    // Display: MissingConfig
    let cfg = KitError::MissingConfig { key: "db_url" };
    assert_eq!(cfg.to_string(), "missing config `db_url`");

    // Display: BuildFailed (contains source message)
    let source: Box<dyn Error + Send + Sync> = "inner failure".into();
    let build = KitError::BuildFailed {
        context: "db",
        source,
    };
    assert!(build.to_string().contains("failed to build `db`"));
    assert!(build.to_string().contains("inner failure"));

    // Error::source() for BuildFailed returns Some
    assert!(build.source().is_some());

    // Error::source() for other variants returns None
    #[allow(deprecated)]
    {
        assert!(KitError::NotReady.source().is_none());
    }
    assert!(cycle.source().is_none());
    assert!(dep.source().is_none());
}

#[cfg(feature = "confers")]
mod confers_loader {
    use std::error::Error;
    use trait_kit::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct StubConfig {
        value: u32,
    }

    impl Configurable for StubConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Ok(Self { value: 42 })
        }
    }

    #[test]
    fn load_config_stores_value_when_load_succeeds() {
        let kit = Kit::new();
        kit.load_config::<StubConfig>()
            .expect("load should succeed");
        let kit = kit.build().expect("build should succeed");

        assert!(kit.contains_config::<StubConfig>());
        let stored: StubConfig = kit.config().expect("config should be retrievable");
        assert_eq!(stored.value, 42);
    }

    #[derive(Clone, Debug)]
    struct FailingConfig;

    impl Configurable for FailingConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Err(Box::new(std::io::Error::other("intentional load failure")))
        }
    }

    #[test]
    fn load_config_propagates_error_when_load_fails() {
        let kit = Kit::new();
        let result = kit.load_config::<FailingConfig>();

        match result {
            Err(KitError::BuildFailed { context, source }) => {
                assert_eq!(context, "load_config");
                assert!(source.to_string().contains("intentional load failure"));
            }
            other => panic!("expected BuildFailed, got: {other:?}"),
        }
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct OverridableConfig {
        value: &'static str,
    }

    impl Configurable for OverridableConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Ok(Self { value: "loaded" })
        }
    }

    #[test]
    fn load_config_overrides_prior_set_config() {
        let kit = Kit::new();
        kit.set_config(OverridableConfig { value: "initial" });
        kit.load_config::<OverridableConfig>()
            .expect("load should override prior value");
        let kit = kit.build().expect("build should succeed");

        let stored: OverridableConfig = kit.config().expect("config should be retrievable");
        assert_eq!(stored.value, "loaded");
    }
}

#[cfg(feature = "confers")]
mod confers_derive_bridge {
    use serial_test::serial;
    use std::error::Error;
    use trait_kit::prelude::*;

    #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, confers::Config)]
    #[config(env_prefix = "TRAIT_KIT_T026_")]
    struct DerivedConfig {
        #[config(default = "fallback_value".to_string())]
        field: String,
    }

    impl Configurable for DerivedConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            match DerivedConfig::load_sync() {
                Ok(c) => Ok(c),
                Err(e) => Err(Box::new(std::io::Error::other(e.to_string()))),
            }
        }
    }

    #[test]
    #[serial]
    fn load_config_bridges_to_confers_derive_load_sync() {
        std::env::remove_var("TRAIT_KIT_T026_FIELD");

        let kit = Kit::new();
        kit.load_config::<DerivedConfig>()
            .expect("load should succeed via confers derive load_sync()");
        let kit = kit.build().expect("build should succeed");

        let config: DerivedConfig = kit.config().expect("config should be retrievable");
        assert_eq!(config.field, "fallback_value");
        drop(kit);

        std::env::set_var("TRAIT_KIT_T026_FIELD", "from_env");
        let kit = Kit::new();
        let result = kit.load_config::<DerivedConfig>();
        std::env::remove_var("TRAIT_KIT_T026_FIELD");

        let kit = match result {
            Ok(()) => kit.build().expect("build should succeed"),
            Err(e) => panic!("load_config failed: {e:?}"),
        };
        let config: DerivedConfig = kit.config().expect("config should be retrievable");
        assert_eq!(config.field, "from_env");
    }
}

#[cfg(feature = "confers-macros")]
mod module_config_trait {
    use trait_kit::kit::config::ModuleConfig;
    use trait_kit::kit::Config;

    #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, Config)]
    struct ModuleStub {
        #[config(default = "stub".to_string())]
        name: String,
    }

    impl ModuleConfig for ModuleStub {
        const PATH: &'static str = "config/module_stub.toml";

        fn default_value() -> Self {
            Self {
                name: "default".to_string(),
            }
        }
    }

    #[test]
    fn module_config_trait_requires_path_and_default() {
        assert_eq!(ModuleStub::PATH, "config/module_stub.toml");
        let default = ModuleStub::default_value();
        assert_eq!(default.name, "default");
    }

    #[test]
    fn derive_config_macro_re_exported() {
        // If this compiles, `use trait_kit::kit::Config;` succeeded.
        let _ = std::marker::PhantomData::<ModuleStub>;
    }
}

#[cfg(feature = "hot-reload")]
mod hot_reload {
    use std::cell::Cell;
    use std::error::Error;
    use std::rc::Rc;
    use trait_kit::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct ReloadableConfig {
        value: u32,
    }

    impl Configurable for ReloadableConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Ok(Self { value: 99 })
        }
    }

    #[test]
    fn subscribe_callback_invoked_on_reload() {
        let kit = Kit::new();
        let called = Rc::new(Cell::new(false));
        let called_clone = Rc::clone(&called);
        kit.subscribe::<ReloadableConfig>(move || {
            called_clone.set(true);
        });

        kit.reload_config::<ReloadableConfig>()
            .expect("reload should succeed");
        let kit = kit.build().expect("build should succeed");

        assert!(called.get(), "callback should have been invoked");
        let config: ReloadableConfig = kit.config().expect("config should be retrievable");
        assert_eq!(config.value, 99);
    }

    #[test]
    fn reload_config_updates_stored_value() {
        let kit = Kit::new();
        kit.set_config(ReloadableConfig { value: 1 });
        kit.reload_config::<ReloadableConfig>()
            .expect("reload should override prior value");
        let kit = kit.build().expect("build should succeed");

        let config: ReloadableConfig = kit.config().expect("config should be retrievable");
        assert_eq!(config.value, 99);
    }
}

#[cfg(feature = "encryption")]
mod encryption {
    use trait_kit::kit::config::ModuleConfig;
    use trait_kit::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
    struct SecretConfig {
        api_key: String,
        port: u16,
    }

    impl ModuleConfig for SecretConfig {
        const PATH: &'static str = "config/secret.toml";

        fn default_value() -> Self {
            Self {
                api_key: "default_key".to_string(),
                port: 8080,
            }
        }
    }

    // 32-byte master key for XChaCha20-Poly1305 + HKDF.
    // pragma: allowlist secret
    const MASTER_KEY: [u8; 32] = *b"0123456789abcdef0123456789abcdef";

    #[test]
    fn encrypted_config_roundtrip() {
        let kit = Kit::new();
        let original = SecretConfig {
            api_key: "sk-12345".to_string(),
            port: 5432,
        };
        kit.set_encrypted(&original, &MASTER_KEY)
            .expect("encrypt should succeed");
        assert!(kit.contains_encrypted::<SecretConfig>());
        let kit = kit.build().expect("build should succeed");

        let decrypted: SecretConfig = kit
            .get_encrypted(&MASTER_KEY)
            .expect("decrypt should succeed");
        assert_eq!(decrypted, original);
    }

    #[test]
    fn get_encrypted_fails_with_wrong_key() {
        let kit = Kit::new();
        let original = SecretConfig {
            api_key: "sk-12345".to_string(),
            port: 5432,
        };
        kit.set_encrypted(&original, &MASTER_KEY)
            .expect("encrypt should succeed");
        let kit = kit.build().expect("build should succeed");

        let wrong_key = *b"fedcba9876543210fedcba9876543210";
        let result: Result<SecretConfig, _> = kit.get_encrypted(&wrong_key);
        assert!(
            result.is_err(),
            "decryption with wrong key should fail (proves real encryption, not plaintext storage)"
        );
    }

    #[test]
    fn get_encrypted_returns_missing_config_error_when_not_set() {
        let kit = Kit::new();
        let kit = kit.build().expect("build should succeed");

        let result: Result<SecretConfig, _> = kit.get_encrypted(&MASTER_KEY);
        assert!(result.is_err());
        match result.unwrap_err() {
            KitError::MissingConfig { key } => {
                assert!(key.contains("SecretConfig"));
            }
            other => panic!("expected MissingConfig, got: {other:?}"),
        }
    }

    #[test]
    fn set_encrypted_overwrites_prior_value() {
        let kit = Kit::new();
        kit.set_encrypted(
            &SecretConfig {
                api_key: "old_key".to_string(),
                port: 1111,
            },
            &MASTER_KEY,
        )
        .expect("first encrypt should succeed");
        kit.set_encrypted(
            &SecretConfig {
                api_key: "new_key".to_string(),
                port: 2222,
            },
            &MASTER_KEY,
        )
        .expect("overwrite should succeed");
        let kit = kit.build().expect("build should succeed");

        let decrypted: SecretConfig = kit
            .get_encrypted(&MASTER_KEY)
            .expect("decrypt should return latest value");
        assert_eq!(decrypted.api_key, "new_key");
        assert_eq!(decrypted.port, 2222);
    }

    #[test]
    fn encrypted_storage_is_separate_from_plaintext_typemap() {
        // set_encrypted must NOT populate the plaintext TypeMap — the value
        // should only exist in encrypted_configs, retrievable solely via
        // get_encrypted with the correct master key.
        let kit = Kit::new();
        kit.set_encrypted(
            &SecretConfig {
                api_key: "sk-12345".to_string(),
                port: 5432,
            },
            &MASTER_KEY,
        )
        .expect("encrypt should succeed");
        assert!(kit.contains_encrypted::<SecretConfig>());
        let kit = kit.build().expect("build should succeed");
        // Plaintext TypeMap should NOT contain the config.
        assert!(!kit.contains_config::<SecretConfig>());
        assert!(kit.config::<SecretConfig>().is_err());
    }

    #[test]
    fn encrypted_blob_getters_via_roundtrip() {
        // The pub(crate) fields can't be constructed directly from
        // integration tests; verify getters indirectly by confirming
        // set_encrypted + get_encrypted round-trips (which exercises
        // nonce()/ciphertext() inside Kit::get_encrypted).
        let kit = Kit::new();
        kit.set_encrypted(
            &SecretConfig {
                api_key: "sk-12345".to_string(),
                port: 5432,
            },
            &MASTER_KEY,
        )
        .expect("encrypt should succeed");
        let kit = kit.build().expect("build should succeed");
        let ok: Result<SecretConfig, _> = kit.get_encrypted(&MASTER_KEY);
        assert!(ok.is_ok());
    }

    #[test]
    fn set_encrypted_propagates_serialization_error() {
        use trait_kit::kit::config::ModuleConfig;

        #[derive(Clone)]
        struct Unserializable;
        impl serde::Serialize for Unserializable {
            fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                Err(serde::ser::Error::custom("intentional serialize failure"))
            }
        }
        impl ModuleConfig for Unserializable {
            const PATH: &'static str = "config/unserializable.toml";
            fn default_value() -> Self {
                Self
            }
        }

        let kit = Kit::new();
        let result = kit.set_encrypted(&Unserializable, &MASTER_KEY);
        match result {
            Err(KitError::BuildFailed { context, source }) => {
                assert_eq!(context, "set_encrypted");
                assert!(source.to_string().contains("intentional serialize failure"));
            }
            other => panic!("expected BuildFailed, got: {other:?}"),
        }
    }
}

#[cfg(test)]
mod graph_coverage {
    use std::any::TypeId;
    use trait_kit::kit::graph::{DependencyGraph, GraphError, ModuleEntry};

    fn entry(name: &'static str, deps: Vec<(&'static str, TypeId)>) -> ModuleEntry {
        ModuleEntry {
            type_id: TypeId::of::<()>(),
            name,
            dependencies: deps,
        }
    }

    // Use distinct placeholder types so each entry has a unique TypeId.
    struct A;
    struct B;
    struct C;

    #[test]
    fn name_of_returns_registered_name() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![],
        })
        .unwrap();
        assert_eq!(g.name_of(TypeId::of::<A>()), Some("a"));
        assert_eq!(g.name_of(TypeId::of::<B>()), None);
    }

    #[test]
    fn dependency_names_returns_registered_deps() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![("b", TypeId::of::<B>())],
        })
        .unwrap();
        g.add(ModuleEntry {
            type_id: TypeId::of::<B>(),
            name: "b",
            dependencies: vec![],
        })
        .unwrap();
        assert_eq!(g.dependency_names(TypeId::of::<A>()), vec!["b"]);
        assert_eq!(g.dependency_names(TypeId::of::<B>()), Vec::<&str>::new());
        // Unknown type returns empty.
        assert_eq!(g.dependency_names(TypeId::of::<C>()), Vec::<&str>::new());
    }

    #[test]
    fn entries_returns_registration_order() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![],
        })
        .unwrap();
        g.add(ModuleEntry {
            type_id: TypeId::of::<B>(),
            name: "b",
            dependencies: vec![],
        })
        .unwrap();
        let names: Vec<_> = g.entries().iter().map(|e| e.name).collect();
        assert_eq!(names, vec!["a", "b"]);
    }

    #[test]
    fn default_creates_empty_graph() {
        let g = DependencyGraph::default();
        assert!(g.entries().is_empty());
    }

    #[test]
    fn add_rejects_duplicate_type_id() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![],
        })
        .unwrap();
        let err = g
            .add(ModuleEntry {
                type_id: TypeId::of::<A>(),
                name: "a_dup",
                dependencies: vec![],
            })
            .unwrap_err();
        assert_eq!(err, "a_dup");
    }

    #[test]
    fn validate_returns_dependency_missing_for_unknown_dep() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![("missing", TypeId::of::<B>())],
        })
        .unwrap();
        match g.validate() {
            Err(GraphError::DependencyMissing { module, missing }) => {
                assert_eq!(module, "a");
                assert_eq!(missing, "missing");
            }
            other => panic!("expected DependencyMissing, got: {other:?}"),
        }
    }

    #[test]
    fn find_cycle_traverses_unvisited_branch() {
        // Graph: a → b → c → b (cycle between b and c, a leads in)
        // This exercises the `if visited[dep_idx] == 0 && dfs(...)` true branch.
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![("b", TypeId::of::<B>())],
        })
        .unwrap();
        g.add(ModuleEntry {
            type_id: TypeId::of::<B>(),
            name: "b",
            dependencies: vec![("c", TypeId::of::<C>())],
        })
        .unwrap();
        g.add(ModuleEntry {
            type_id: TypeId::of::<C>(),
            name: "c",
            dependencies: vec![("b", TypeId::of::<B>())], // back-edge to b
        })
        .unwrap();

        match g.validate() {
            Err(GraphError::CycleDetected { cycle }) => {
                assert!(cycle.contains(&"b"));
                assert!(cycle.contains(&"c"));
            }
            other => panic!("expected CycleDetected, got: {other:?}"),
        }
    }

    #[test]
    fn validate_succeeds_for_acyclic_graph() {
        let mut g = DependencyGraph::new();
        g.add(ModuleEntry {
            type_id: TypeId::of::<A>(),
            name: "a",
            dependencies: vec![],
        })
        .unwrap();
        g.add(ModuleEntry {
            type_id: TypeId::of::<B>(),
            name: "b",
            dependencies: vec![("a", TypeId::of::<A>())],
        })
        .unwrap();
        assert!(g.validate().is_ok());
    }

    // Suppress unused warning for the helper.
    #[test]
    fn entry_helper_compiles() {
        let _ = entry("x", vec![]);
    }
}

mod kit_build_coverage {
    use std::sync::Arc;
    use trait_kit::prelude::*;

    struct CycleA;
    impl ModuleMeta for CycleA {
        const NAME: &'static str = "cycle_a";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            static DEPS: &[(&str, std::any::TypeId)] =
                &[("cycle_b", std::any::TypeId::of::<CycleB>())];
            DEPS
        }
    }
    impl AutoBuilder for CycleA {
        type Capability = Arc<()>;
        type Error = KitError;
        fn build(_kit: &Kit) -> Result<Self::Capability, Self::Error> {
            Ok(Arc::new(()))
        }
    }

    struct CycleB;
    impl ModuleMeta for CycleB {
        const NAME: &'static str = "cycle_b";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            static DEPS: &[(&str, std::any::TypeId)] =
                &[("cycle_a", std::any::TypeId::of::<CycleA>())];
            DEPS
        }
    }
    impl AutoBuilder for CycleB {
        type Capability = Arc<()>;
        type Error = KitError;
        fn build(_kit: &Kit) -> Result<Self::Capability, Self::Error> {
            Ok(Arc::new(()))
        }
    }

    #[test]
    fn kit_build_returns_cycle_detected_for_mutual_deps() {
        let mut kit = Kit::new();
        kit.register::<CycleA>().unwrap();
        kit.register::<CycleB>().unwrap();
        match kit.build() {
            Err(KitError::CycleDetected { cycle }) => {
                assert!(cycle.contains(&"cycle_a"));
                assert!(cycle.contains(&"cycle_b"));
            }
            other => panic!("expected CycleDetected, got: {other:?}"),
        }
    }

    #[test]
    fn kit_debug_shows_module_and_config_counts() {
        let mut kit = Kit::new();
        kit.set_config(42i32);
        kit.set_config("hello".to_string());
        let s = format!("{:?}", kit);
        assert!(s.contains("Kit<Unbuilt>"));
        assert!(s.contains("modules: 0"));
        assert!(s.contains("configs: 2"));

        kit.register::<CycleA>().unwrap();
        let s2 = format!("{:?}", kit);
        assert!(s2.contains("modules: 1"));
    }

    #[test]
    fn kit_ready_debug_shows_counts() {
        // Use a non-cyclic module so build() succeeds.
        struct Solo;
        impl ModuleMeta for Solo {
            const NAME: &'static str = "solo";
            fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
                &[]
            }
        }
        impl AutoBuilder for Solo {
            type Capability = Arc<()>;
            type Error = KitError;
            fn build(_kit: &Kit) -> Result<Self::Capability, Self::Error> {
                Ok(Arc::new(()))
            }
        }

        let mut kit = Kit::new();
        kit.set_config(99u64);
        kit.register::<Solo>().unwrap();
        let kit = kit.build().unwrap();
        let s = format!("{:?}", kit);
        assert!(s.contains("Kit<Ready>"));
        assert!(s.contains("modules: 1"));
        assert!(s.contains("configs: 1"));
    }

    #[test]
    fn kit_default_equals_new() {
        let kit = Kit::default();
        let s = format!("{:?}", kit);
        assert!(s.contains("modules: 0"));
        assert!(s.contains("configs: 0"));
    }
}

#[cfg(feature = "hot-reload")]
mod reload_config_coverage {
    use std::error::Error;
    use trait_kit::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct FailingReloadConfig;

    impl Configurable for FailingReloadConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Err(Box::new(std::io::Error::other(
                "reload intentional failure",
            )))
        }
    }

    #[test]
    fn reload_config_propagates_load_error() {
        let kit = Kit::new();
        let result = kit.reload_config::<FailingReloadConfig>();
        match result {
            Err(KitError::BuildFailed { context, source }) => {
                assert_eq!(context, "reload_config");
                assert!(source.to_string().contains("reload intentional failure"));
            }
            other => panic!("expected BuildFailed, got: {other:?}"),
        }
    }

    #[test]
    fn reload_config_invokes_multiple_subscribers() {
        use std::cell::Cell;
        use std::rc::Rc;

        #[derive(Clone, Debug, PartialEq, Eq)]
        struct MultiSubConfig;
        impl Configurable for MultiSubConfig {
            fn load() -> Result<Self, Box<dyn Error + Send>> {
                Ok(Self)
            }
        }

        let kit = Kit::new();
        let counter = Rc::new(Cell::new(0u32));
        let c1 = Rc::clone(&counter);
        let c2 = Rc::clone(&counter);

        kit.subscribe::<MultiSubConfig>(move || {
            c1.set(c1.get() + 1);
        });
        kit.subscribe::<MultiSubConfig>(move || {
            c2.set(c2.get() + 10);
        });

        kit.reload_config::<MultiSubConfig>()
            .expect("reload should succeed");

        // Both subscribers should have fired: 1 + 10 = 11.
        assert_eq!(counter.get(), 11);
    }

    #[test]
    fn subscribe_and_reload_with_no_subscribers_succeeds() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct NoSubConfig;
        impl Configurable for NoSubConfig {
            fn load() -> Result<Self, Box<dyn Error + Send>> {
                Ok(Self)
            }
        }
        let kit = Kit::new();
        // No subscribers registered — reload should still succeed.
        kit.reload_config::<NoSubConfig>()
            .expect("reload should succeed");
        let kit = kit.build().expect("build should succeed");
        let _: NoSubConfig = kit.config().expect("config should be stored");
    }
}

#[cfg(feature = "confers-macros")]
mod load_config_or_default_coverage {
    use std::error::Error;
    use trait_kit::kit::config::ModuleConfig;
    use trait_kit::prelude::*;

    #[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, trait_kit::kit::Config)]
    struct WithDefault {
        #[config(default = "loaded".to_string())]
        field: String,
    }

    impl ModuleConfig for WithDefault {
        const PATH: &'static str = "config/with_default.toml";
        fn default_value() -> Self {
            Self {
                field: "fallback".to_string(),
            }
        }
    }

    impl Configurable for WithDefault {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            // Simulate load failure — should fall back to default_value.
            Err(Box::new(std::io::Error::other(
                "load failed, using default",
            )))
        }
    }

    #[test]
    fn load_config_or_default_uses_default_when_load_fails() {
        let kit = Kit::new();
        kit.load_config_or_default::<WithDefault>()
            .expect("should never error");
        let kit = kit.build().expect("build should succeed");
        let cfg: WithDefault = kit.config().expect("config should be stored");
        assert_eq!(cfg.field, "fallback");
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct LoadOkConfig {
        v: u32,
    }

    impl ModuleConfig for LoadOkConfig {
        const PATH: &'static str = "config/load_ok.toml";
        fn default_value() -> Self {
            Self { v: 0 }
        }
    }

    impl Configurable for LoadOkConfig {
        fn load() -> Result<Self, Box<dyn Error + Send>> {
            Ok(Self { v: 42 })
        }
    }

    #[test]
    fn load_config_or_default_uses_loaded_value_when_load_succeeds() {
        let kit = Kit::new();
        kit.load_config_or_default::<LoadOkConfig>()
            .expect("should never error");
        let kit = kit.build().expect("build should succeed");
        let cfg: LoadOkConfig = kit.config().expect("config should be stored");
        assert_eq!(cfg.v, 42);
    }

    #[test]
    fn load_config_or_default_overrides_prior_set_config() {
        let kit = Kit::new();
        kit.set_config(LoadOkConfig { v: 1 });
        kit.load_config_or_default::<LoadOkConfig>()
            .expect("should override");
        let kit = kit.build().expect("build should succeed");
        let cfg: LoadOkConfig = kit.config().expect("config should be stored");
        assert_eq!(cfg.v, 42);
    }
}