cargo-rail 0.31.1

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
//! Core types for dependency unification
//!
//! This module contains all the data structures used by the unification system:
//! - `UnificationPlan` - the complete plan for unifying dependencies
//! - `UnifiedDep` - a dependency to add to workspace.dependencies
//! - `MemberEdit` - edits to apply to member Cargo.toml files
//! - Various issue and tracking types

use crate::cargo::manifest_analyzer::DepKind;
use crate::cargo::multi_target_metadata::ComputedMsrv;
use rustc_hash::FxHashMap;
use semver::VersionReq;
use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;

// Core Types

/// A dep that will be unified in [workspace.dependencies]
///
/// Uses `Arc<str>` for identifier fields to avoid redundant allocations.
/// The same package/feature names are shared across multiple structures.
#[derive(Debug, Clone)]
pub struct UnifiedDep {
    /// Workspace dependency key.
    pub name: Arc<str>,
    /// Actual package name when the workspace dependency key is renamed.
    pub package: Option<Arc<str>>,
    /// Version requirement (e.g., "^1.0.0")
    pub version_req: VersionReq,
    /// Features to enable (minimal intersection across all uses)
    pub features: Vec<Arc<str>>,
    /// Whether to enable default features
    pub default_features: bool,
    /// List of workspace members that use this dependency
    pub used_by: Vec<Arc<str>>,
    /// Target platform constraint (e.g., "cfg(unix)")
    pub target: Option<Arc<str>>,
    /// Local path for path dependencies
    pub path: Option<PathBuf>,
}

/// An edit to apply to a member's `Cargo.toml`
///
/// Uses `Arc<str>` for identifier fields to share allocations with source data.
#[derive(Debug, Clone)]
pub enum MemberEdit {
    /// Replace dep with workspace inheritance
    UseWorkspace {
        /// Name of the dependency to replace
        dep_name: Arc<str>,
        /// Type of dependency (normal, dev, build)
        dep_kind: DepKind,
        /// Target platform constraint (e.g., "cfg(unix)") - preserves which section to edit
        target: Option<Arc<str>>,
        /// Additional features to enable locally (beyond workspace features)
        local_features: Vec<Arc<str>>,
        /// Whether the dependency is optional
        is_optional: bool,
    },
    /// Remove an unused dep
    RemoveDep {
        /// Name of the dependency to remove
        dep_name: Arc<str>,
        /// Type of dependency (normal, dev, build)
        dep_kind: DepKind,
        /// Target platform constraint (if in target-specific section)
        target: Option<Arc<str>>,
    },
    /// Move a normal declaration, preserving its complete entry, into development dependencies.
    MoveToDev {
        /// Cargo dependency key, including a rename.
        dep_name: Arc<str>,
        /// Target predicate of the normal declaration.
        target: Option<Arc<str>>,
    },
    /// Remove a dead feature (empty no-op)
    RemoveFeature {
        /// Name of the feature to remove
        feature_name: Arc<str>,
    },
    /// Add missing features to a dependency (fix undeclared feature borrowing)
    AddFeatures {
        /// Name of the dependency to update
        dep_name: Arc<str>,
        /// Type of dependency (normal, dev, build)
        dep_kind: DepKind,
        /// Target platform constraint (if in target-specific section)
        target: Option<Arc<str>>,
        /// Features to add to the dependency
        features_to_add: Vec<Arc<str>>,
    },
    /// Ensure this crate inherits MSRV from the workspace
    ///
    /// Sets `[package].rust-version = { workspace = true }`.
    EnforceMsrvInheritance,
    /// Replace one semantically equivalent package field with workspace inheritance.
    InheritPackageField {
        /// Cargo package field under `[package]`.
        field: Arc<str>,
    },
}

/// Captured workspace-package policy compared with every member declaration.
#[derive(Debug, Clone)]
pub struct PackageInheritanceField {
    /// Cargo field declared by `[workspace.package]`.
    pub field: Arc<str>,
    /// Members that already inherit the field.
    pub inherited: Vec<Arc<str>>,
    /// Members whose equivalent explicit declaration will be inherited.
    pub planned: Vec<Arc<str>>,
    /// Members whose explicit declaration intentionally differs.
    pub local_overrides: Vec<Arc<str>>,
    /// Members that do not declare the field.
    pub missing: Vec<Arc<str>>,
    /// Equivalent declarations retained because another domain owns mutation policy.
    pub retained_equivalent: Vec<Arc<str>>,
    /// Stable reason for retaining equivalent declarations, when applicable.
    pub retention_reason: Option<&'static str>,
}

/// Issue that prevents or warns about unification
#[derive(Debug, Clone)]
pub struct UnifyIssue {
    /// Classification of the issue for machine-readable diagnostics
    pub kind: UnifyIssueKind,
    /// Name of the dependency with the issue
    pub dep_name: Arc<str>,
    /// Whether this blocks unification or is just a warning
    pub severity: IssueSeverity,
    /// Description of the issue
    pub message: Arc<str>,
}

/// Category of unification issue
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnifyIssueKind {
    /// Generic issue with no special category
    General,
    /// A workspace-member cohort would be split across local and registry sources
    WorkspaceMemberCohortSplitRisk,
    /// A declaration Cargo-Rail kept on purpose; nothing for a maintainer to decide
    Preserved,
}

