cargo-rail 0.13.4

Graph-aware testing, dependency unification, and crate extraction for Rust monorepos
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
//! Clean unification analyzer using the HYBRID approach
//!
//! This is the core of the unify implementation that properly integrates
//! with WorkspaceContext and uses multi-target metadata + manifest analysis.
//! The undeclared features detection lives here.

use crate::cargo::{
  manifest_analyzer::{ExistingWorkspaceDep, ManifestAnalyzer, parse_existing_workspace_deps},
  multi_target_metadata::MultiTargetMetadata,
  unify::version_utils::{find_major_version_conflicts, is_exact_pin, versions_compatible},
  unify::{CandidateIterator, FeaturePruner, TransitivePlanner, UnusedDepFinder},
  unify_types::{
    DuplicateCleanup, IssueSeverity, MemberEdit, UndeclaredFeature, UnificationPlan, UnifiedDep, UnifyDecision,
    UnifyDecisionCode, UnifyDecisionReason, UnifyDecisionSubject, UnifyIssue, UnifyIssueKind, ValidationResult,
    VersionMismatch,
  },
};
use crate::config::{ExactPinHandling, MajorVersionConflict, UnifyConfig};
use crate::error::{RailResult, ResultExt};
use crate::progress;
use crate::workspace::WorkspaceContext;
use rustc_hash::{FxHashMap, FxHashSet};
use semver::Version;
use semver::VersionReq;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Analyzes workspace for dependency unifications
pub struct UnifyAnalyzer {
  /// Multi-target metadata (Arc for cheap sharing - avoids expensive clone)
  metadata: Arc<MultiTargetMetadata>,
  manifests: ManifestAnalyzer,
  /// Configuration for unification behavior (can be overridden at runtime)
  pub config: UnifyConfig,
  /// Existing workspace dependencies (already in [workspace.dependencies])
  existing_workspace_deps: FxHashMap<String, ExistingWorkspaceDep>,
  /// Precomputed cohort diagnostics from config + workspace-member graph policy
  cohort_issues: Vec<UnifyIssue>,
  /// Explainability records for cohort policy decisions keyed by member package name.
  cohort_decisions: FxHashMap<Arc<str>, Vec<CohortDecision>>,
  /// Workspace root path (for path normalization)
  workspace_root: PathBuf,
  /// Canonical workspace root path (computed once)
  canonical_workspace_root: PathBuf,
}

type FeatureSources = FxHashMap<String, FxHashMap<String, FxHashSet<String>>>;
type FeatureTargetSpecific = FxHashMap<String, FxHashMap<String, bool>>;

#[derive(Debug, Clone)]
struct CohortDecision {
  summary: Arc<str>,
  members: Vec<Arc<str>>,
}

impl UnifyAnalyzer {
  /// Create a new analyzer from workspace context
  pub fn new(ctx: &WorkspaceContext) -> RailResult<Self> {
    // Get multi-target metadata (lazily loaded on first access)
    // Uses Arc::clone for cheap reference counting instead of cloning the entire cache
    let metadata = ctx.multi_target_metadata()?;

    // Parse all manifests once
    let workspace_packages = metadata.workspace_packages();
    let manifests = ManifestAnalyzer::parse_workspace(ctx.workspace_root(), &workspace_packages)?;

    // Parse existing workspace.dependencies to avoid duplicates
    let existing_workspace_deps = parse_existing_workspace_deps(ctx.workspace_root())?;

    // Build config from context, then enforce workspace-member cohort semantics.
    let base_config = ctx.config.as_ref().map(|c| c.unify.clone()).unwrap_or_default();
    let workspace_member_names: FxHashSet<Arc<str>> = workspace_packages
      .iter()
      .map(|pkg| Arc::from(pkg.name.as_str()))
      .collect();
    let (config, cohort_issues, cohort_decisions) =
      Self::apply_workspace_member_cohort_policy(base_config, &manifests, &workspace_member_names);
    let workspace_root = ctx.workspace_root().to_path_buf();
    let canonical_workspace_root = workspace_root.canonicalize().unwrap_or_else(|_| workspace_root.clone());

    Ok(Self {
      metadata,
      manifests,
      config,
      existing_workspace_deps,
      cohort_issues,
      cohort_decisions,
      workspace_root,
      canonical_workspace_root,
    })
  }

  /// Build connected cohorts of workspace members that depend on each other.
  fn build_workspace_member_cohorts(
    manifests: &ManifestAnalyzer,
    workspace_member_names: &FxHashSet<Arc<str>>,
  ) -> Vec<Vec<Arc<str>>> {
    let mut adjacency: FxHashMap<Arc<str>, FxHashSet<Arc<str>>> = FxHashMap::default();
    for member in workspace_member_names {
      adjacency.entry(Arc::clone(member)).or_default();
    }

    for member in &manifests.members {
      let member_name: Arc<str> = Arc::from(member.package_name.as_str());
      if !workspace_member_names.contains(&member_name) {
        continue;
      }

      for dep_key in member.dependencies.keys() {
        if !workspace_member_names.contains(&dep_key.name) {
          continue;
        }

        adjacency
          .entry(Arc::clone(&member_name))
          .or_default()
          .insert(Arc::clone(&dep_key.name));
        adjacency
          .entry(Arc::clone(&dep_key.name))
          .or_default()
          .insert(Arc::clone(&member_name));
      }
    }

    let mut visited: FxHashSet<Arc<str>> = FxHashSet::default();
    let mut cohorts = Vec::new();
    let mut nodes: Vec<_> = adjacency.keys().cloned().collect();
    nodes.sort();

    for node in nodes {
      if visited.contains(&node) {
        continue;
      }

      let mut stack = vec![Arc::clone(&node)];
      let mut component = Vec::new();

      while let Some(current) = stack.pop() {
        if !visited.insert(Arc::clone(&current)) {
          continue;
        }
        component.push(Arc::clone(&current));
        if let Some(neighbors) = adjacency.get(&current) {
          for neighbor in neighbors {
            if !visited.contains(neighbor) {
              stack.push(Arc::clone(neighbor));
            }
          }
        }
      }

      component.sort();
      cohorts.push(component);
    }

    cohorts
  }

