cargo-rail 0.31.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
//! Unify configuration - controls workspace dependency unification behavior

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};

/// Top-level resolution domains where Unify acquires compiler evidence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CompilerTargetSelection {
    /// Every top-level resolution domain: `"all"`. A legacy empty list means the same.
    #[default]
    All,
    /// No domain: `"none"`. Unify resolves dependencies but withholds compiler-proven removals.
    None,
    /// One exact non-empty subset of the top-level targets.
    Explicit(Vec<String>),
}

impl Serialize for CompilerTargetSelection {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::All => serializer.serialize_str("all"),
            Self::None => serializer.serialize_str("none"),
            Self::Explicit(targets) => targets.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for CompilerTargetSelection {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Representation {
            Mode(String),
            Explicit(Vec<String>),
        }

        match Representation::deserialize(deserializer)? {
            Representation::Mode(mode) if mode == "all" => Ok(Self::All),
            Representation::Mode(mode) if mode == "none" => Ok(Self::None),
            Representation::Mode(mode) => Err(de::Error::custom(format!(
                "unify.compiler_targets mode must be 'all' or 'none', found '{mode}'"
            ))),
            // Earlier releases printed the inherited default as an empty list.
            Representation::Explicit(targets) if targets.is_empty() => Ok(Self::All),
            Representation::Explicit(targets) => Ok(Self::Explicit(targets)),
        }
    }
}

impl CompilerTargetSelection {
    /// Whether the selection inherits every resolution domain.
    pub(crate) fn inherits_all(&self) -> bool {
        matches!(self, Self::All)
    }

    fn explicit(&self) -> &[String] {
        match self {
            Self::Explicit(targets) => targets,
            Self::All | Self::None => &[],
        }
    }
}

/// Defines which consumers may activate private workspace configuration.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ConsumerScope {
    /// Consumers may exist outside this workspace; dormant configuration is preserved.
    #[default]
    Open,
    /// This workspace is the complete consumer universe for `publish = false` packages.
    Workspace,
}

impl ConsumerScope {
    /// Stable configuration spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Workspace => "workspace",
        }
    }
}

/// Unify configuration - controls workspace dependency unification behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnifyConfig {
    /// Standalone Cargo workspace roots whose dependency declarations Unify also repairs.
    #[serde(default)]
    pub cargo_manifests: Vec<std::path::PathBuf>,
    /// Top-level target-resolution domains used for compiler evidence.
    ///
    /// `"all"` (the default) selects every top-level target. A list selects only
    /// the domains where Unify's compiler evidence command is valid on this host.
    /// `"none"` acquires no compiler evidence. Unselected domains remain part of
    /// dependency resolution and conservatively prevent edits that require their
    /// missing evidence.
    #[serde(default)]
    pub compiler_targets: CompilerTargetSelection,

    /// Handle path dependencies? (default: true)
    /// If false, path dependencies are excluded from unification
    #[serde(default = "default_include_paths")]
    pub include_paths: bool,

    /// Handle renamed dependencies (package = "...")? (default: false)
    /// Renamed deps are tricky to unify correctly, opt-in only
    #[serde(default)]
    pub include_renamed: bool,

    /// Host-owned pins for fragmented transitive features and their owning manifest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transitive_pinning: Option<TransitivePinning>,

    /// Dependencies to exclude from unification (safety hatch)
    ///
    /// Workspace-member dependencies are handled as connected cohorts.
    /// Excluding one member excludes the full cohort atomically to avoid
    /// local-vs-registry split graphs.
    #[serde(default)]
    pub exclude: Vec<String>,

    /// Dependencies to force-include in unification (safety hatch)
    ///
    /// Workspace-member cohorts are auto-included by cargo-rail to prevent
    /// single-user threshold splits; this option is mainly for non-member deps.
    #[serde(default)]
    pub include: Vec<String>,

    /// Maximum number of backups to keep (default: 3)
    /// Older backups are automatically cleaned up after successful unify operations
    #[serde(default = "default_max_backups")]
    pub max_backups: usize,

    /// Byte count at which compiler-artifact acquisition reports storage pressure.
    #[serde(default = "default_compiler_artifact_soft_limit_bytes")]
    pub compiler_artifact_soft_limit_bytes: u64,

    /// Maximum filesystem consumption authorized for the command-owned compiler working set.
    #[serde(default = "default_compiler_artifact_hard_limit_bytes")]
    pub compiler_artifact_hard_limit_bytes: u64,

    /// MSRV computation and inheritance policy.
    #[serde(default)]
    pub msrv_policy: MsrvPolicy,

    /// Consumer boundary used by destructive feature and optional-dependency pruning.
    ///
    /// `open` reports dormant configuration without removing it. `workspace`
    /// authorizes removal from `publish = false` packages after complete
    /// reachability and post-edit graph verification.
    #[serde(default)]
    pub consumer_scope: ConsumerScope,

    /// Features to preserve from dead feature pruning (glob patterns supported)
    /// Use this to keep features intended for future use or external consumers.
    /// Examples: ["future-api", "unstable-*", "bench*"]
    #[serde(default)]
    pub preserve_features: Vec<String>,

    /// Strict version compatibility checking (default: true)
    /// When true, version mismatches between member manifests and existing
    /// workspace.dependencies are reported as blocking errors.
    /// When false, they are warnings only.
    #[serde(default = "default_true")]
    pub strict_version_compat: bool,

    /// How to handle exact version pins like "=0.8.0" (default: "warn")
    /// - "skip": Exclude exact-pinned deps from unification
    /// - "preserve": Keep the exact pin operator in workspace.dependencies
    /// - "warn": Convert to caret but emit a warning
    #[serde(default)]
    pub exact_pin_handling: ExactPinHandling,

    /// How to handle major version conflicts (default: "warn")
    /// - "warn": Skip unification and emit a warning (both versions stay in graph)
    /// - "bump": Force unify to highest resolved version (user accepts breakage risk)
    #[serde(default)]
    pub major_version_conflict: MajorVersionConflict,

    /// Patterns for features to skip in undeclared feature detection (glob supported)
    /// Default: ["default", "std", "alloc", "*_backend", "*_impl"]
    /// These are features that are typically not actionable or are implementation details.
    #[serde(default = "default_skip_undeclared_patterns")]
    pub skip_undeclared_patterns: Vec<String>,
}