/// Severity level of a unification issue
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// Blocks unification - must be resolved
    Error,
    /// Proceeds but with caution
    Warning,
    /// Records a decision; requires no action
    Info,
}

/// Record of a duplicate version that was cleaned up
#[derive(Debug, Clone)]
pub struct DuplicateCleanup {
    /// Dependency name
    pub dep_name: Arc<str>,
    /// Versions that were found across different targets
    pub versions_found: Vec<Arc<str>>,
    /// Version that was selected (always highest)
    pub selected_version: Arc<str>,
}

/// Record of a private feature proven unreachable from every feature root.
#[derive(Debug, Clone)]
pub struct PrunedFeature {
    /// Crate that declared the feature
    pub crate_name: Arc<str>,
    /// Feature name that was pruned
    pub feature_name: Arc<str>,
    /// Manifest edges removed with the unreachable feature declaration.
    pub declared_edges: Vec<Arc<str>>,
}

/// Root-to-feature path proving why a declared feature is retained.
#[derive(Debug, Clone)]
pub struct ReachableFeature {
    /// Crate declaring the feature.
    pub crate_name: Arc<str>,
    /// Reachable feature name.
    pub feature_name: Arc<str>,
    /// Semantic root category.
    pub root_kind: &'static str,
    /// Member-local path from root to feature.
    pub path: Vec<Arc<str>>,
}

/// Record of an optional feature that's not currently enabled but enables something
/// These are user-facing API and should NOT be automatically removed
#[derive(Debug, Clone)]
pub struct OptionalFeature {
    /// Crate that declared the feature
    pub crate_name: Arc<str>,
    /// Feature name
    pub feature_name: Arc<str>,
    /// What this feature enables (for reporting)
    pub enables: Vec<Arc<str>>,
}

/// Record of a version mismatch between member manifest and workspace.dependencies
#[derive(Debug, Clone)]
pub struct VersionMismatch {
    /// Member that has the mismatched version
    pub member: Arc<str>,
    /// Dependency name
    pub dep_name: Arc<str>,
    /// Version declared in the member's Cargo.toml
    pub member_version: Arc<str>,
    /// Version in workspace.dependencies
    pub workspace_version: Arc<str>,
}

/// Record of an unused dependency.
#[derive(Debug, Clone)]
pub struct UnusedDep {
    /// Member that has the unused dependency
    pub member: Arc<str>,
    /// Dependency name
    pub dep_name: Arc<str>,
    /// Kind of dependency (normal, dev, build)
    pub kind: DepKind,
    /// Cargo target constraint of the exact declaration, if any.
    pub target: Option<Arc<str>>,
    /// Why this dependency was flagged as unused
    pub reason: UnusedReason,
    /// Deterministic evidence certificate authorizing the removal decision.
    pub proof: DependencyProof,
}

/// Portable proof certificate for one dependency-removal decision.
#[derive(Debug, Clone)]
pub struct DependencyProof {
    /// Certificate schema version.
    pub schema_version: u32,
    /// Cargo package IDs resolved for the declaration.
    pub package_ids: Vec<Arc<str>>,
    /// rustc crate names observed for the declaration.
    pub crate_names: Vec<Arc<str>>,
    /// Evidence source (`compiler` or `resolved_graph`).
    pub evidence_source: &'static str,
    /// Number of applicable configurations.
    pub applicable_configurations: usize,
    /// Number of complete applicable configurations.
    pub complete_configurations: usize,
    /// Configurations containing positive usage evidence.
    pub used_observations: usize,
    /// Configurations containing exhaustive unused evidence.
    pub unused_observations: usize,
    /// Configurations with incomplete evidence.
    pub incomplete_observations: usize,
    /// Exact compiler-evidence cache hits contributing to the decision.
    pub cache_hits: usize,
    /// Compiler configurations recollected during this analysis.
    pub cache_misses: usize,
    /// Stable reasons why evidence could not be reused.
    pub cache_miss_reasons: Vec<Arc<str>>,
    /// Stable reasons why fresh evidence was not stored for later reuse.
    pub cache_publication_bypasses: Vec<Arc<str>>,
    /// Named uncertainties that would block this decision.
    pub uncertainties: Vec<Arc<str>>,
}

/// Reason a dependency was flagged as unused
#[derive(Debug, Clone)]
pub enum UnusedReason {
    /// Present in the resolved graph but reported as unused by rustc
    /// (`unused_crate_dependencies`).
    NotUsedInSource,
    /// Unused by production units and used by development units.
    DevelopmentOnly,
    /// Not found in resolved dependency graph for any configured target
    NotInResolvedGraph,
    /// Target-specific dep where the target IS configured but dep still not resolved
    /// (e.g., `[target.'cfg(windows)'.dependencies]` when windows target is configured)
    TargetConfiguredButNotResolved {
        /// The target cfg expression from the manifest
        target_cfg: Arc<str>,
    },
}