  /// Enforce atomic unification policy for workspace-member cohorts.
  ///
  /// This prevents local-vs-registry splits when only part of an interconnected
  /// workspace-member dependency set would otherwise be unified.
  fn apply_workspace_member_cohort_policy(
    mut config: UnifyConfig,
    manifests: &ManifestAnalyzer,
    workspace_member_names: &FxHashSet<Arc<str>>,
  ) -> (UnifyConfig, Vec<UnifyIssue>, FxHashMap<Arc<str>, Vec<CohortDecision>>) {
    let mut issues = Vec::new();
    let mut cohort_decisions: FxHashMap<Arc<str>, Vec<CohortDecision>> = FxHashMap::default();
    let cohorts = Self::build_workspace_member_cohorts(manifests, workspace_member_names);

    for cohort in cohorts.into_iter().filter(|c| c.len() > 1) {
      let excluded_members: Vec<&Arc<str>> = cohort.iter().filter(|name| config.should_exclude(name)).collect();

      if !excluded_members.is_empty() {
        if excluded_members.len() != cohort.len() {
          let mut cohort_names: Vec<&str> = cohort.iter().map(|s| &**s).collect();
          let mut excluded_names: Vec<&str> = excluded_members.iter().map(|s| &***s).collect();
          cohort_names.sort_unstable();
          excluded_names.sort_unstable();
          let summary = Arc::from(format!(
            "Enforced atomic workspace-member cohort [{}] after partial exclusion [{}] to avoid local-vs-registry splits.",
            cohort_names.join(", "),
            excluded_names.join(", ")
          ));
          issues.push(UnifyIssue {
            kind: UnifyIssueKind::WorkspaceMemberCohortSplitRisk,
            dep_name: Arc::clone(excluded_members[0]),
            severity: IssueSeverity::Warning,
            message: Arc::from(format!(
              "Workspace-member cohort [{}] was partially excluded [{}]. \
               Applying exclude atomically to the full cohort to prevent local-vs-registry source splits.",
              cohort_names.join(", "),
              excluded_names.join(", ")
            )),
          });
          for member in &cohort {
            cohort_decisions
              .entry(Arc::clone(member))
              .or_default()
              .push(CohortDecision {
                summary: Arc::clone(&summary),
                members: cohort.to_vec(),
              });
          }
        }

        for member in &cohort {
          if !config.should_exclude(member) {
            config.exclude.push(member.to_string());
          }
        }
        continue;
      }

      let mut low_usage_members = Vec::new();
      let mut regular_members = Vec::new();
      for member in &cohort {
        if config.should_include(member) {
          regular_members.push(member.to_string());
          continue;
        }

        if manifests.package_usage_count(member) < 2 {
          low_usage_members.push(member.to_string());
        } else {
          regular_members.push(member.to_string());
        }
      }

      if !low_usage_members.is_empty() && !regular_members.is_empty() {
        low_usage_members.sort();
        regular_members.sort();
        let mut cohort_names: Vec<&str> = cohort.iter().map(|s| &**s).collect();
        cohort_names.sort_unstable();
        let summary = Arc::from(format!(
          "Enforced atomic workspace-member cohort [{}] because single-user filtering would split [{}].",
          cohort_names.join(", "),
          low_usage_members.join(", ")
        ));

        issues.push(UnifyIssue {
          kind: UnifyIssueKind::WorkspaceMemberCohortSplitRisk,
          dep_name: Arc::from(regular_members[0].as_str()),
          severity: IssueSeverity::Warning,
          message: Arc::from(format!(
            "Workspace-member cohort [{}] would split under single-user filtering \
             (single-user members: [{}]). cargo-rail will unify the entire cohort atomically.",
            cohort_names.join(", "),
            low_usage_members.join(", ")
          )),
        });

        for member in &cohort {
          cohort_decisions
            .entry(Arc::clone(member))
            .or_default()
            .push(CohortDecision {
              summary: Arc::clone(&summary),
              members: cohort.to_vec(),
            });
        }
      }

      // Cohort members bypass single-user heuristics: all-or-nothing behavior by default.
      for member in &cohort {
        if !config.should_include(member) {
          config.include.push(member.to_string());
        }
      }
    }

    (config, issues, cohort_decisions)
  }

  fn record_decision_reason(
    decisions: &mut Vec<UnifyDecision>,
    dep_name: Arc<str>,
    subject: UnifyDecisionSubject,
    member: Option<Arc<str>>,
    target: Option<Arc<str>>,
    reason: UnifyDecisionReason,
  ) {
    Self::record_decision_reasons(decisions, dep_name, subject, member, target, vec![reason]);
  }

  fn record_decision_reasons(
    decisions: &mut Vec<UnifyDecision>,
    dep_name: Arc<str>,
    subject: UnifyDecisionSubject,
    member: Option<Arc<str>>,
    target: Option<Arc<str>>,
    mut reasons: Vec<UnifyDecisionReason>,
  ) {
    if reasons.is_empty() {
      return;
    }

    if let Some(existing) = decisions.iter_mut().find(|decision| {
      decision.dep_name == dep_name
        && decision.subject == subject
        && decision.member == member
        && decision.target == target
    }) {
      existing.reasons.append(&mut reasons);
      return;
    }

    decisions.push(UnifyDecision {
      dep_name,
      subject,
      member,
      target,
      reasons,
    });
  }