impl Default for UnifyConfig {
    fn default() -> Self {
        Self {
            cargo_manifests: Vec::new(),
            compiler_targets: CompilerTargetSelection::All,
            include_paths: default_include_paths(),
            include_renamed: false,
            transitive_pinning: None,
            exclude: Vec::new(),
            include: Vec::new(),
            max_backups: default_max_backups(),
            compiler_artifact_soft_limit_bytes: default_compiler_artifact_soft_limit_bytes(),
            compiler_artifact_hard_limit_bytes: default_compiler_artifact_hard_limit_bytes(),
            msrv_policy: MsrvPolicy::default(),
            consumer_scope: ConsumerScope::default(),
            preserve_features: Vec::new(),
            strict_version_compat: true,
            exact_pin_handling: ExactPinHandling::default(),
            major_version_conflict: MajorVersionConflict::default(),
            skip_undeclared_patterns: default_skip_undeclared_patterns(),
        }
    }
}

impl UnifyConfig {
    /// Resolve compiler-evidence targets from the captured resolution domains.
    pub fn effective_compiler_targets<'a>(&self, workspace_targets: &[&'a str]) -> Vec<&'a str> {
        match &self.compiler_targets {
            CompilerTargetSelection::All => workspace_targets.to_vec(),
            CompilerTargetSelection::None => Vec::new(),
            CompilerTargetSelection::Explicit(selected) => workspace_targets
                .iter()
                .copied()
                .filter(|target| selected.iter().any(|configured| configured == target))
                .collect(),
        }
    }

    /// Validate compiler-evidence targets against the top-level resolution authority.
    pub fn validate_workspace_targets(&self, workspace_targets: &[String]) -> Result<(), crate::error::ConfigError> {
        let mut unique = std::collections::BTreeSet::new();
        for target in self.compiler_targets.explicit() {
            if target.trim().is_empty() || target != target.trim() {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.compiler_targets".to_string(),
                    message: "targets must be non-empty and have no surrounding whitespace".to_string(),
                });
            }
            if !unique.insert(target) {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.compiler_targets".to_string(),
                    message: format!("contains duplicate target '{target}'"),
                });
            }
            if !workspace_targets.contains(target) {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.compiler_targets".to_string(),
                    message: format!("target '{target}' is not declared in top-level targets"),
                });
            }
        }
        Ok(())
    }

    /// Check if a dependency should be excluded from unification
    pub fn should_exclude(&self, dep_name: &str) -> bool {
        self.exclude.iter().any(|e| e == dep_name)
    }

    /// Check if a dependency should be force-included in unification
    pub fn should_include(&self, dep_name: &str) -> bool {
        self.include.iter().any(|i| i == dep_name)
    }

    /// Check if a feature should be preserved from dead feature pruning
    ///
    /// Supports glob patterns (e.g., "unstable-*", "bench*")
    pub fn should_preserve_feature(&self, feature_name: &str) -> bool {
        matches_feature_pattern(&self.preserve_features, feature_name)
    }

    /// Check if a feature should be skipped in undeclared feature detection
    ///
    /// Supports glob patterns (e.g., "*_backend", "*_impl")
    pub fn should_skip_undeclared_feature(&self, feature_name: &str) -> bool {
        matches_feature_pattern(&self.skip_undeclared_patterns, feature_name)
    }

    /// Validate unify configuration against the workspace
    ///
    /// Checks:
    /// - transitive pinning host path exists if configured as a path (not "root")
    /// - transitive pinning host path contains a Cargo.toml
    pub fn validate(&self, workspace_root: &std::path::Path) -> Result<(), crate::error::ConfigError> {
        self.validate_policy()?;
        self.validate_host(workspace_root)
    }

    pub(crate) fn validate_policy(&self) -> Result<(), crate::error::ConfigError> {
        let mut manifests = std::collections::BTreeSet::new();
        for path in &self.cargo_manifests {
            if path.is_absolute()
                || path
                    .components()
                    .any(|component| !matches!(component, std::path::Component::Normal(_)))
                || path.file_name().is_none_or(|name| name != "Cargo.toml")
                || path == std::path::Path::new("Cargo.toml")
                || !manifests.insert(path)
            {
                return Err(crate::error::ConfigError::InvalidField {
                    field: "unify.cargo_manifests".into(),
                    reason: "use unique workspace-relative standalone Cargo.toml paths without traversal".into(),
                });
            }
        }
        validate_glob_patterns("unify.preserve_features", &self.preserve_features)?;
        validate_glob_patterns("unify.skip_undeclared_patterns", &self.skip_undeclared_patterns)?;

        if self.compiler_artifact_soft_limit_bytes == 0 {
            return Err(crate::error::ConfigError::InvalidValue {
                field: "unify.compiler_artifact_soft_limit_bytes".to_string(),
                message: "must be greater than zero".to_string(),
            });
        }
        if self.compiler_artifact_hard_limit_bytes < self.compiler_artifact_soft_limit_bytes {
            return Err(crate::error::ConfigError::InvalidValue {
                field: "unify.compiler_artifact_hard_limit_bytes".to_string(),
                message: "must be greater than or equal to compiler_artifact_soft_limit_bytes".to_string(),
            });
        }

        if let Some(TransitivePinning {
            host: TransitiveFeatureHost::Path(p),
        }) = &self.transitive_pinning
        {
            // Check for path traversal (security/consistency)
            if p.contains("..") {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.transitive_pinning.host".to_string(),
                    message: format!("path '{}' contains '..' traversal, which is not allowed", p),
                });
            }

            // Check path is not absolute
            if std::path::Path::new(p).is_absolute() {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.transitive_pinning.host".to_string(),
                    message: format!("path '{}' is absolute, must be relative to workspace root", p),
                });
            }
        }
        Ok(())
    }

    pub(crate) fn transitive_host_path(&self) -> Option<&str> {
        match self.transitive_pinning.as_ref().map(|pinning| &pinning.host) {
            Some(TransitiveFeatureHost::Path(path)) => Some(path),
            _ => None,
        }
    }

    pub(crate) fn validate_host(&self, workspace_root: &std::path::Path) -> Result<(), crate::error::ConfigError> {
        if let Some(p) = self.transitive_host_path() {
            // Check directory exists
            let full_path = workspace_root.join(p);
            if !full_path.exists() {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.transitive_pinning.host".to_string(),
                    message: format!("path '{}' does not exist", p),
                });
            }

            // Check Cargo.toml exists at that path
            let cargo_toml = full_path.join("Cargo.toml");
            if !cargo_toml.exists() {
                return Err(crate::error::ConfigError::InvalidValue {
                    field: "unify.transitive_pinning.host".to_string(),
                    message: format!("path '{}' does not contain a Cargo.toml", p),
                });
            }
        }

        Ok(())
    }
}