/// A fragmented transitive dependency to pin in an explicitly selected host.
#[derive(Debug, Clone)]
pub struct TransitivePin {
    /// Dependency name
    pub name: Arc<str>,
    /// Resolved version
    pub version: semver::Version,
    /// Features to enable
    pub features: Vec<Arc<str>>,
}

/// Record of a feature that is used at runtime but not declared in Cargo.toml
///
/// This happens when a crate relies on Cargo's feature unification to "borrow"
/// features from another crate in the workspace. After unification, standalone
/// builds of that crate will fail because the borrowed feature is no longer available.
#[derive(Debug, Clone)]
pub struct UndeclaredFeature {
    /// Member crate that uses the undeclared feature
    pub member: Arc<str>,
    /// Dependency name
    pub dep_name: Arc<str>,
    /// Features that are resolved (enabled at runtime) but not declared
    pub undeclared_features: Vec<Arc<str>>,
    /// Features that were declared in Cargo.toml
    pub declared_features: Vec<Arc<str>>,
    /// Features from the resolved dependency graph
    pub resolved_features: Vec<Arc<str>>,
    /// Kind of dependency (normal, dev, build)
    pub dep_kind: DepKind,
    /// Target platform constraint (if in target-specific section)
    pub target: Option<Arc<str>>,
    /// Which workspace members provide the borrowed features
    /// Shows where the feature is coming from (for transparency)
    pub borrowed_from: Vec<Arc<str>>,
    /// Exact declarations that enabled the borrowed resolver features.
    pub enabling_paths: Vec<FeatureEnablingPath>,
    /// Workspace-relative source paths whose diagnostics require the feature.
    pub required_by: Vec<Arc<str>>,
}

/// One manifest declaration contributing to a feature-policy decision.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FeatureEnablingPath {
    /// Workspace member containing the declaration.
    pub member: Arc<str>,
    /// Cargo.toml dependency key, preserving renames.
    pub alias: Arc<str>,
    /// Normal, development, or build dependency domain.
    pub dependency_kind: DepKind,
    /// Target predicate on the declaration, when present.
    pub target: Option<Arc<str>>,
    /// Explicit and conditional features enabled by this declaration.
    pub features: Vec<Arc<str>>,
    /// Whether this declaration enables the dependency's default feature.
    pub default_features: bool,
    /// Whether this declaration is optional.
    pub optional: bool,
}

/// Subject area for a per-dependency decision entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnifyDecisionSubject {
    /// A dependency being written or updated in `[workspace.dependencies]`.
    WorkspaceDependency,
    /// A dependency skipped from workspace unification.
    SkippedDependency,
    /// A transitive dependency pinned into the workspace/host manifest.
    TransitivePin,
    /// A member-local dependency fix for undeclared features.
    UndeclaredFeatureFix,
}

impl UnifyDecisionSubject {
    /// Stable machine-readable string for JSON/text output.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::WorkspaceDependency => "workspace_dependency",
            Self::SkippedDependency => "skipped_dependency",
            Self::TransitivePin => "transitive_pin",
            Self::UndeclaredFeatureFix => "undeclared_feature_fix",
        }
    }
}

/// Machine-readable code for a unify decision reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnifyDecisionCode {
    /// Shared features were selected using the intersection strategy.
    FeatureIntersection,
    /// Features were widened using a union strategy.
    FeatureUnion,
    /// Workspace-member dependency features remain local to each declaration.
    WorkspaceMemberFeaturesLocal,
    /// Exact version pins were preserved in the workspace dependency.
    ExactPinPreserved,
    /// Exact version pins were converted to a caret requirement with a warning.
    ExactPinWarnCaret,
    /// Exact version pins caused the dependency to be skipped.
    ExactPinSkipped,
    /// A workspace-member cohort was enforced atomically.
    CohortEnforced,
    /// A dependency was pinned transitively to stabilize resolution.
    TransitivePin,
    /// Missing features were added locally to avoid borrowed-feature breakage.
    UndeclaredFeatureFix,
}

impl UnifyDecisionCode {
    /// Stable machine-readable string for JSON/text output.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::FeatureIntersection => "intersection",
            Self::FeatureUnion => "union",
            Self::WorkspaceMemberFeaturesLocal => "workspace_member_features_local",
            Self::ExactPinPreserved => "exact_pin_preserved",
            Self::ExactPinWarnCaret => "exact_pin_warn_caret",
            Self::ExactPinSkipped => "exact_pin_skipped",
            Self::CohortEnforced => "cohort_enforced",
            Self::TransitivePin => "transitive_pin",
            Self::UndeclaredFeatureFix => "undeclared_feature_fix",
        }
    }
}

/// One reason attached to a dependency decision.
#[derive(Debug, Clone)]
pub struct UnifyDecisionReason {
    /// Machine-readable reason code.
    pub code: UnifyDecisionCode,
    /// Human-readable summary.
    pub summary: Arc<str>,
    /// Feature names involved in the decision when relevant.
    pub features: Vec<Arc<str>>,
    /// Workspace members involved in the decision when relevant.
    pub members: Vec<Arc<str>>,
    /// Feature providers for borrowed-feature repairs.
    pub borrowed_from: Vec<Arc<str>>,
    /// Exact manifest paths that contributed to a feature rule.
    pub feature_paths: Vec<FeatureEnablingPath>,
}