  /// Normalize a dependency path relative to the workspace root.
  ///
  /// Takes a path that's relative to a member's Cargo.toml and converts it
  /// to be relative to the workspace root.
  fn normalize_dep_path(&self, member_manifest_path: &Path, dep_path: &str) -> PathBuf {
    // Get the member's directory (parent of Cargo.toml)
    let member_dir = member_manifest_path.parent().unwrap_or(member_manifest_path);
    // Resolve the dep path relative to the member's directory
    let absolute_dep_path = member_dir.join(dep_path);

    // Canonicalize to resolve .. and symlinks (if path exists)
    let canonical_dep = absolute_dep_path.canonicalize().unwrap_or(absolute_dep_path.clone());

    // Make relative to workspace root
    if let Ok(relative) = canonical_dep.strip_prefix(&self.canonical_workspace_root) {
      return relative.to_path_buf();
    }

    // Fallback: if canonicalization moved outside workspace, try non-canonicalized path
    if let Ok(relative) = absolute_dep_path.strip_prefix(&self.workspace_root) {
      return relative.to_path_buf();
    }

    // Last resort: use the path as-is
    PathBuf::from(dep_path)
  }

  /// Normalize a workspace member directory path relative to the workspace root.
  fn normalize_workspace_member_path(&self, member_manifest_path: &Path) -> PathBuf {
    let member_dir = member_manifest_path.parent().unwrap_or(member_manifest_path);

    let canonical_member = member_dir.canonicalize().unwrap_or_else(|_| member_dir.to_path_buf());

    if let Ok(relative) = canonical_member.strip_prefix(&self.canonical_workspace_root) {
      return relative.to_path_buf();
    }

    if let Ok(relative) = member_dir.strip_prefix(&self.workspace_root) {
      return relative.to_path_buf();
    }

    member_dir.to_path_buf()
  }