fn matches_feature_pattern(patterns: &[String], feature_name: &str) -> bool {
    patterns.iter().any(|pattern| {
        if pattern.contains(['*', '?', '[']) {
            glob::Pattern::new(pattern).is_ok_and(|pattern| pattern.matches(feature_name))
        } else {
            pattern == feature_name
        }
    })
}

fn validate_glob_patterns(field: &str, patterns: &[String]) -> Result<(), crate::error::ConfigError> {
    for pattern in patterns {
        glob::Pattern::new(pattern).map_err(|error| crate::error::ConfigError::InvalidGlobPattern {
            pattern: pattern.clone(),
            message: format!("{field}: {error}"),
        })?;
    }
    Ok(())
}

/// How to determine the final MSRV (Minimum Supported Rust Version)
///
/// Controls how cargo-rail computes the rust-version to write to [workspace.package].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MsrvSource {
    /// Use the maximum dependency rust-version as the candidate floor.
    ///
    /// A higher existing workspace declaration is retained because dependency
    /// metadata does not prove that the workspace compiles on an older compiler.
    Deps,
    /// Preserve existing workspace rust-version
    ///
    /// Keeps the existing [workspace.package].rust-version unchanged.
    /// Emits a warning if dependencies require a higher version.
    Workspace,
    /// Take max(workspace, deps) - default
    ///
    /// Uses the higher of the existing workspace rust-version or the
    /// maximum from dependencies. Your explicit workspace setting wins
    /// if it requires a higher Rust version than your dependencies.
    #[default]
    Max,
}