/// Per-dependency explainability record shared by text and JSON output.
#[derive(Debug, Clone)]
pub struct UnifyDecision {
    /// Dependency name this decision applies to.
    pub dep_name: Arc<str>,
    /// Decision subject.
    pub subject: UnifyDecisionSubject,
    /// Member crate for member-local fixes/skips when applicable.
    pub member: Option<Arc<str>>,
    /// Target-specific manifest section for member-local fixes when applicable.
    pub target: Option<Arc<str>>,
    /// Concrete reasons behind the decision.
    pub reasons: Vec<UnifyDecisionReason>,
}

// UnificationPlan

/// Dependency-domain repairs for one separately resolved Cargo workspace.
#[derive(Debug, Clone)]
pub struct IndependentDependencyPlan {
    /// Owning standalone workspace root.
    pub workspace_root: PathBuf,
    /// Captured source and resolution authority for its proofs.
    pub snapshot_id: String,
    /// Captured feature and target views revalidated after declaration edits.
    pub coverage_views: Vec<crate::compiler::CoverageView>,
    /// Package manifests in this workspace, keyed only within this workspace.
    pub member_paths: FxHashMap<Arc<str>, PathBuf>,
    /// Proven dependency-domain findings.
    pub unused_deps: Vec<UnusedDep>,
    /// Exact declaration edits grouped by package within this workspace.
    pub member_edits: FxHashMap<Arc<str>, Vec<MemberEdit>>,
}

/// Planned dependency and manifest repairs in the root and declared independent workspaces.
#[derive(Debug)]
pub struct UnificationPlan {
    /// Dependency repairs in independently declared Cargo workspaces.
    pub independent_workspaces: Vec<IndependentDependencyPlan>,
    /// Dependencies to add to [workspace.dependencies]
    pub workspace_deps: Vec<UnifiedDep>,
    /// Edits to apply to each member's Cargo.toml
    pub member_edits: FxHashMap<Arc<str>, Vec<MemberEdit>>,
    /// Mapping from package name to manifest path (relative to workspace root)
    pub member_paths: FxHashMap<Arc<str>, PathBuf>,
    /// Transitive dependencies to pin (with version info)
    pub transitive_pins: Vec<TransitivePin>,
    /// Issues detected during analysis
    pub issues: Vec<UnifyIssue>,
    /// Computed MSRV from the dependency graph when the configured policy enables it.
    pub computed_msrv: Option<ComputedMsrv>,
    /// Duplicate versions that were silently cleaned up
    pub duplicates_cleaned: Vec<DuplicateCleanup>,
    /// Truly dead features (empty no-ops) that can be safely pruned
    pub pruned_features: Vec<PrunedFeature>,
    /// Deterministic explanations for retained reachable features.
    pub reachable_features: Vec<ReachableFeature>,
    /// Optional features that are not enabled but provide user-facing functionality
    /// These should NOT be removed, only reported for awareness
    pub optional_features: Vec<OptionalFeature>,
    /// Version mismatches between member manifests and existing workspace.dependencies
    pub version_mismatches: Vec<VersionMismatch>,
    /// Unused dependencies detected in workspace members
    pub unused_deps: Vec<UnusedDep>,
    /// Undeclared features detected (resolved > declared)
    /// These indicate crates relying on feature unification from other workspace members
    pub undeclared_features: Vec<UndeclaredFeature>,
    /// Versioned-output source for captured package-field inheritance decisions.
    pub package_inheritance: Vec<PackageInheritanceField>,
    /// Per-dependency explainability records for text/JSON output.
    pub dependency_decisions: Vec<UnifyDecision>,
}

impl UnificationPlan {
    /// Returns true if there are any errors that block unification
    pub fn has_blocking_issues(&self) -> bool {
        self.issues.iter().any(|i| i.severity == IssueSeverity::Error)
    }

    /// Total number of concrete member edits planned across the workspace.
    ///
    /// Note: `member_edits` may contain empty vectors in edge cases; this returns the
    /// actual edit count and is the right basis for "would this mutate files?" checks.
    pub fn member_edit_count(&self) -> usize {
        self.member_edits.values().map(|v| v.len()).sum::<usize>()
            + self
                .independent_workspaces
                .iter()
                .flat_map(|workspace| workspace.member_edits.values())
                .map(Vec::len)
                .sum::<usize>()
    }

    /// Number of equivalent package declarations planned for workspace inheritance.
    pub fn package_inheritance_edit_count(&self) -> usize {
        self.package_inheritance.iter().map(|field| field.planned.len()).sum()
    }

    /// Returns true if the plan would mutate manifests or workspace MSRV.
    ///
    /// Intentionally ignores informational-only fields like `optional_features`.
    pub fn has_planned_changes(&self, msrv_write_needed: bool) -> bool {
        !self.workspace_deps.is_empty()
            || self.member_edit_count() > 0
            || !self.transitive_pins.is_empty()
            || msrv_write_needed
    }