  /// Analyze workspace and generate unification plan
  pub fn analyze(&self) -> RailResult<UnificationPlan> {
    let dep_count = self.manifests.all_dependencies().len();
    let mut workspace_deps = Vec::with_capacity(dep_count);
    let mut member_edits: FxHashMap<Arc<str>, Vec<MemberEdit>> = FxHashMap::default();
    let mut member_paths: FxHashMap<Arc<str>, PathBuf> = FxHashMap::default();
    let mut issues = self.cohort_issues.clone();
    issues.reserve(16); // Issues are rare, small pre-alloc
    let mut duplicates_cleaned = Vec::with_capacity(8);
    let mut version_mismatches = Vec::with_capacity(8);
    let mut dependency_decisions = Vec::with_capacity(dep_count);

    // Pre-compute workspace member metadata for reuse.
    let mut workspace_member_names: FxHashSet<Arc<str>> = FxHashSet::default();
    let mut workspace_member_paths: FxHashMap<Arc<str>, PathBuf> = FxHashMap::default();
    let mut workspace_member_versions: FxHashMap<Arc<str>, Version> = FxHashMap::default();

    // Build member_paths mapping from metadata (manifest file paths)
    for pkg in self.metadata.workspace_packages() {
      let member_name = Arc::from(pkg.name.as_str());
      let manifest_path = pkg.manifest_path.clone().into_std_path_buf();
      workspace_member_names.insert(Arc::clone(&member_name));
      workspace_member_paths.insert(
        Arc::clone(&member_name),
        self.normalize_workspace_member_path(&manifest_path),
      );
      workspace_member_versions.insert(Arc::clone(&member_name), pkg.version.clone());
      member_paths.insert(member_name, manifest_path);
    }

    progress!("Analyzing {} dependencies...", self.manifests.all_dependencies().len());

    // Process each dependency using the CandidateIterator
    // This encapsulates include_renamed branching and filtering logic
    for candidate in CandidateIterator::new(&self.manifests, &self.config) {
      let dep_key = candidate.dep_key;
      let usage_sites = candidate.usages;

      // Check for major version conflicts
      // Different major versions cannot be safely merged - behavior depends on config.
      let major_versions = find_major_version_conflicts(&usage_sites);
      if major_versions.len() > 1 {
        let versions_str: Vec<_> = major_versions.iter().map(|v| v.to_string()).collect();
        match self.config.major_version_conflict {
          MajorVersionConflict::Warn => {
            // Skip unification, emit warning - both versions stay in the graph
            issues.push(UnifyIssue {
              kind: UnifyIssueKind::General,
              dep_name: Arc::clone(&dep_key.name),
              severity: IssueSeverity::Warning,
              message: Arc::from(format!(
                "Multiple major versions detected (majors: {}) - skipping unification. \
                 Consider consolidating to a single major version to reduce duplicate compilation, \
                 or set major_version_conflict = \"bump\" to force unification to highest version.",
                versions_str.join(", ")
              )),
            });
            continue; // Skip this dependency, continue with others
          }
          MajorVersionConflict::Bump => {
            // Emit warning but continue with unification to highest version
            issues.push(UnifyIssue {
              kind: UnifyIssueKind::General,
              dep_name: Arc::clone(&dep_key.name),
              severity: IssueSeverity::Warning,
              message: Arc::from(format!(
                "Multiple major versions detected (majors: {}) - bumping to highest resolved version. \
                 This may break crates depending on older major versions.",
                versions_str.join(", ")
              )),
            });
            // Don't continue - fall through to use highest resolved version
          }
        }
      }

      // Check for exact version pins
      let has_exact_pin = usage_sites
        .iter()
        .any(|u| u.declared_version.as_ref().map(|v| is_exact_pin(v)).unwrap_or(false));

      if has_exact_pin {
        match self.config.exact_pin_handling {
          ExactPinHandling::Skip => {
            // Skip this dep entirely - don't unify exact pins
            Self::record_decision_reason(
              &mut dependency_decisions,
              Arc::clone(&dep_key.name),
              UnifyDecisionSubject::SkippedDependency,
              None,
              None,
              UnifyDecisionReason {
                code: UnifyDecisionCode::ExactPinSkipped,
                summary: Arc::from(
                  "Skipped because exact_pin_handling = \"skip\" and at least one usage is pinned exactly.",
                ),
                features: Vec::new(),
                members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
                borrowed_from: Vec::new(),
              },
            );
            continue;
          }
          ExactPinHandling::Warn => {
            issues.push(UnifyIssue {
              kind: UnifyIssueKind::General,
              dep_name: Arc::clone(&dep_key.name),
              severity: IssueSeverity::Warning,
              message: Arc::from(
                "Has exact version pin (=x.y.z) - converting to caret (^). \
                        Consider adding to unify.exclude or setting exact_pin_handling = \"skip\"",
              ),
            });
          }
          ExactPinHandling::Preserve => {
            // Will be handled below when constructing version_req
          }
        }
      }

      // Get version from metadata - but ONLY from direct dependencies of workspace members
      // This uses direct_dep_versions() which filters out transitive dependencies
      let versions = self.metadata.direct_dep_versions(&dep_key.name);

      // Workspace-member deps must be unifyable even when Cargo metadata excludes
      // non-default members from resolved direct-dependency traversal.
      let version = if versions.is_empty() {
        if workspace_member_names.contains(&dep_key.name) {
          match workspace_member_versions.get(&dep_key.name) {
            Some(v) => v,
            None => continue,
          }
        } else {
          continue; // Not a direct dependency of any workspace member
        }
      } else {
        // Get unique versions across all targets
        let unique_versions: FxHashSet<_> = versions.values().collect();

        // Always use highest version (cargo's resolver already picks highest compatible)
        // When targets resolve to different versions, we unify to highest
        match unique_versions.iter().max() {
          Some(max) if unique_versions.len() > 1 => {
            // Multiple versions found across targets - use highest
            // This is the "silent win" - we unify duplicates automatically
            let mut versions_found: Vec<Arc<str>> = unique_versions.iter().map(|v| Arc::from(v.to_string())).collect();
            versions_found.sort();
            duplicates_cleaned.push(DuplicateCleanup {
              dep_name: Arc::clone(&dep_key.name),
              versions_found,
              selected_version: Arc::from(max.to_string()),
            });
            *max
          }
          Some(version) => *version,
          None => continue, // Empty set - shouldn't happen given versions check above
        }
      };

      // Construct version requirement - preserve exact pins if configured
      let version_req = if has_exact_pin && self.config.exact_pin_handling == ExactPinHandling::Preserve {
        // Find the exact pin version from declared_version
        let exact_version = usage_sites
          .iter()
          .find_map(|u| u.declared_version.as_ref().filter(|v| is_exact_pin(v)))
          .cloned()
          .unwrap_or_else(|| format!("={}", version));
        // Try exact version first, fall back to caret format, then ultimate fallback
        VersionReq::parse(&exact_version)
          .or_else(|_| VersionReq::parse(&format!("^{}", version)))
          .unwrap_or_else(|_| VersionReq::default())
      } else {
        // Try caret format first, fall back to plain version, then ultimate fallback
        VersionReq::parse(&format!("^{}", version))
          .or_else(|_| VersionReq::parse(&version.to_string()))
          .unwrap_or_else(|_| VersionReq::default())
      };
      let mut decision_reasons = Vec::new();
      if has_exact_pin {
        match self.config.exact_pin_handling {
          ExactPinHandling::Preserve => {
            decision_reasons.push(UnifyDecisionReason {
              code: UnifyDecisionCode::ExactPinPreserved,
              summary: Arc::from(format!(
                "Preserved exact pin in workspace.dependencies because exact_pin_handling = \"preserve\" ({}).",
                version_req
              )),
              features: Vec::new(),
              members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
              borrowed_from: Vec::new(),
            });
          }
          ExactPinHandling::Warn => {
            decision_reasons.push(UnifyDecisionReason {
              code: UnifyDecisionCode::ExactPinWarnCaret,
              summary: Arc::from(format!(
                "Converted exact pin to {} because exact_pin_handling = \"warn\".",
                version_req
              )),
              features: Vec::new(),
              members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
              borrowed_from: Vec::new(),
            });
          }
          ExactPinHandling::Skip => {}
        }
      }

      // Check for version mismatches with existing workspace.dependencies
      if let Some(existing_ws_dep) = self.existing_workspace_deps.get(&*dep_key.name)
        && let Some(ref ws_version) = existing_ws_dep.version
      {
        for usage in &usage_sites {
          if let Some(ref declared) = usage.declared_version
            && !versions_compatible(declared, ws_version)
          {
            version_mismatches.push(VersionMismatch {
              member: Arc::clone(&usage.used_by),
              dep_name: Arc::clone(&dep_key.name),
              member_version: Arc::from(declared.as_str()),
              workspace_version: Arc::from(ws_version.as_str()),
            });

            // Add as issue based on strictness config
            let severity = if self.config.strict_version_compat {
              IssueSeverity::Error
            } else {
              IssueSeverity::Warning
            };
            issues.push(UnifyIssue {
              kind: UnifyIssueKind::General,
              dep_name: Arc::clone(&dep_key.name),
              severity,
              message: Arc::from(format!(
                "{} declares \"{}\" but workspace.dependencies has \"{}\". \
                 Converting to workspace = true may break this crate.",
                usage.used_by, declared, ws_version
              )),
            });
          }
        }
      }

      let is_workspace_member_dep = workspace_member_names.contains(&dep_key.name);

      // For workspace-member dependencies, we only unify source/version/path atomically.
      // Feature policy remains local per member to avoid enabling member features globally
      // (for example Tokio's "full" leaking into WASM jobs via workspace.dependencies).
      //
      // Non-member deps keep existing feature/default-features unification behavior.
      let (features, default_features, feature_reason) = if is_workspace_member_dep {
        (std::collections::BTreeSet::new(), true, None)
      } else {
        // Check for mixed defaults - use union strategy if present
        // When include_renamed = true, check across all package variants
        let has_mixed_defaults = if self.config.include_renamed {
          self.manifests.package_has_mixed_defaults(&dep_key.name)
        } else {
          self.manifests.has_mixed_defaults(dep_key)
        };

        // Compute features - when include_renamed = true, aggregate across all variants
        // Note: intersection doesn't make sense across renamed deps (they're separate usages)
        // so we use union to ensure all needed features are included
        if self.config.include_renamed {
          // For package-level aggregation, always use union strategy
          // (renamed deps typically have distinct feature needs)
          let features = self.manifests.compute_package_union(&dep_key.name);
          // When mixed defaults detected, use default-features = true to preserve
          // features for crates that rely on them (same logic as non-include_renamed path)
          let df = if has_mixed_defaults {
            true
          } else {
            self
              .manifests
              .package_default_features_policy(&dep_key.name)
              .unwrap_or(true)
          };
          let mut feature_list: Vec<Arc<str>> = features.iter().map(|feature| Arc::from(feature.as_str())).collect();
          feature_list.sort();
          (
            features,
            df,
            Some(UnifyDecisionReason {
              code: UnifyDecisionCode::FeatureUnion,
              summary: Arc::from(
                "Used union because include_renamed aggregates distinct Cargo.toml keys at the package level.",
              ),
              features: feature_list,
              members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
              borrowed_from: Vec::new(),
            }),
          )
        } else {
          // Standard per-dep_key logic
          let intersection = self.manifests.compute_intersection(dep_key);

          if has_mixed_defaults || intersection.is_empty() {
            // Use union strategy for:
            // 1. Mixed default-features settings
            // 2. No common features (empty intersection)
            // Set default-features = true (max/union strategy)
            let union = self.manifests.compute_union(dep_key);
            let mut feature_list: Vec<Arc<str>> = union.iter().map(|feature| Arc::from(feature.as_str())).collect();
            feature_list.sort();
            let summary = if has_mixed_defaults {
              "Used union because dependency usages disagree on default-features."
            } else {
              "Used union because the shared feature intersection was empty."
            };
            (
              union,
              true,
              Some(UnifyDecisionReason {
                code: UnifyDecisionCode::FeatureUnion,
                summary: Arc::from(summary),
                features: feature_list,
                members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
                borrowed_from: Vec::new(),
              }),
            )
          } else {
            // Use intersection (minimal) strategy
            // Use conservative default-features policy
            let df = self.manifests.default_features_policy(dep_key).unwrap_or(true);
            let mut feature_list: Vec<Arc<str>> =
              intersection.iter().map(|feature| Arc::from(feature.as_str())).collect();
            feature_list.sort();
            (
              intersection,
              df,
              Some(UnifyDecisionReason {
                code: UnifyDecisionCode::FeatureIntersection,
                summary: Arc::from("Used intersection to keep only features shared by every usage."),
                features: feature_list,
                members: usage_sites.iter().map(|usage| Arc::clone(&usage.used_by)).collect(),
                borrowed_from: Vec::new(),
              }),
            )
          }
        }
      };
      if let Some(reason) = feature_reason {
        decision_reasons.push(reason);
      }

      // Note: Target constraints stay in member manifests, not workspace.dependencies.
      // Members use `[target.'cfg(...)'.dependencies] dep = { workspace = true }`.
      // We don't set target on UnifiedDep because [workspace.dependencies] cannot
      // have [target] sections in virtual workspaces, and even in non-virtual ones
      // it's cleaner to keep target constraints where they're used.
      let target = None;

      // Get users - use Arc<str> to share allocations
      let users: FxHashSet<Arc<str>> = usage_sites.iter().map(|u| Arc::clone(&u.used_by)).collect();

      // Workspace members must always carry `path` so member-to-member deps stay local.
      // This prevents dual-resolution in fresh lockfiles (local member + crates.io package).
      let dep_path: Option<PathBuf> = if is_workspace_member_dep {
        workspace_member_paths.get(&dep_key.name).cloned()
      } else if self.config.include_paths {
        // Include explicit path deps for non-member packages only when requested.
        usage_sites.iter().find_map(|u| {
          u.path.as_ref().and_then(|p| {
            u.manifest_path
              .as_ref()
              .map(|manifest_path| self.normalize_dep_path(manifest_path, p))
          })
        })
      } else {
        None // include_paths = false, skip all path deps
      };

      // Compute the unified features (this is what workspace.dependencies should have)
      let computed_features: Vec<Arc<str>> = features.into_iter().map(Arc::from).collect();
      if let Some(cohort_entries) = self.cohort_decisions.get(&dep_key.name) {
        for entry in cohort_entries {
          decision_reasons.push(UnifyDecisionReason {
            code: UnifyDecisionCode::CohortEnforced,
            summary: Arc::clone(&entry.summary),
            features: Vec::new(),
            members: entry.members.clone(),
            borrowed_from: Vec::new(),
          });
        }
      }

      // Check if this dep already exists in workspace.dependencies
      let existing_dep = self.existing_workspace_deps.get(&*dep_key.name);

      // Determine if we need to update workspace.dependencies
      // Update if: dep doesn't exist, OR features differ, OR default-features differs, OR has path
      let needs_workspace_update = match existing_dep {
        None => true, // Doesn't exist, need to add
        Some(existing) => {
          // Check if features are different (compare as &str)
          let mut existing_features: Vec<&str> = existing.features.iter().map(String::as_str).collect();
          let mut computed: Vec<&str> = computed_features.iter().map(|s| &**s).collect();
          existing_features.sort();
          computed.sort();

          // Also check if existing path is missing or differs from resolved path.
          let path_differs = match (&dep_path, &existing.path) {
            (Some(new_path), Some(existing_path)) => Path::new(existing_path) != new_path,
            (Some(_), None) => true,
            _ => false,
          };

          existing_features != computed || existing.default_features != default_features || path_differs
        }
      };

      // The features to use for local feature calculation
      // Use computed features (which will be what goes in workspace.dependencies)
      let workspace_features = computed_features.clone();

      // Create unified dep if workspace needs update
      if needs_workspace_update {
        let unified = UnifiedDep {
          name: Arc::clone(&dep_key.name),
          version_req,
          features: workspace_features.clone(),
          default_features,
          used_by: users.into_iter().collect(),
          target,
          path: dep_path, // Include path for workspace member deps
        };
        workspace_deps.push(unified);
      }
      Self::record_decision_reasons(
        &mut dependency_decisions,
        Arc::clone(&dep_key.name),
        UnifyDecisionSubject::WorkspaceDependency,
        None,
        None,
        decision_reasons,
      );

      // Compute member edits for ALL dep kinds (normal, dev, build)
      // Per design doc: all dep kinds should be unified, not just Normal
      // This happens whether or not the dep already exists in workspace.dependencies
      for usage in usage_sites {
        // Compute local features (member features - workspace features)
        // Convert to Arc<str> and filter out features already in workspace
        let local_features: Vec<Arc<str>> = usage
          .unconditional_features
          .iter()
          .filter(|f| !workspace_features.iter().any(|wf| &**wf == *f))
          .map(|f| Arc::from(f.as_str()))
          .collect();

        // Use the cargo_toml_key from the usage - this is the actual key in Cargo.toml
        // For renamed deps like `old_serde = { package = "serde" }`, this is "old_serde"
        // This is critical for include_renamed mode where usage_sites are aggregated
        // across multiple dep_keys for the same package
        let edit = MemberEdit::UseWorkspace {
          dep_name: Arc::clone(&usage.cargo_toml_key),
          dep_kind: usage.kind,
          target: usage.target.as_ref().map(|t| Arc::from(t.as_str())), // Preserve target for correct section
          local_features,
          is_optional: usage.optional,
        };

        member_edits.entry(Arc::clone(&usage.used_by)).or_default().push(edit);
      }
    }

    // Handle transitive fragmentation
    let transitive_pins = if self.config.pin_transitives {
      TransitivePlanner::new(&self.metadata).find_pins()
    } else {
      Vec::new()
    };
    for pin in &transitive_pins {
      Self::record_decision_reason(
        &mut dependency_decisions,
        Arc::clone(&pin.name),
        UnifyDecisionSubject::TransitivePin,
        None,
        None,
        UnifyDecisionReason {
          code: UnifyDecisionCode::TransitivePin,
          summary: Arc::from(
            "Pinned transitively because target-specific feature resolution would otherwise fragment the graph.",
          ),
          features: pin.features.clone(),
          members: Vec::new(),
          borrowed_from: Vec::new(),
        },
      );
    }

    // Compute MSRV if enabled
    let computed_msrv = if self.config.msrv {
      progress!("Computing MSRV from dependency graph...");
      self
        .metadata
        .compute_msrv_with_config(&self.workspace_root, self.config.msrv_source)
    } else {
      None
    };

    // Optionally ensure every workspace member inherits MSRV from the workspace.
    //
    // This is only safe when we have (or will write) `[workspace.package].rust-version`.
    // When msrv is disabled or cannot be computed, `rust-version = { workspace = true }`
    // would cause Cargo to error if the workspace value is absent.
    if self.config.enforce_msrv_inheritance {
      if !self.config.msrv {
        issues.push(UnifyIssue {
          kind: UnifyIssueKind::General,
          dep_name: Arc::from("rust-version"),
          severity: IssueSeverity::Warning,
          message: Arc::from(
            "enforce_msrv_inheritance is enabled but unify.msrv is false; skipping MSRV inheritance enforcement",
          ),
        });
      } else if computed_msrv.is_none() {
        issues.push(UnifyIssue {
          kind: UnifyIssueKind::General,
          dep_name: Arc::from("rust-version"),
          severity: IssueSeverity::Warning,
          message: Arc::from(
            "enforce_msrv_inheritance is enabled but no workspace MSRV could be determined; skipping MSRV inheritance enforcement",
          ),
        });
      } else {
        progress!("Enforcing MSRV inheritance on workspace members...");
        for (member_name, manifest_path) in &member_paths {
          if member_manifest_inherits_msrv(manifest_path)? {
            continue;
          }
          member_edits
            .entry(Arc::clone(member_name))
            .or_default()
            .push(MemberEdit::EnforceMsrvInheritance);
        }
      }
    }

    // Scan for dead and optional features if enabled
    let feature_pruner = FeaturePruner::new(&self.metadata, &self.config);
    let (pruned_features, optional_features) = if self.config.prune_dead_features {
      progress!("Scanning for dead features in resolved graph...");
      feature_pruner.scan()
    } else {
      (Vec::new(), Vec::new())
    };

    // Detect unused dependencies
    let unused_finder = UnusedDepFinder::new(
      &self.workspace_root,
      &self.metadata,
      &self.manifests,
      self.config.compiler_diag_cache,
    );
    let unused_deps = if self.config.detect_unused {
      progress!("Detecting unused dependencies...");
      unused_finder.find()
    } else {
      Vec::new()
    };

    // Generate removal edits if remove_unused is enabled
    if self.config.remove_unused && !unused_deps.is_empty() {
      progress!(
        "Generating removal edits for {} unused dependencies...",
        unused_deps.len()
      );
      for (member, edits) in unused_finder.generate_removal_edits(&unused_deps) {
        member_edits.entry(Arc::from(member)).or_default().extend(edits);
      }
    }

    // Generate removal edits for dead features (empty no-ops)
    for (crate_name, edits) in feature_pruner.generate_prune_edits(&pruned_features) {
      member_edits.entry(crate_name).or_default().extend(edits);
    }

    // Detect undeclared features
    // Find cases where a crate uses features that it didn't declare in Cargo.toml
    // This happens when Cargo's feature unification "borrows" features from other members
    let undeclared_features = if self.config.detect_undeclared_features {
      progress!("Checking for undeclared feature dependencies...");
      self.detect_undeclared_features()
    } else {
      Vec::new()
    };

    // Generate fixes or warnings for undeclared features
    if self.config.fix_undeclared_features && !undeclared_features.is_empty() {
      progress!(
        "Generating fixes for {} undeclared feature issues...",
        undeclared_features.len()
      );
      for uf in &undeclared_features {
        let edit = MemberEdit::AddFeatures {
          dep_name: Arc::clone(&uf.dep_name),
          dep_kind: uf.dep_kind,
          target: uf.target.clone(),
          features_to_add: uf.undeclared_features.clone(),
        };
        member_edits.entry(Arc::clone(&uf.member)).or_default().push(edit);
        Self::record_decision_reason(
          &mut dependency_decisions,
          Arc::clone(&uf.dep_name),
          UnifyDecisionSubject::UndeclaredFeatureFix,
          Some(Arc::clone(&uf.member)),
          uf.target.clone(),
          UnifyDecisionReason {
            code: UnifyDecisionCode::UndeclaredFeatureFix,
            summary: Arc::from(format!(
              "Added missing features to {} so it stops borrowing resolver state from other workspace members.",
              uf.member
            )),
            features: uf.undeclared_features.clone(),
            members: vec![Arc::clone(&uf.member)],
            borrowed_from: uf.borrowed_from.clone(),
          },
        );
      }
    } else {
      // Add issues for undeclared features (warn mode)
      for uf in &undeclared_features {
        let undeclared_str: Vec<&str> = uf.undeclared_features.iter().map(|s| &**s).collect();
        let declared_str = if uf.declared_features.is_empty() {
          "none".to_string()
        } else {
          let strs: Vec<&str> = uf.declared_features.iter().map(|s| &**s).collect();
          strs.join(", ")
        };
        issues.push(UnifyIssue {
          kind: UnifyIssueKind::General,
          dep_name: Arc::clone(&uf.dep_name),
          severity: IssueSeverity::Warning,
          message: Arc::from(format!(
            "{} uses {} features [{}] but only declares [{}]. \
             This crate relies on feature unification from other workspace members. \
             After unification, standalone builds will fail. \
             Fix: Add the missing features to {}'s Cargo.toml.",
            uf.member,
            uf.dep_name,
            undeclared_str.join(", "),
            declared_str,
            uf.member,
          )),
        });
      }
    }

    // Run validation
    let validation_results = self.validate_targets()?;

    // Defensive cleanup: avoid representing "no-op members" as pending changes.
    member_edits.retain(|_, edits| !edits.is_empty());
    for decision in &mut dependency_decisions {
      decision.reasons.sort_by(|left, right| {
        left
          .code
          .as_str()
          .cmp(right.code.as_str())
          .then_with(|| left.summary.cmp(&right.summary))
      });
    }
    dependency_decisions.sort_by(|left, right| {
      left
        .dep_name
        .cmp(&right.dep_name)
        .then_with(|| left.subject.as_str().cmp(right.subject.as_str()))
        .then_with(|| left.member.cmp(&right.member))
        .then_with(|| left.target.cmp(&right.target))
    });

    Ok(UnificationPlan {
      workspace_deps,
      member_edits,
      member_paths,
      transitive_pins,
      validation_results,
      issues,
      computed_msrv,
      duplicates_cleaned,
      pruned_features,
      optional_features,
      version_mismatches,
      unused_deps,
      undeclared_features,
      dependency_decisions,
    })
  }