/// How to handle exact version pins ("=x.y.z") during unification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExactPinHandling {
    /// Exclude exact-pinned deps from unification entirely
    Skip,
    /// Preserve the exact pin operator in workspace.dependencies
    Preserve,
    /// Convert to caret (^) but emit a warning (default)
    #[default]
    Warn,
}

/// How to handle major version conflicts during unification
///
/// Major version conflicts occur when the same dependency is declared with
/// different major versions across workspace members (e.g., `serde = "1.0"` and `serde = "2.0"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MajorVersionConflict {
    /// Skip unification and emit a warning (default)
    ///
    /// Both versions remain in the build graph. This is the safe choice when
    /// you want to avoid breaking changes but may result in duplicate compilation.
    #[default]
    Warn,
    /// Force unify to the highest resolved version
    ///
    /// Uses the highest version from the resolved metadata across all target triples.
    /// Use when you want the leanest build graph and accept breakage risk.
    Bump,
}

/// Configuration for where to add dev-dependencies when consolidating transitive features
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TransitiveFeatureHost {
    /// Use workspace root Cargo.toml (default)
    #[default]
    Root,
    /// Use a specific member crate (relative path from workspace root)
    Path(String),
}

// Custom serialization/deserialization for TransitiveFeatureHost
impl Serialize for TransitiveFeatureHost {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            TransitiveFeatureHost::Root => serializer.serialize_str("root"),
            TransitiveFeatureHost::Path(path) => serializer.serialize_str(path),
        }
    }
}

impl<'de> Deserialize<'de> for TransitiveFeatureHost {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct TransitiveFeatureHostVisitor;

        impl serde::de::Visitor<'_> for TransitiveFeatureHostVisitor {
            type Value = TransitiveFeatureHost;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("'root' or a path string")
            }

            fn visit_str<E>(self, value: &str) -> Result<TransitiveFeatureHost, E>
            where
                E: serde::de::Error,
            {
                match value {
                    "root" => Ok(TransitiveFeatureHost::Root),
                    path => Ok(TransitiveFeatureHost::Path(path.to_string())),
                }
            }
        }

        deserializer.deserialize_any(TransitiveFeatureHostVisitor)
    }
}

/// Enabled host-owned pinning policy for fragmented transitive features.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransitivePinning {
    /// Manifest that owns the generated transitive dev-dependencies.
    #[serde(default)]
    pub host: TransitiveFeatureHost,
}

/// MSRV computation and member-inheritance policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(tag = "mode", rename_all = "lowercase", deny_unknown_fields)]
pub enum MsrvPolicy {
    /// Do not compute or write workspace MSRV.
    Disabled,
    /// Compute workspace MSRV from the selected authoritative sources.
    Compute {
        /// Inputs used to choose the final version.
        #[serde(default)]
        source: MsrvSource,
        /// Whether members inherit the computed workspace value.
        #[serde(default)]
        inherit: bool,
    },
}

#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum MsrvPolicyMode {
    Disabled,
    #[default]
    Compute,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MsrvPolicyInput {
    #[serde(default)]
    mode: MsrvPolicyMode,
    source: Option<MsrvSource>,
    inherit: Option<bool>,
}

impl<'de> Deserialize<'de> for MsrvPolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let input = MsrvPolicyInput::deserialize(deserializer)?;
        match input.mode {
            MsrvPolicyMode::Disabled if input.source.is_some() || input.inherit.is_some() => Err(
                serde::de::Error::custom("disabled MSRV policy does not accept `source` or `inherit`"),
            ),
            MsrvPolicyMode::Disabled => Ok(Self::Disabled),
            MsrvPolicyMode::Compute => Ok(Self::Compute {
                source: input.source.unwrap_or_default(),
                inherit: input.inherit.unwrap_or_default(),
            }),
        }
    }
}

impl Default for MsrvPolicy {
    fn default() -> Self {
        Self::Compute {
            source: MsrvSource::default(),
            inherit: false,
        }
    }
}

impl MsrvPolicy {
    /// Source policy when computation is enabled.
    pub const fn source(self) -> Option<MsrvSource> {
        match self {
            Self::Disabled => None,
            Self::Compute { source, .. } => Some(source),
        }
    }

    /// Whether workspace members must inherit the computed value.
    pub const fn inherits(self) -> bool {
        matches!(self, Self::Compute { inherit: true, .. })
    }
}

// Default Functions

fn default_max_backups() -> usize {
    3
}

const fn default_compiler_artifact_soft_limit_bytes() -> u64 {
    32 * 1024 * 1024 * 1024
}