    /// Generates a human-readable summary of the plan
    pub fn summary(&self) -> String {
        let mut s = String::new();
        s.push_str("=== Unification Plan ===\n\n");

        // Show dependencies to unify (new workspace deps)
        if !self.workspace_deps.is_empty() {
            s.push_str(&format!("Dependencies to unify: {}\n", self.workspace_deps.len()));
            for dep in &self.workspace_deps {
                s.push_str(&format!("  - {} = \"{}\"", dep.name, dep.version_req));

                if !dep.features.is_empty() {
                    let feats: Vec<&str> = dep.features.iter().map(|f| &**f).collect();
                    s.push_str(&format!(", features = [{}]", feats.join(", ")));
                }

                if !dep.default_features {
                    s.push_str(", default-features = false");
                }

                s.push_str(&format!(" (used by {} crates)\n", dep.used_by.len()));
            }
            s.push('\n');
        }

        // Show member edits (deps being converted to workspace = true)
        if !self.member_edits.is_empty() {
            // Collect unique dep names being converted, removed deps, removed features, and added features
            let mut converted_deps: HashSet<Arc<str>> = HashSet::new();
            let mut removed_deps: HashSet<Arc<str>> = HashSet::new();
            let mut removed_features: HashSet<Arc<str>> = HashSet::new();
            let mut features_added_count = 0usize;
            let mut features_added_crates: HashSet<Arc<str>> = HashSet::new();
            let mut msrv_inheritance_crates: HashSet<Arc<str>> = HashSet::new();
            for (member_name, edits) in &self.member_edits {
                for edit in edits {
                    match edit {
                        MemberEdit::UseWorkspace { dep_name, .. } => {
                            converted_deps.insert(Arc::clone(dep_name));
                        }
                        MemberEdit::RemoveDep { dep_name, .. } | MemberEdit::MoveToDev { dep_name, .. } => {
                            removed_deps.insert(Arc::clone(dep_name));
                        }
                        MemberEdit::RemoveFeature { feature_name } => {
                            removed_features.insert(Arc::clone(feature_name));
                        }
                        MemberEdit::AddFeatures { features_to_add, .. } => {
                            features_added_count += features_to_add.len();
                            features_added_crates.insert(Arc::clone(member_name));
                        }
                        MemberEdit::EnforceMsrvInheritance => {
                            msrv_inheritance_crates.insert(Arc::clone(member_name));
                        }
                        MemberEdit::InheritPackageField { .. } => {}
                    }
                }
            }

            // Only show if there are deps being converted that aren't already in workspace_deps
            let workspace_dep_names: HashSet<Arc<str>> =
                self.workspace_deps.iter().map(|d| Arc::clone(&d.name)).collect();
            let conversion_only: Vec<_> = converted_deps.difference(&workspace_dep_names).collect();

            if !conversion_only.is_empty() {
                s.push_str(&format!(
                    "Dependencies to convert to workspace inheritance: {}\n",
                    conversion_only.len()
                ));
                for dep_name in conversion_only {
                    s.push_str(&format!("  - {} (already in workspace.dependencies)\n", dep_name));
                }
                s.push('\n');
            }

            // Show deps being removed
            if !removed_deps.is_empty() {
                s.push_str(&format!("Dependencies to remove (unused): {}\n", removed_deps.len()));
                for dep_name in &removed_deps {
                    s.push_str(&format!("  - {}\n", dep_name));
                }
                s.push('\n');
            }

            if !removed_features.is_empty() {
                s.push_str(&format!(
                    "Features to remove (dead or empty): {}\n",
                    removed_features.len()
                ));
                for feature_name in &removed_features {
                    s.push_str(&format!("  - {}\n", feature_name));
                }
                s.push('\n');
            }

            // Show features being added (undeclared feature fixes)
            if features_added_count > 0 {
                s.push_str(&format!(
                    "Undeclared features to fix: {} features across {} crates\n",
                    features_added_count,
                    features_added_crates.len()
                ));
                s.push('\n');
            }

            if !msrv_inheritance_crates.is_empty() {
                s.push_str(&format!(
                    "MSRV inheritance to enforce: {} crates\n",
                    msrv_inheritance_crates.len()
                ));
                s.push('\n');
            }
        }

        s.push_str(&format!("Member edits: {}\n", self.member_edits.len()));
        s.push_str(&format!("Transitive pins: {}\n", self.transitive_pins.len()));

        let (preserved, attention): (Vec<_>, Vec<_>) = self
            .issues
            .iter()
            .partition(|issue| issue.kind == UnifyIssueKind::Preserved);
        if !attention.is_empty() {
            s.push_str(&format!("\nIssues requiring attention: {}\n", attention.len()));
            for issue in attention {
                let kind_suffix = match issue.kind {
                    UnifyIssueKind::WorkspaceMemberCohortSplitRisk => " [WorkspaceMemberCohortSplitRisk]",
                    UnifyIssueKind::General | UnifyIssueKind::Preserved => "",
                };
                s.push_str(&format!(
                    "  - [{}]{} {}: {}\n",
                    if issue.severity == IssueSeverity::Error {
                        "ERROR"
                    } else {
                        "WARN"
                    },
                    kind_suffix,
                    issue.dep_name,
                    issue.message
                ));
            }
        }
        if !preserved.is_empty() {
            s.push_str(&format!(
                "\nPreserved on purpose: {} declarations (see --explain)\n",
                preserved.len()
            ));
        }

        // Show computed MSRV if available
        if let Some(ref msrv) = self.computed_msrv {
            s.push_str(&format!(
                "\nComputed MSRV: {} (from {} deps with rust-version)\n",
                msrv.version, msrv.deps_with_msrv
            ));
            if let Some(ref warning) = msrv.warning {
                s.push_str(&format!("  Warning: {}\n", warning));
            }
            if !msrv.contributors.is_empty() {
                let contributors_str = if msrv.contributors.len() > 3 {
                    format!(
                        "{}, ... ({} total)",
                        msrv.contributors[..3].join(", "),
                        msrv.contributors.len()
                    )
                } else {
                    msrv.contributors.join(", ")
                };
                s.push_str(&format!("  Contributors: {}\n", contributors_str));
            }
        }

        // Show duplicates that were cleaned up
        if !self.duplicates_cleaned.is_empty() {
            s.push_str(&format!(
                "\nDuplicate versions unified: {}\n",
                self.duplicates_cleaned.len()
            ));
            for dup in &self.duplicates_cleaned {
                s.push_str(&format!(
                    "  - {} -> {} (was: {})\n",
                    dup.dep_name,
                    dup.selected_version,
                    dup.versions_found.join(", ")
                ));
            }
        }

        // Show pruned dead features (empty no-ops)
        if !self.pruned_features.is_empty() {
            s.push_str(&format!(
                "\nDead features (empty no-ops, safe to prune): {}\n",
                self.pruned_features.len()
            ));
            // Group by crate (BTreeMap for deterministic output order)
            let mut by_crate: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for pf in &self.pruned_features {
                by_crate.entry(&pf.crate_name).or_default().push(&pf.feature_name);
            }
            for (crate_name, mut features) in by_crate {
                features.sort_unstable();
                s.push_str(&format!("  - {}: {}\n", crate_name, features.join(", ")));
            }
        }

        // Show optional features (user-facing API, NOT removed)
        if !self.optional_features.is_empty() {
            s.push_str(&format!(
                "\nOptional features (user-facing API, NOT removed): {}\n",
                self.optional_features.len()
            ));
            // Group by crate (BTreeMap for deterministic output order)
            let mut by_crate: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for of in &self.optional_features {
                by_crate.entry(&of.crate_name).or_default().push(&of.feature_name);
            }
            for (crate_name, mut features) in by_crate {
                features.sort_unstable();
                s.push_str(&format!("  - {}: {}\n", crate_name, features.join(", ")));
            }
        }

        // Show version mismatches
        if !self.version_mismatches.is_empty() {
            s.push_str(&format!(
                "\n  Version mismatches with workspace.dependencies: {}\n",
                self.version_mismatches.len()
            ));
            for mismatch in &self.version_mismatches {
                s.push_str(&format!(
                    "  - {} in {}: declares \"{}\" but workspace has \"{}\"\n",
                    mismatch.dep_name, mismatch.member, mismatch.member_version, mismatch.workspace_version
                ));
            }
        }

        // Show unused dependencies
        if !self.unused_deps.is_empty() {
            s.push_str(&format!(
                "\n  Unused dependencies detected: {}\n",
                self.unused_deps.len()
            ));
            // Group by member (BTreeMap for deterministic output order)
            let mut by_member: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for ud in &self.unused_deps {
                by_member.entry(&ud.member).or_default().push(&ud.dep_name);
            }
            for (member, mut deps) in by_member {
                deps.sort_unstable();
                s.push_str(&format!("  - {}: {}\n", member, deps.join(", ")));
            }
        }

        s
    }
}

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

    /// Helper to create Arc<str> from string literal
    fn arc(s: &str) -> Arc<str> {
        Arc::from(s)
    }

    #[test]
    fn test_member_edit_add_features_struct() {
        let edit = MemberEdit::AddFeatures {
            dep_name: arc("serde"),
            dep_kind: DepKind::Normal,
            target: None,
            features_to_add: vec![arc("derive"), arc("std")],
        };

        match edit {
            MemberEdit::AddFeatures {
                dep_name,
                dep_kind,
                target,
                features_to_add,
            } => {
                assert_eq!(&*dep_name, "serde");
                assert_eq!(dep_kind, DepKind::Normal);
                assert!(target.is_none());
                assert_eq!(features_to_add.len(), 2);
                assert!(features_to_add.iter().any(|f| &**f == "derive"));
            }
            _ => panic!("Expected AddFeatures variant"),
        }
    }

    #[test]
    fn test_member_edit_add_features_with_target() {
        let edit = MemberEdit::AddFeatures {
            dep_name: arc("libc"),
            dep_kind: DepKind::Normal,
            target: Some(arc("cfg(unix)")),
            features_to_add: vec![arc("extra_traits")],
        };

        match edit {
            MemberEdit::AddFeatures { target, .. } => {
                assert_eq!(target.as_deref(), Some("cfg(unix)"));
            }
            _ => panic!("Expected AddFeatures variant"),
        }
    }

    #[test]
    fn test_member_edit_add_features_dev_dependency() {
        let edit = MemberEdit::AddFeatures {
            dep_name: arc("tokio"),
            dep_kind: DepKind::Dev,
            target: None,
            features_to_add: vec![arc("rt-multi-thread"), arc("macros")],
        };

        match edit {
            MemberEdit::AddFeatures { dep_kind, .. } => {
                assert_eq!(dep_kind, DepKind::Dev);
            }
            _ => panic!("Expected AddFeatures variant"),
        }
    }

    #[test]
    fn test_member_edit_add_features_build_dependency() {
        let edit = MemberEdit::AddFeatures {
            dep_name: arc("cc"),
            dep_kind: DepKind::Build,
            target: None,
            features_to_add: vec![arc("parallel")],
        };

        match edit {
            MemberEdit::AddFeatures { dep_kind, .. } => {
                assert_eq!(dep_kind, DepKind::Build);
            }
            _ => panic!("Expected AddFeatures variant"),
        }
    }

    // UndeclaredFeature Tests

    #[test]
    fn test_undeclared_feature_struct() {
        let uf = UndeclaredFeature {
            member: arc("my-crate"),
            dep_name: arc("backoff"),
            undeclared_features: vec![arc("futures"), arc("tokio")],
            declared_features: vec![arc("default")],
            resolved_features: vec![arc("default"), arc("futures"), arc("tokio")],
            dep_kind: DepKind::Normal,
            target: None,
            borrowed_from: vec![arc("other-crate")],
            enabling_paths: vec![],
            required_by: vec![],
        };

        assert_eq!(&*uf.member, "my-crate");
        assert_eq!(&*uf.dep_name, "backoff");
        assert_eq!(uf.undeclared_features.len(), 2);
        assert_eq!(uf.declared_features.len(), 1);
        assert_eq!(uf.resolved_features.len(), 3);
        assert_eq!(uf.dep_kind, DepKind::Normal);
        assert!(uf.target.is_none());
        assert_eq!(uf.borrowed_from.len(), 1);
    }

    #[test]
    fn test_undeclared_feature_with_target() {
        let uf = UndeclaredFeature {
            member: arc("platform-crate"),
            dep_name: arc("libc"),
            undeclared_features: vec![arc("extra_traits")],
            declared_features: vec![],
            resolved_features: vec![arc("extra_traits")],
            dep_kind: DepKind::Normal,
            target: Some(arc("cfg(unix)")),
            borrowed_from: vec![arc("unix-crate")],
            enabling_paths: vec![],
            required_by: vec![],
        };

        assert_eq!(uf.target.as_deref(), Some("cfg(unix)"));
    }

    #[test]
    fn test_undeclared_feature_dev_dependency() {
        let uf = UndeclaredFeature {
            member: arc("test-crate"),
            dep_name: arc("tokio"),
            undeclared_features: vec![arc("macros")],
            declared_features: vec![arc("rt")],
            resolved_features: vec![arc("rt"), arc("macros")],
            dep_kind: DepKind::Dev,
            target: None,
            borrowed_from: vec![arc("main-crate")],
            enabling_paths: vec![],
            required_by: vec![],
        };

        assert_eq!(uf.dep_kind, DepKind::Dev);
    }

    // UnificationPlan Summary Tests

    #[test]
    fn test_summary_with_add_features_edit() {
        let mut plan = UnificationPlan {
            independent_workspaces: Vec::new(),
            workspace_deps: vec![],
            member_edits: FxHashMap::default(),
            member_paths: FxHashMap::default(),
            transitive_pins: vec![],
            issues: vec![],
            computed_msrv: None,
            duplicates_cleaned: vec![],
            pruned_features: vec![],
            reachable_features: vec![],
            optional_features: vec![],
            version_mismatches: vec![],
            unused_deps: vec![],
            undeclared_features: vec![],
            package_inheritance: vec![],
            dependency_decisions: vec![],
        };

        // Add a MemberEdit::AddFeatures
        plan.member_edits.insert(
            arc("test-crate"),
            vec![MemberEdit::AddFeatures {
                dep_name: arc("serde"),
                dep_kind: DepKind::Normal,
                target: None,
                features_to_add: vec![arc("derive")],
            }],
        );

        let summary = plan.summary();
        assert!(summary.contains("Undeclared features to fix: 1 features across 1 crates"));
    }

    #[test]
    fn test_summary_with_multiple_add_features_edits() {
        let mut plan = UnificationPlan {
            independent_workspaces: Vec::new(),
            workspace_deps: vec![],
            member_edits: FxHashMap::default(),
            member_paths: FxHashMap::default(),
            transitive_pins: vec![],
            issues: vec![],
            computed_msrv: None,
            duplicates_cleaned: vec![],
            pruned_features: vec![],
            reachable_features: vec![],
            optional_features: vec![],
            version_mismatches: vec![],
            unused_deps: vec![],
            undeclared_features: vec![],
            package_inheritance: vec![],
            dependency_decisions: vec![],
        };

        // Add multiple AddFeatures edits
        plan.member_edits.insert(
            arc("crate-a"),
            vec![
                MemberEdit::AddFeatures {
                    dep_name: arc("serde"),
                    dep_kind: DepKind::Normal,
                    target: None,
                    features_to_add: vec![arc("derive"), arc("std")],
                },
                MemberEdit::AddFeatures {
                    dep_name: arc("tokio"),
                    dep_kind: DepKind::Normal,
                    target: None,
                    features_to_add: vec![arc("rt")],
                },
            ],
        );
        plan.member_edits.insert(
            arc("crate-b"),
            vec![MemberEdit::AddFeatures {
                dep_name: arc("backoff"),
                dep_kind: DepKind::Normal,
                target: None,
                features_to_add: vec![arc("futures")],
            }],
        );

        let summary = plan.summary();
        // 2 + 1 + 1 = 4 features across 2 crates
        assert!(summary.contains("Undeclared features to fix: 4 features across 2 crates"));
    }

    #[test]
    fn test_summary_no_undeclared_warning_when_fixes_present() {
        let mut plan = UnificationPlan {
            independent_workspaces: Vec::new(),
            workspace_deps: vec![],
            member_edits: FxHashMap::default(),
            member_paths: FxHashMap::default(),
            transitive_pins: vec![],
            issues: vec![],
            computed_msrv: None,
            duplicates_cleaned: vec![],
            pruned_features: vec![],
            reachable_features: vec![],
            optional_features: vec![],
            version_mismatches: vec![],
            unused_deps: vec![],
            undeclared_features: vec![UndeclaredFeature {
                member: arc("my-crate"),
                dep_name: arc("backoff"),
                undeclared_features: vec![arc("futures")],
                declared_features: vec![],
                resolved_features: vec![arc("futures")],
                dep_kind: DepKind::Normal,
                target: None,
                borrowed_from: vec![arc("other-crate")],
                enabling_paths: vec![],
                required_by: vec![],
            }],
            package_inheritance: vec![],
            dependency_decisions: vec![],
        };

        // Add a fix
        plan.member_edits.insert(
            arc("my-crate"),
            vec![MemberEdit::AddFeatures {
                dep_name: arc("backoff"),
                dep_kind: DepKind::Normal,
                target: None,
                features_to_add: vec![arc("futures")],
            }],
        );

        let summary = plan.summary();
        // Should NOT show the warning since we have fixes
        assert!(!summary.contains("⚠️  Undeclared features detected"));
        // Should show the fix count
        assert!(summary.contains("Undeclared features to fix: 1 features across 1 crates"));
    }

    #[test]
    fn test_member_edit_clone() {
        let edit = MemberEdit::AddFeatures {
            dep_name: arc("test"),
            dep_kind: DepKind::Normal,
            target: Some(arc("cfg(test)")),
            features_to_add: vec![arc("a"), arc("b")],
        };

        let cloned = edit.clone();
        match (edit, cloned) {
            (
                MemberEdit::AddFeatures {
                    dep_name: a,
                    features_to_add: fa,
                    ..
                },
                MemberEdit::AddFeatures {
                    dep_name: b,
                    features_to_add: fb,
                    ..
                },
            ) => {
                assert_eq!(a, b);
                assert_eq!(fa, fb);
            }
            _ => panic!("Expected AddFeatures"),
        }
    }

    #[test]
    fn test_undeclared_feature_clone() {
        let uf = UndeclaredFeature {
            member: arc("test"),
            dep_name: arc("dep"),
            undeclared_features: vec![arc("f1")],
            declared_features: vec![arc("f2")],
            resolved_features: vec![arc("f1"), arc("f2")],
            dep_kind: DepKind::Dev,
            target: Some(arc("cfg(windows)")),
            borrowed_from: vec![arc("source-crate")],
            enabling_paths: vec![],
            required_by: vec![],
        };

        let cloned = uf.clone();
        assert_eq!(uf.member, cloned.member);
        assert_eq!(uf.dep_name, cloned.dep_name);
        assert_eq!(uf.undeclared_features, cloned.undeclared_features);
        assert_eq!(uf.target, cloned.target);
        assert_eq!(uf.borrowed_from, cloned.borrowed_from);
    }

    #[test]
    fn test_member_edit_count_ignores_empty_entries() {
        let mut member_edits: FxHashMap<Arc<str>, Vec<MemberEdit>> = FxHashMap::default();
        member_edits.insert(arc("crate-a"), vec![]);

        let plan = UnificationPlan {
            independent_workspaces: Vec::new(),
            workspace_deps: vec![],
            member_edits,
            member_paths: FxHashMap::default(),
            transitive_pins: vec![],
            issues: vec![],
            computed_msrv: None,
            duplicates_cleaned: vec![],
            pruned_features: vec![],
            reachable_features: vec![],
            optional_features: vec![OptionalFeature {
                crate_name: arc("crate-a"),
                feature_name: arc("serde"),
                enables: vec![arc("serde/derive")],
            }],
            version_mismatches: vec![],
            unused_deps: vec![],
            undeclared_features: vec![],
            package_inheritance: vec![],
            dependency_decisions: vec![],
        };

        assert_eq!(plan.member_edit_count(), 0);
        assert!(!plan.has_planned_changes(false));
    }
}