  /// Validate that the unification works for all targets
  fn validate_targets(&self) -> RailResult<Vec<ValidationResult>> {
    let targets = self.metadata.targets();
    let mut results = Vec::with_capacity(targets.len());

    for target in targets {
      // Simple check: does metadata load successfully for this target?
      // In production, you might want to run `cargo check --target=X`
      let success = self.metadata.get(target).is_some();

      results.push(ValidationResult {
        target: Arc::from(target),
        success,
        error: if !success {
          Some(Arc::from("Failed to load metadata"))
        } else {
          None
        },
      });
    }

    Ok(results)
  }

  // ============================================================================
  // Helper methods for detect_undeclared_features
  // ============================================================================

  /// Get workspace member package names
  fn workspace_member_names(&self) -> FxHashSet<String> {
    self
      .metadata
      .workspace_packages()
      .iter()
      .map(|p| p.name.to_string())
      .collect()
  }

  /// Build workspace baseline features from [workspace.dependencies]
  ///
  /// These are workspace policy - members don't need to re-declare them.
  fn workspace_baseline_features(&self) -> FxHashMap<String, FxHashSet<String>> {
    self
      .existing_workspace_deps
      .iter()
      .map(|(name, dep)| {
        let mut feats: FxHashSet<String> = dep.features.iter().cloned().collect();
        if dep.default_features {
          feats.insert("default".to_string());
        }
        (name.clone(), feats)
      })
      .collect()
  }