const fn default_compiler_artifact_hard_limit_bytes() -> u64 {
    64 * 1024 * 1024 * 1024
}

fn default_include_paths() -> bool {
    true
}

pub(crate) fn default_true() -> bool {
    true
}

fn default_skip_undeclared_patterns() -> Vec<String> {
    const PATTERNS: &[&str] = &["default", "std", "alloc", "*_backend", "*_impl"];
    PATTERNS.iter().map(|&s| String::from(s)).collect()
}

// Tests

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

    #[test]
    fn test_unify_config_defaults() {
        let config = UnifyConfig::default();
        assert_eq!(config.compiler_targets, CompilerTargetSelection::All);
        assert!(config.include_paths); // Default: true
        assert!(!config.include_renamed); // Default: false
        assert!(config.transitive_pinning.is_none());
        assert!(config.exclude.is_empty());
        assert!(config.include.is_empty());
        assert_eq!(config.msrv_policy.source(), Some(MsrvSource::Max));
        assert_eq!(config.consumer_scope, ConsumerScope::Open);
        assert_eq!(config.compiler_artifact_soft_limit_bytes, 32 * 1024 * 1024 * 1024);
        assert_eq!(config.compiler_artifact_hard_limit_bytes, 64 * 1024 * 1024 * 1024);
    }

    #[test]
    fn compiler_targets_are_an_exact_resolution_subset() {
        let config: UnifyConfig =
            toml_edit::de::from_str(r#"compiler_targets = ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"]"#)
                .unwrap();
        let workspace_targets = [
            "aarch64-apple-darwin".to_string(),
            "thumbv6m-none-eabi".to_string(),
            "x86_64-unknown-linux-gnu".to_string(),
        ];
        config.validate_workspace_targets(&workspace_targets).unwrap();
        let resolution_targets = workspace_targets.iter().map(String::as_str).collect::<Vec<_>>();
        assert_eq!(
            config.effective_compiler_targets(&resolution_targets),
            ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"]
        );

        let outside: UnifyConfig = toml_edit::de::from_str(r#"compiler_targets = ["wasm32-wasip1"]"#).unwrap();
        assert!(outside.validate_workspace_targets(&workspace_targets).is_err());
        let duplicate: UnifyConfig =
            toml_edit::de::from_str(r#"compiler_targets = ["aarch64-apple-darwin", "aarch64-apple-darwin"]"#).unwrap();
        assert!(duplicate.validate_workspace_targets(&workspace_targets).is_err());
    }

    #[test]
    fn compiler_target_modes_keep_legacy_empty_lists_on_every_target() {
        let resolution_targets = ["aarch64-apple-darwin", "thumbv6m-none-eabi"];
        // Omitted, "all", and the empty list printed by earlier releases all select every target.
        for input in ["", "compiler_targets = \"all\"", "compiler_targets = []"] {
            let config: UnifyConfig = toml_edit::de::from_str(input).unwrap();
            assert_eq!(config.compiler_targets, CompilerTargetSelection::All, "{input}");
            assert_eq!(
                config.effective_compiler_targets(&resolution_targets),
                resolution_targets,
                "{input}"
            );
            assert!(
                toml_edit::ser::to_string(&config)
                    .unwrap()
                    .contains("compiler_targets = \"all\""),
                "{input}"
            );
        }
        let none: UnifyConfig = toml_edit::de::from_str("compiler_targets = \"none\"").unwrap();
        none.validate_workspace_targets(&resolution_targets.map(str::to_string))
            .unwrap();
        assert!(none.effective_compiler_targets(&resolution_targets).is_empty());
        assert!(
            toml_edit::ser::to_string(&none)
                .unwrap()
                .contains("compiler_targets = \"none\"")
        );
        let error = toml_edit::de::from_str::<UnifyConfig>("compiler_targets = \"host\"").unwrap_err();
        assert!(error.to_string().contains("must be 'all' or 'none'"), "{error}");
    }

    #[test]
    fn compiler_artifact_budget_rejects_zero_or_reversed_limits() {
        let workspace = tempfile::tempdir().expect("workspace");
        let zero = UnifyConfig {
            compiler_artifact_soft_limit_bytes: 0,
            ..UnifyConfig::default()
        };
        assert!(
            zero.validate(workspace.path())
                .expect_err("zero soft limit")
                .to_string()
                .contains("soft_limit_bytes")
        );

        let reversed = UnifyConfig {
            compiler_artifact_soft_limit_bytes: 2048,
            compiler_artifact_hard_limit_bytes: 1024,
            ..UnifyConfig::default()
        };
        assert!(
            reversed
                .validate(workspace.path())
                .expect_err("reversed limits")
                .to_string()
                .contains("hard_limit_bytes")
        );
    }

    #[test]
    fn test_unify_config_should_exclude() {
        let config = UnifyConfig {
            exclude: vec!["tokio".to_string(), "serde".to_string()],
            ..Default::default()
        };
        assert!(config.should_exclude("tokio"));
        assert!(config.should_exclude("serde"));
        assert!(!config.should_exclude("regex"));
    }

    #[test]
    fn test_unify_config_should_include() {
        let config = UnifyConfig {
            include: vec!["special-dep".to_string()],
            ..Default::default()
        };
        assert!(config.should_include("special-dep"));
        assert!(!config.should_include("normal-dep"));
    }

    #[test]
    fn test_unify_config_default_transitive_host() {
        let config = UnifyConfig::default();
        assert!(config.transitive_pinning.is_none());
    }

    #[test]
    fn typed_unify_policies_parse_without_invalid_combinations() {
        let config: UnifyConfig = toml_edit::de::from_str(
            r#"
      transitive_pinning = { host = "crates/host" }
      msrv_policy = { mode = "compute", source = "workspace", inherit = true }
      "#,
        )
        .unwrap();
        assert_eq!(
            config.transitive_pinning,
            Some(TransitivePinning {
                host: TransitiveFeatureHost::Path("crates/host".to_string())
            })
        );
        assert_eq!(
            config.msrv_policy,
            MsrvPolicy::Compute {
                source: MsrvSource::Workspace,
                inherit: true
            }
        );
    }

    #[test]
    fn msrv_policy_defaults_partial_compute_and_preserves_explicit_modes() {
        let partial: UnifyConfig = toml_edit::de::from_str("msrv_policy = { inherit = true }").unwrap();
        assert_eq!(
            partial.msrv_policy,
            MsrvPolicy::Compute {
                source: MsrvSource::Max,
                inherit: true,
            }
        );

        let complete: UnifyConfig =
            toml_edit::de::from_str(r#"msrv_policy = { mode = "compute", source = "workspace", inherit = false }"#)
                .unwrap();
        assert_eq!(
            complete.msrv_policy,
            MsrvPolicy::Compute {
                source: MsrvSource::Workspace,
                inherit: false,
            }
        );

        let disabled: UnifyConfig = toml_edit::de::from_str(r#"msrv_policy = { mode = "disabled" }"#).unwrap();
        assert_eq!(disabled.msrv_policy, MsrvPolicy::Disabled);
        assert!(
            toml_edit::de::from_str::<UnifyConfig>(r#"msrv_policy = { mode = "disabled", inherit = false }"#,).is_err(),
            "disabled policy must reject compute-only fields"
        );
    }

    #[test]
    fn test_consumer_scope_requires_explicit_workspace_contract() {
        let default = UnifyConfig::default();
        assert_eq!(default.consumer_scope, ConsumerScope::Open);

        let config: UnifyConfig = toml_edit::de::from_str("consumer_scope = \"workspace\"").unwrap();
        assert_eq!(config.consumer_scope, ConsumerScope::Workspace);

        let invalid = toml_edit::de::from_str::<UnifyConfig>("consumer_scope = \"private\"");
        assert!(
            invalid.is_err(),
            "unknown trust boundaries must fail configuration parsing"
        );
    }

    #[test]
    fn test_strict_version_compat_default() {
        let config = UnifyConfig::default();
        assert!(config.strict_version_compat); // Default is true
    }

    #[test]
    fn test_exact_pin_handling_default() {
        let config = UnifyConfig::default();
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Warn);
    }

    #[test]
    fn test_exact_pin_handling_parsing() {
        let toml = r#"exact_pin_handling = "skip""#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Skip);

        let toml = r#"exact_pin_handling = "preserve""#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Preserve);

        let toml = r#"exact_pin_handling = "warn""#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Warn);
    }

    #[test]
    fn test_new_config_options_parsing() {
        let toml = r#"
      strict_version_compat = false
      exact_pin_handling = "preserve"
    "#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert!(!config.strict_version_compat);
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Preserve);
    }

    #[test]
    fn test_major_version_conflict_default() {
        let config = UnifyConfig::default();
        assert_eq!(config.major_version_conflict, MajorVersionConflict::Warn);
    }

    #[test]
    fn test_major_version_conflict_parsing() {
        let toml = r#"major_version_conflict = "warn""#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.major_version_conflict, MajorVersionConflict::Warn);

        let toml = r#"major_version_conflict = "bump""#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.major_version_conflict, MajorVersionConflict::Bump);
    }

    #[test]
    fn test_major_version_conflict_with_other_options() {
        let toml = r#"
      strict_version_compat = false
      exact_pin_handling = "preserve"
      major_version_conflict = "bump"
    "#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert!(!config.strict_version_compat);
        assert_eq!(config.exact_pin_handling, ExactPinHandling::Preserve);
        assert_eq!(config.major_version_conflict, MajorVersionConflict::Bump);
    }

    #[test]
    fn test_transitive_host_validate_root() {
        // Root should always be valid
        let config = UnifyConfig {
            transitive_pinning: Some(TransitivePinning {
                host: TransitiveFeatureHost::Root,
            }),
            ..Default::default()
        };
        let workspace = std::env::current_dir().unwrap();
        config.validate(&workspace).unwrap();
    }

    #[test]
    fn test_transitive_host_validate_valid_path() {
        let config = UnifyConfig::default();
        let workspace = std::env::current_dir().unwrap();
        config.validate(&workspace).unwrap();
    }

    #[test]
    fn test_transitive_host_validate_nonexistent_path() {
        let config = UnifyConfig {
            transitive_pinning: Some(TransitivePinning {
                host: TransitiveFeatureHost::Path("nonexistent/path".to_string()),
            }),
            ..Default::default()
        };
        let workspace = std::env::current_dir().unwrap();
        let result = config.validate(&workspace);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, crate::error::ConfigError::InvalidValue { .. }));
    }

    #[test]
    fn test_transitive_host_validate_path_traversal() {
        let config = UnifyConfig {
            transitive_pinning: Some(TransitivePinning {
                host: TransitiveFeatureHost::Path("../somewhere".to_string()),
            }),
            ..Default::default()
        };
        let workspace = std::env::current_dir().unwrap();
        let result = config.validate(&workspace);
        assert!(result.is_err());
        let err = result.unwrap_err();
        if let crate::error::ConfigError::InvalidValue { message, .. } = err {
            assert!(message.contains(".."));
        } else {
            panic!("Expected InvalidValue error");
        }
    }

    #[test]
    fn invalid_feature_globs_fail_validation() {
        for (field, config) in [
            (
                "unify.preserve_features",
                UnifyConfig {
                    preserve_features: vec!["[".to_string()],
                    ..Default::default()
                },
            ),
            (
                "unify.skip_undeclared_patterns",
                UnifyConfig {
                    skip_undeclared_patterns: vec!["[".to_string()],
                    ..Default::default()
                },
            ),
        ] {
            let error = config.validate(std::path::Path::new(".")).unwrap_err();
            assert!(
                matches!(
                  error,
                  crate::error::ConfigError::InvalidGlobPattern {
                    ref message,
                    ..
                  } if message.contains(field)
                ),
                "{field} should reject malformed glob patterns"
            );
        }
    }

    #[test]
    fn test_preserve_features_default() {
        let config = UnifyConfig::default();
        assert!(config.preserve_features.is_empty());
    }

    #[test]
    fn test_preserve_features_parsing() {
        let toml = r#"
      preserve_features = ["future-api", "unstable-*", "bench*"]
    "#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.preserve_features.len(), 3);
        assert!(config.preserve_features.contains(&"future-api".to_string()));
        assert!(config.preserve_features.contains(&"unstable-*".to_string()));
        assert!(config.preserve_features.contains(&"bench*".to_string()));
    }

    #[test]
    fn test_should_preserve_feature_exact_match() {
        let config = UnifyConfig {
            preserve_features: vec!["future-api".to_string(), "experimental".to_string()],
            ..Default::default()
        };
        assert!(config.should_preserve_feature("future-api"));
        assert!(config.should_preserve_feature("experimental"));
        assert!(!config.should_preserve_feature("other-feature"));
    }

    #[test]
    fn test_should_preserve_feature_glob_wildcard() {
        let config = UnifyConfig {
            preserve_features: vec!["unstable-*".to_string()],
            ..Default::default()
        };
        assert!(config.should_preserve_feature("unstable-api"));
        assert!(config.should_preserve_feature("unstable-feature"));
        assert!(config.should_preserve_feature("unstable-"));
        assert!(!config.should_preserve_feature("unstable")); // No trailing dash
        assert!(!config.should_preserve_feature("stable-api"));
    }

    #[test]
    fn test_should_preserve_feature_glob_suffix() {
        let config = UnifyConfig {
            preserve_features: vec!["bench*".to_string()],
            ..Default::default()
        };
        assert!(config.should_preserve_feature("bench"));
        assert!(config.should_preserve_feature("benchmark"));
        assert!(config.should_preserve_feature("benchmarks"));
        assert!(!config.should_preserve_feature("prebench"));
    }

    #[test]
    fn test_should_preserve_feature_glob_question_mark() {
        let config = UnifyConfig {
            preserve_features: vec!["test-?".to_string()],
            ..Default::default()
        };
        assert!(config.should_preserve_feature("test-a"));
        assert!(config.should_preserve_feature("test-1"));
        assert!(!config.should_preserve_feature("test-ab")); // Two chars
        assert!(!config.should_preserve_feature("test-")); // No char
    }

    #[test]
    fn test_should_preserve_feature_multiple_patterns() {
        let config = UnifyConfig {
            preserve_features: vec!["future-api".to_string(), "unstable-*".to_string(), "bench*".to_string()],
            ..Default::default()
        };
        // Exact match
        assert!(config.should_preserve_feature("future-api"));
        // Glob matches
        assert!(config.should_preserve_feature("unstable-feature"));
        assert!(config.should_preserve_feature("benchmark"));
        // Non-matches
        assert!(!config.should_preserve_feature("stable-api"));
        assert!(!config.should_preserve_feature("other"));
    }

    #[test]
    fn test_should_preserve_feature_empty_list() {
        let config = UnifyConfig::default();
        assert!(!config.should_preserve_feature("any-feature"));
    }

    #[test]
    fn test_msrv_source_default() {
        let config = UnifyConfig::default();
        assert_eq!(config.msrv_policy.source(), Some(MsrvSource::Max));
    }

    // skip_undeclared_patterns Tests

    #[test]
    fn test_skip_undeclared_patterns_default() {
        let config = UnifyConfig::default();
        assert!(!config.skip_undeclared_patterns.is_empty());
        assert!(config.skip_undeclared_patterns.contains(&"default".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"std".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"alloc".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"*_backend".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"*_impl".to_string()));
    }

    #[test]
    fn test_skip_undeclared_patterns_parsing() {
        let toml = r#"
      skip_undeclared_patterns = ["default", "std", "custom-*"]
    "#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert_eq!(config.skip_undeclared_patterns.len(), 3);
        assert!(config.skip_undeclared_patterns.contains(&"default".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"std".to_string()));
        assert!(config.skip_undeclared_patterns.contains(&"custom-*".to_string()));
    }

    #[test]
    fn test_skip_undeclared_patterns_empty() {
        let toml = r#"
      skip_undeclared_patterns = []
    "#;
        let config: UnifyConfig = toml_edit::de::from_str(toml).unwrap();
        assert!(config.skip_undeclared_patterns.is_empty());
    }

    #[test]
    fn test_should_skip_undeclared_feature_exact_match() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec!["default".to_string(), "std".to_string()],
            ..Default::default()
        };
        assert!(config.should_skip_undeclared_feature("default"));
        assert!(config.should_skip_undeclared_feature("std"));
        assert!(!config.should_skip_undeclared_feature("derive"));
    }

    #[test]
    fn test_should_skip_undeclared_feature_glob_suffix() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec!["*_backend".to_string()],
            ..Default::default()
        };
        assert!(config.should_skip_undeclared_feature("sqlite_backend"));
        assert!(config.should_skip_undeclared_feature("postgres_backend"));
        assert!(config.should_skip_undeclared_feature("_backend")); // Just suffix
        assert!(!config.should_skip_undeclared_feature("backend"));
        assert!(!config.should_skip_undeclared_feature("backend_"));
    }

    #[test]
    fn test_should_skip_undeclared_feature_glob_prefix() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec!["unstable-*".to_string()],
            ..Default::default()
        };
        assert!(config.should_skip_undeclared_feature("unstable-api"));
        assert!(config.should_skip_undeclared_feature("unstable-internal"));
        assert!(config.should_skip_undeclared_feature("unstable-")); // Just prefix
        assert!(!config.should_skip_undeclared_feature("unstable"));
    }

    #[test]
    fn test_should_skip_undeclared_feature_glob_question_mark() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec!["test-?".to_string()],
            ..Default::default()
        };
        assert!(config.should_skip_undeclared_feature("test-1"));
        assert!(config.should_skip_undeclared_feature("test-a"));
        assert!(!config.should_skip_undeclared_feature("test-12"));
        assert!(!config.should_skip_undeclared_feature("test-"));
    }

    #[test]
    fn test_should_skip_undeclared_feature_multiple_patterns() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec![
                "default".to_string(),
                "std".to_string(),
                "*_backend".to_string(),
                "*_impl".to_string(),
            ],
            ..Default::default()
        };
        assert!(config.should_skip_undeclared_feature("default"));
        assert!(config.should_skip_undeclared_feature("std"));
        assert!(config.should_skip_undeclared_feature("sqlite_backend"));
        assert!(config.should_skip_undeclared_feature("sync_impl"));
        assert!(!config.should_skip_undeclared_feature("derive"));
        assert!(!config.should_skip_undeclared_feature("serde"));
    }

    #[test]
    fn test_should_skip_undeclared_feature_empty_patterns() {
        let config = UnifyConfig {
            skip_undeclared_patterns: vec![],
            ..Default::default()
        };
        // Nothing should be skipped with empty patterns
        assert!(!config.should_skip_undeclared_feature("default"));
        assert!(!config.should_skip_undeclared_feature("std"));
        assert!(!config.should_skip_undeclared_feature("anything"));
    }
}