  /// Track which members contribute which features (beyond workspace baseline)
  ///
  /// Returns (feature_sources, feature_is_target_specific):
  /// - feature_sources: dep_name -> feature -> set of members that declare it
  /// - feature_is_target_specific: dep_name -> feature -> true if ALL declarations are target-specific
  fn track_feature_sources(
    &self,
    workspace_baseline: &FxHashMap<String, FxHashSet<String>>,
  ) -> (FeatureSources, FeatureTargetSpecific) {
    let mut feature_sources: FeatureSources = FxHashMap::default();
    let mut feature_is_target_specific: FeatureTargetSpecific = FxHashMap::default();

    for member in &self.manifests.members {
      for (dep_key, usages) in &member.dependencies {
        let baseline = workspace_baseline.get(&*dep_key.name);
        // Compute dep name string once per (member, dep) pair instead of per-feature
        let dep_name_str = dep_key.name.to_string();

        for usage in usages {
          let mut feats: FxHashSet<&String> = usage.unconditional_features.iter().collect();
          feats.extend(usage.conditional_features.iter());

          let is_target_specific = usage.target.is_some();

          for feat in feats {
            // Skip features in workspace baseline (workspace policy)
            if baseline.is_some_and(|b| b.contains(feat)) {
              continue;
            }

            // Clone dep_name_str once per feature instead of allocating twice
            feature_sources
              .entry(dep_name_str.clone())
              .or_default()
              .entry(feat.clone())
              .or_default()
              .insert(member.package_name.clone());

            // Track target-specificity: only consider target-specific if ALL declarations are
            let entry = feature_is_target_specific
              .entry(dep_name_str.clone())
              .or_default()
              .entry(feat.clone())
              .or_insert(true);
            if !is_target_specific {
              *entry = false;
            }
          }
        }
      }
    }

    (feature_sources, feature_is_target_specific)
  }

  /// Detect dependencies where resolved features exceed declared features
  ///
  /// This catches cases where a crate relies on Cargo's feature unification to
  /// "borrow" features from other workspace members. After workspace dependency
  /// unification, standalone builds (cargo test -p <crate>) will fail because
  /// the borrowed features are no longer available.
  ///
  /// Key distinctions:
  /// - **Workspace policy**: Features in `[workspace.dependencies]` are intentional
  ///   workspace-level declarations. Members using these don't need to re-declare.
  /// - **Member borrowing**: Features that only come from another member are
  ///   implicit coupling and should be flagged.
  /// - **Conditional features**: Features declared via `[features]` table (e.g.,
  ///   `my-feature = ["dep/feat"]`) count as declared - the author made an
  ///   intentional choice.
  fn detect_undeclared_features(&self) -> Vec<UndeclaredFeature> {
    let workspace_member_names = self.workspace_member_names();
    let workspace_baseline = self.workspace_baseline_features();
    let (feature_sources, feature_is_target_specific) = self.track_feature_sources(&workspace_baseline);

    let mut undeclared = Vec::with_capacity(16);
    let mut skipped_platform_features: Vec<(String, String, String)> = Vec::with_capacity(8);
    let mut skipped_workspace_member_deps: FxHashSet<String> = FxHashSet::default();

    // Find borrowed features for each member
    for member in &self.manifests.members {
      for (dep_key, usages) in &member.dependencies {
        // Skip workspace member deps - their optional features are intentional opt-ins
        if workspace_member_names.contains(&*dep_key.name) {
          skipped_workspace_member_deps.insert(dep_key.name.to_string());
          continue;
        }

        let Some(feat_sources) = feature_sources.get(&*dep_key.name) else {
          continue;
        };

        let target_specific_map = feature_is_target_specific.get(&*dep_key.name);

        for usage in usages {
          if let Some(borrowed) = self.find_borrowed_features_for_usage(
            member,
            dep_key,
            usage,
            feat_sources,
            target_specific_map,
            &mut skipped_platform_features,
          ) {
            undeclared.push(borrowed);
          }
        }
      }
    }

    // Log skipped items
    if !skipped_workspace_member_deps.is_empty() {
      progress!(
        "  Skipped undeclared feature detection for {} workspace member deps (features are opt-in)",
        skipped_workspace_member_deps.len()
      );
    }
    if !skipped_platform_features.is_empty() {
      progress!(
        "  Skipped {} platform-specific undeclared features (target-constrained declarations)",
        skipped_platform_features.len()
      );
    }

    undeclared
  }

  /// Find borrowed features for a single dependency usage
  #[allow(clippy::too_many_arguments)]
  fn find_borrowed_features_for_usage(
    &self,
    member: &crate::cargo::manifest_analyzer::ParsedManifest,
    dep_key: &crate::cargo::manifest_analyzer::DepKey,
    usage: &crate::cargo::manifest_analyzer::DepUsage,
    feat_sources: &FxHashMap<String, FxHashSet<String>>,
    target_specific_map: Option<&FxHashMap<String, bool>>,
    skipped_platform_features: &mut Vec<(String, String, String)>,
  ) -> Option<UndeclaredFeature> {
    // Get this usage's declared features
    let mut declared: FxHashSet<String> = usage.unconditional_features.iter().cloned().collect();
    declared.extend(usage.conditional_features.iter().cloned());
    if usage.default_features {
      declared.insert("default".to_string());
    }

    let mut borrowed_features: Vec<Arc<str>> = Vec::with_capacity(feat_sources.len());
    let mut borrowed_from_members: FxHashSet<Arc<str>> = FxHashSet::default();

    for (feat, sources) in feat_sources {
      // Skip if this member declares the feature itself
      if declared.contains(feat) {
        continue;
      }

      // Skip if configured to skip this feature pattern
      if self.config.should_skip_undeclared_feature(feat) {
        continue;
      }

      // Skip if feature is target-specific (all declarations have target constraints)
      if let Some(ts_map) = target_specific_map
        && ts_map.get(feat).copied().unwrap_or(false)
      {
        skipped_platform_features.push((member.package_name.clone(), dep_key.name.to_string(), feat.clone()));
        continue;
      }

      // This feature is borrowed from other members
      borrowed_features.push(Arc::from(feat.as_str()));
      for source in sources {
        if source != &member.package_name {
          borrowed_from_members.insert(Arc::from(source.as_str()));
        }
      }
    }

    if borrowed_features.is_empty() {
      return None;
    }

    borrowed_features.sort();
    let mut borrowed_from: Vec<Arc<str>> = borrowed_from_members.into_iter().collect();
    borrowed_from.sort();

    Some(UndeclaredFeature {
      member: Arc::from(member.package_name.as_str()),
      dep_name: Arc::clone(&dep_key.name),
      undeclared_features: borrowed_features,
      declared_features: declared.into_iter().map(|s| Arc::from(s.as_str())).collect(),
      resolved_features: feat_sources.keys().map(|s| Arc::from(s.as_str())).collect(),
      dep_kind: usage.kind,
      target: usage.target.as_ref().map(|t| Arc::from(t.as_str())),
      borrowed_from,
    })
  }
}

fn member_manifest_inherits_msrv(manifest_path: &Path) -> RailResult<bool> {
  let content =
    std::fs::read_to_string(manifest_path).context(format!("Failed to read {}", manifest_path.display()))?;
  let doc: toml_edit::DocumentMut = content
    .parse()
    .context(format!("Failed to parse {}", manifest_path.display()))?;

  let Some(pkg) = doc.get("package").and_then(|p| p.as_table()) else {
    // No [package] section (likely a virtual workspace member). Nothing to enforce.
    return Ok(true);
  };

  let Some(rv) = pkg.get("rust-version") else {
    return Ok(false);
  };

  let Some(rv_tbl) = rv.as_table_like() else {
    return Ok(false);
  };

  Ok(rv_tbl.get("workspace").and_then(|v| v.as_bool()) == Some(true))
}