cargo-rail 0.27.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
//! Capture one authoritative workspace view and share its derived state.

use crate::cargo::multi_target_metadata::MultiTargetMetadata;
use crate::cargo::resolution::{
    CargoConfigSnapshot, ResolutionInputs, ResolutionRequest, ResolutionView, ResolutionViews,
    capture_target_identities,
};
use crate::compiler::cfg_eval::TargetCfgSet;
use crate::config::RailConfig;
use crate::error::{GitError, RailError, RailResult};
use crate::git::SystemGit;
use crate::graph::WorkspaceGraph;
use crate::source::{
    ChangeSet, ContentDigest, GitWorktreeCapture, PlanningSourceCapture, RepositoryPath, SourceEntryKind,
    SourceExclusions, SourceSnapshot, changes_between_objects,
};
use crate::workspace::snapshot::{CapturedLockfile, CapturedRailConfig, DerivedViews, WorkspaceSnapshot};
use cargo_metadata::{Metadata, MetadataCommand, Package};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Cargo state for the workspace
///
/// Provides cargo metadata and workspace information.
/// This is built once and shared across all commands via WorkspaceContext.
#[derive(Debug, Clone)]
pub struct CargoState {
    /// Underlying cargo metadata
    metadata: Arc<Metadata>,

    /// Cached workspace root
    workspace_root: PathBuf,

    /// Index: package name → index in metadata.packages (workspace members only)
    /// Enables O(1) package lookup instead of O(n) linear scan
    package_index: std::collections::HashMap<String, usize>,

    /// Cached set of proc-macro crate names for O(1) detection
    /// Built once during construction, used by change analysis
    proc_macro_crates: std::collections::HashSet<String>,
}

impl CargoState {
    /// Load fresh Cargo-owned workspace metadata.
    fn load(workspace_root: &Path) -> RailResult<Self> {
        crate::instrumentation::record_cargo_metadata_load(false);
        let metadata = MetadataCommand::new()
            .manifest_path(workspace_root.join("Cargo.toml"))
            .exec()?;
        Ok(Self::from_metadata(Arc::new(super::capture_metadata_paths(metadata)?)))
    }

    fn load_fresh(
        workspace_root: &Path,
        cargo_current_dir: &Path,
        cargo_program: &std::ffi::OsStr,
        credential_sensitive: bool,
    ) -> RailResult<Self> {
        crate::instrumentation::record_cargo_metadata_load(false);
        let mut command = MetadataCommand::new();
        command
            .cargo_path(PathBuf::from(cargo_program))
            .current_dir(cargo_current_dir)
            .manifest_path(workspace_root.join("Cargo.toml"));
        if workspace_root.join("Cargo.lock").is_file() {
            command.other_options(vec!["--locked".to_string()]);
        }
        let metadata = command.exec().map_err(|error| {
      if credential_sensitive {
        RailError::with_help(
          "Cargo metadata failed while credential capabilities were active",
          "run cargo metadata directly for provider diagnostics; cargo-rail suppresses credential-provider output",
        )
      } else {
        error.into()
      }
    })?;
        Ok(Self::from_metadata(Arc::new(super::capture_metadata_paths(metadata)?)))
    }

    fn load_planning(workspace_root: &Path, cargo_current_dir: &Path, require_existing_lock: bool) -> RailResult<Self> {
        crate::instrumentation::record_cargo_metadata_load(false);
        let mut command = MetadataCommand::new();
        command
            .current_dir(cargo_current_dir)
            .manifest_path(workspace_root.join("Cargo.toml"));
        if require_existing_lock || workspace_root.join("Cargo.lock").is_file() {
            command.other_options(vec!["--locked".to_string()]);
        }
        let metadata = command.exec()?;
        Ok(Self::from_metadata(Arc::new(super::capture_metadata_paths(metadata)?)))
    }

    /// Build CargoState from metadata, constructing the package index and proc-macro cache
    fn from_metadata(metadata: Arc<Metadata>) -> Self {
        let workspace_root = metadata.workspace_root.as_std_path().to_path_buf();

        // Build O(1) lookup index: package name → index in metadata.packages
        let workspace_member_ids: std::collections::HashSet<_> = metadata.workspace_members.iter().collect();
        let workspace_packages: Vec<_> = metadata
            .packages
            .iter()
            .enumerate()
            .filter(|(_, pkg)| workspace_member_ids.contains(&pkg.id))
            .collect();

        let package_index = workspace_packages
            .iter()
            .map(|(idx, pkg)| (pkg.name.to_string(), *idx))
            .collect();

        // Build proc-macro crate set for O(1) detection
        let proc_macro_crates = workspace_packages
            .iter()
            .filter(|(_, pkg)| {
                pkg.targets.iter().any(|t| {
                    t.kind
                        .iter()
                        .any(|k| matches!(k, cargo_metadata::TargetKind::ProcMacro))
                })
            })
            .map(|(_, pkg)| pkg.name.to_string())
            .collect();

        Self {
            metadata,
            workspace_root,
            package_index,
            proc_macro_crates,
        }
    }

    /// Get workspace root path
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    /// Get all workspace members
    pub fn workspace_members(&self) -> Vec<&Package> {
        self.metadata.workspace_packages()
    }

    /// Get a specific workspace package by name (O(1) lookup)
    pub fn get_package(&self, name: &str) -> Option<&Package> {
        self.package_index.get(name).map(|&idx| &self.metadata.packages[idx])
    }

    /// Get the authoritative Cargo metadata.
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Clone the shared metadata handle for another workspace-level index.
    pub(crate) fn shared_metadata(&self) -> Arc<Metadata> {
        Arc::clone(&self.metadata)
    }

    /// Check if a crate is a proc-macro crate (O(1) lookup)
    pub fn is_proc_macro(&self, crate_name: &str) -> bool {
        self.proc_macro_crates.contains(crate_name)
    }

    /// Get the set of all proc-macro crate names
    pub fn proc_macro_crates(&self) -> &std::collections::HashSet<String> {
        &self.proc_macro_crates
    }

    /// Check if a package is publishable based on Cargo.toml
    ///
    /// Returns `true` if the package can be published to a registry.
    /// Returns `false` if `publish = false` in Cargo.toml.
    ///
    /// Note: This only checks Cargo.toml. For combined Cargo.toml + rail.toml
    /// checking, use `ReleaseValidator::is_publishable()`.
    pub fn is_package_publishable(package: &Package) -> bool {
        // package.publish is Option<Vec<String>>:
        // - None = publishable (no restriction)
        // - Some([]) = publish = false (empty registry list)
        // - Some(["crates-io"]) = can publish to listed registries
        package.publish.as_ref().map(|p| !p.is_empty()).unwrap_or(true)
    }

    /// Return whether Cargo permits publishing this package to `registry`.
    ///
    /// An omitted `package.publish` permits every registry. An explicit list
    /// is a hard upper bound; repository policy cannot widen it.
    pub fn package_allows_registry(package: &Package, registry: &str) -> bool {
        package
            .publish
            .as_ref()
            .is_none_or(|registries| registries.iter().any(|candidate| candidate == registry))
    }

    /// Return whether a member has a binary target but no `lib` or `proc-macro` target.
    ///
    /// Returns `false` for an unknown member.
    pub fn is_binary_only(&self, crate_name: &str) -> bool {
        let Some(pkg) = self.get_package(crate_name) else {
            return false;
        };

        let mut has_bin = false;
        let mut has_lib_like = false;

        for target in &pkg.targets {
            for kind in &target.kind {
                match kind {
                    cargo_metadata::TargetKind::Bin => has_bin = true,
                    cargo_metadata::TargetKind::Lib | cargo_metadata::TargetKind::ProcMacro => has_lib_like = true,
                    _ => {}
                }
            }
        }

        has_bin && !has_lib_like
    }
}

/// Git state for the workspace
///
/// Provides git operations scoped to the workspace repository.
/// This is built once and shared across all commands via WorkspaceContext.
#[derive(Debug, Clone)]
pub struct GitState {
    /// Underlying git backend
    git: SystemGit,

    /// Cached repository root (git working tree)
    repo_root: PathBuf,
}

impl GitState {
    /// Open git repository at the given path
    fn open(path: &Path) -> RailResult<Self> {
        let git = SystemGit::open(path)?;
        let repo_root = git.worktree_root.clone();

        Ok(Self { git, repo_root })
    }

    /// Get repository root path
    pub fn repo_root(&self) -> &Path {
        &self.repo_root
    }

    /// Access underlying SystemGit for advanced operations
    ///
    /// Use this when you need direct access to SystemGit methods.
    pub fn git(&self) -> &SystemGit {
        &self.git
    }

    /// Get current branch name
    ///
    /// Returns "HEAD" if in detached HEAD state.
    pub fn current_branch(&self) -> RailResult<String> {
        self.git.current_branch()
    }

    /// Check if HEAD is detached (not on any branch)
    pub fn is_detached_head(&self) -> RailResult<bool> {
        self.git.is_detached_head()
    }

    /// Get the default branch name (main/master) via remote HEAD
    ///
    /// Returns `None` if no default branch can be determined.
    pub fn default_branch(&self) -> RailResult<Option<String>> {
        self.git.default_branch()
    }
}

// Workspace Context

/// Unified workspace context containing all shared workspace-level data.
///
/// Built once at startup, passed by reference to all commands and operations.
/// This eliminates redundant loads and provides a single source of truth for
/// workspace state.
///
/// Uses Arc for efficient sharing across threads and parallel operations.
/// Cloning is extremely cheap (just increments Arc refcounts).
#[derive(Debug)]
pub struct WorkspaceContext {
    /// Cargo workspace root (`Cargo.toml` location).
    ///
    /// When Git is present, this root is validated as equal to or below the Git
    /// worktree. Access the repository root through [`WorkspaceContext::git`].
    pub workspace_root: PathBuf,

    /// Git state and operations, when the workspace is inside a Git repository.
    ///
    /// Commands that require Git must call [`WorkspaceContext::git`] so Cargo-only
    /// commands can still run in sandboxed workspaces.
    git: Option<Arc<GitState>>,

    /// Cargo metadata and workspace info (Arc for cheap cloning across threads)
    cargo: Arc<CargoState>,

    /// Validated repository-relative path to the Cargo workspace, when nested.
    workspace_prefix: Option<PathBuf>,

    /// Immutable source captured before Cargo metadata can create generated state.
    source_capture: Option<Arc<GitWorktreeCapture>>,

    /// Sparse source/index authority used only by non-mutating planning flows.
    planning_source_capture: Option<Arc<PlanningSourceCapture>>,

    /// Dependency graph (built from cargo metadata)
    /// Wrapped in Arc for efficient sharing across threads/commands
    graph: Arc<WorkspaceGraph>,

    /// One exact lazy derived-view owner shared with the snapshot when present.
    derived_views: Arc<DerivedViews>,

    /// Complete authoritative snapshot when requested during context construction.
    snapshot: Option<WorkspaceSnapshot>,

    /// Cargo-Rail configuration (`rail.toml`).
    /// Optional because not all commands require configuration
    /// Wrapped in Arc for efficient sharing
    config: Option<Arc<RailConfig>>,

    /// Exact discovered configuration path for planning deltas.
    config_path: Option<PathBuf>,

    /// Root used to make captured repository paths portable. Historical object
    /// planning owns a temporary materialization rather than the live Git root.
    authority_source_root: PathBuf,

    /// Retains the isolated `to` tree for the lifetime of an object-pair plan.
    historical_planning: Option<HistoricalPlanningAuthority>,
}

#[derive(Debug)]
struct HistoricalPlanningAuthority {
    _root: tempfile::TempDir,
    to: String,
    capture: String,
}

impl WorkspaceContext {
    /// Build workspace context from a root directory.
    ///
    /// Loads optional git state, cargo metadata, builds graph, and attempts to load rail.toml config.
    /// Config is optional - commands that require it should check and error.
    ///
    /// # Errors
    ///
    /// Returns [`RailError::Message`] if `cargo metadata` fails (e.g., invalid `Cargo.toml`).
    ///
    /// Returns [`RailError::Message`] if Cargo discovers a workspace outside the
    /// Git worktree opened from `workspace_root`.
    ///
    /// Returns [`RailError::Config`] if `rail.toml` exists but fails to parse.
    ///
    pub fn build(workspace_root: &Path) -> RailResult<Self> {
        Self::build_inner(workspace_root, ContextCapture::None, None)
    }

    /// Build a context and optionally capture WORKTREE source before metadata loading.
    #[doc(hidden)]
    pub fn build_with_source_capture(workspace_root: &Path, capture_source: bool) -> RailResult<Self> {
        let capture = if capture_source {
            ContextCapture::Worktree
        } else {
            ContextCapture::None
        };
        Self::build_inner(workspace_root, capture, None)
    }

    pub(crate) fn build_with_source_capture_and_config(
        workspace_root: &Path,
        capture_source: bool,
        config_override: Option<&Path>,
    ) -> RailResult<Self> {
        let capture = if capture_source {
            ContextCapture::Worktree
        } else {
            ContextCapture::None
        };
        Self::build_inner(workspace_root, capture, config_override)
    }

    pub(crate) fn build_with_planning_capture_and_config(
        workspace_root: &Path,
        config_override: Option<&Path>,
    ) -> RailResult<Self> {
        Self::build_inner(workspace_root, ContextCapture::Planning, config_override)
    }

    pub(crate) fn build_with_planning_verification_and_config(
        workspace_root: &Path,
        config_override: Option<&Path>,
    ) -> RailResult<Self> {
        Self::build_inner(workspace_root, ContextCapture::PlanningVerification, config_override)
    }

    pub(crate) fn build_historical_planning_with_config(
        workspace_root: &Path,
        from: &str,
        to: &str,
        config_override: Option<&Path>,
    ) -> RailResult<Self> {
        let source_git = Arc::new(GitState::open(workspace_root)?);
        let requested_root = crate::utils::canonicalize_existing(workspace_root).map_err(|error| {
            RailError::message(format!(
                "failed to resolve requested historical workspace root '{}': {error}",
                workspace_root.display()
            ))
        })?;
        let requested_relative =
            crate::utils::path_relative_to(source_git.repo_root(), &requested_root).map_err(|error| {
                RailError::message(format!(
                    "historical workspace root '{}' is outside Git worktree '{}': {error}",
                    requested_root.display(),
                    source_git.repo_root().display()
                ))
            })?;
        let root = tempfile::TempDir::new()
            .map_err(|error| RailError::message(format!("failed to create historical planning root: {error}")))?;
        let materialized_source_root = root.path().join("source");
        fs::create_dir(&materialized_source_root)?;
        let materialized_source_root =
            crate::utils::canonicalize_existing(&materialized_source_root).map_err(|error| {
                RailError::message(format!(
                    "failed to resolve historical planning root '{}': {error}",
                    materialized_source_root.display()
                ))
            })?;
        source_git
            .git()
            .materialize_tree(to, &materialized_source_root)
            .map_err(|error| error.context(format!("failed to materialize historical planning tree '{to}'")))?;
        let materialized_requested_root = materialized_source_root.join(requested_relative);
        let mapped_config = config_override.map(|path| {
            if !path.is_absolute() {
                return path.to_path_buf();
            }
            path.strip_prefix(source_git.repo_root()).map_or_else(
                |_| path.to_path_buf(),
                |relative| materialized_source_root.join(relative),
            )
        });
        let mut context = Self::build_inner_at(
            &materialized_requested_root,
            ContextCapture::Planning,
            mapped_config.as_deref(),
            Some(&materialized_requested_root),
        )
        .map_err(|error| {
            error.context(format!(
                "historical tree '{to}' cannot form a supported Cargo workspace or declared planning policy"
            ))
        })?;
        let workspace_prefix = crate::utils::path_relative_to(&materialized_source_root, context.workspace_root())
            .map_err(|error| {
                RailError::message(format!(
                    "historical Cargo workspace '{}' escapes materialized tree '{}': {error}",
                    context.workspace_root().display(),
                    materialized_source_root.display()
                ))
            })?;
        let capture_input = format!("historical-planning-v1\0{from}\0{to}");
        context.workspace_prefix = (!workspace_prefix.as_os_str().is_empty()).then_some(workspace_prefix);
        context.git = Some(source_git);
        context.authority_source_root = materialized_source_root;
        context.historical_planning = Some(HistoricalPlanningAuthority {
            _root: root,
            to: to.to_string(),
            capture: format!("v1-sha256-{}", ContentDigest::sha256(capture_input.as_bytes())),
        });
        Ok(context)
    }

    /// Build a context with one complete immutable workspace snapshot.
    ///
    /// Commands adopt this constructor only when they consume its complete snapshot.
    /// It performs exact source, Cargo configuration, Cargo/rustc/rustdoc
    /// and compiler-wrapper identity, target configuration, manifest, lockfile,
    /// and base-resolution capture without loading target metadata views.
    ///
    /// # Errors
    ///
    /// Returns an error when any authoritative input is unreadable, malformed,
    /// outside the captured source boundary, contains a credential-bearing Cargo
    /// configuration URL, or changes during capture. Cargo, rustc, rustdoc, and
    /// configured compiler-wrapper identity commands must also succeed.
    pub fn build_with_snapshot(workspace_root: &Path) -> RailResult<Self> {
        Self::build_inner(workspace_root, ContextCapture::Snapshot, None)
    }

    pub(crate) fn build_with_snapshot_and_config(
        workspace_root: &Path,
        config_override: Option<&Path>,
    ) -> RailResult<Self> {
        Self::build_inner(workspace_root, ContextCapture::Snapshot, config_override)
    }

    fn build_inner(workspace_root: &Path, capture: ContextCapture, config_override: Option<&Path>) -> RailResult<Self> {
        Self::build_inner_at(workspace_root, capture, config_override, None)
    }

    fn build_inner_at(
        workspace_root: &Path,
        capture: ContextCapture,
        config_override: Option<&Path>,
        cargo_current_dir: Option<&Path>,
    ) -> RailResult<Self> {
        let process_current_dir = std::env::current_dir().map_err(|error| {
            RailError::message(format!("failed to determine Cargo metadata current directory: {error}"))
        })?;
        let requested_workspace_root = if workspace_root.is_absolute() {
            workspace_root.to_path_buf()
        } else {
            process_current_dir.join(workspace_root)
        };
        // Cargo preserves manifest path aliases, while Git resolves its worktree root.
        // Capture both from the same physical root so package ownership stays comparable.
        let canonical_workspace_root =
            crate::utils::canonicalize_existing(&requested_workspace_root).map_err(|error| {
                RailError::message(format!(
                    "failed to resolve workspace root '{}': {error}",
                    requested_workspace_root.display()
                ))
            })?;
        let workspace_root = canonical_workspace_root.as_path();
        let cargo_current_dir = cargo_current_dir.map_or(process_current_dir, Path::to_path_buf);
        // Load git state when available. Cargo-only commands such as `unify --check`
        // must work in source sandboxes that intentionally omit `.git`.
        let git = match GitState::open(workspace_root) {
            Ok(git) => Some(Arc::new(git)),
            Err(RailError::Git(GitError::RepoNotFound { .. })) => None,
            Err(err) => return Err(err),
        };

        let initial_generated_roots = [super::cargo_rail_state_root(workspace_root)];
        let mut source_capture = if matches!(capture, ContextCapture::Worktree | ContextCapture::Snapshot) {
            git.as_ref()
                .map(|state| GitWorktreeCapture::capture_excluding(state.git(), &initial_generated_roots))
                .transpose()?
        } else {
            None
        };
        let mut planning_source_capture = if capture.is_planning() {
            git.as_ref()
                .map(|state| PlanningSourceCapture::capture_excluding(state.git(), &initial_generated_roots))
                .transpose()?
        } else {
            None
        };

        let planning_cargo_config = if capture == ContextCapture::Planning {
            Some(Arc::new(CargoConfigSnapshot::capture(&cargo_current_dir)?))
        } else {
            None
        };

        let resolution_inputs = if capture == ContextCapture::Snapshot {
            Some(ResolutionViews::capture_inputs(&cargo_current_dir)?)
        } else {
            None
        };

        // Load cargo state
        let cargo = Arc::new(if let Some(inputs) = &resolution_inputs {
            CargoState::load_fresh(
                workspace_root,
                &cargo_current_dir,
                inputs.toolchain.cargo_program(),
                inputs.cargo_config.has_credential_capability(),
            )?
        } else if capture.is_planning() {
            CargoState::load_planning(
                workspace_root,
                &cargo_current_dir,
                capture == ContextCapture::PlanningVerification,
            )?
        } else {
            CargoState::load(workspace_root)?
        });
        let workspace_root = cargo.workspace_root().to_path_buf();
        // Repository paths are the authority for Git-backed capture and mutation.
        // A Cargo workspace may be nested inside that boundary, but never contain it
        // or escape it. Capture this relation once so every path consumer agrees.
        let workspace_prefix = git
            .as_ref()
            .map(|git| {
                crate::utils::path_relative_to(git.repo_root(), &workspace_root).map_err(|error| {
                    RailError::with_help(
                        format!(
                            "Cargo workspace root '{}' is outside Git worktree '{}': {}",
                            workspace_root.display(),
                            git.repo_root().display(),
                            error
                        ),
                        "select a Cargo workspace contained by this repository, or run outside the nested Git worktree",
                    )
                })
            })
            .transpose()?
            .filter(|prefix| !prefix.as_os_str().is_empty());

        let generated_lockfile = if let (Some(capture), Some(git)) = (source_capture.as_mut(), git.as_ref()) {
            let generated_roots = validated_generated_source_roots(git.repo_root(), &workspace_root, &cargo)?;
            capture.exclude_generated_roots(git.git(), &generated_roots)?;
            stabilize_cargo_generated_lockfile(capture, git, &workspace_root, &generated_roots)?
        } else {
            None
        };
        let planning_generated_lockfile =
            if let (Some(capture), Some(git)) = (planning_source_capture.as_mut(), git.as_ref()) {
                let generated_roots = validated_generated_source_roots(git.repo_root(), &workspace_root, &cargo)?;
                capture.exclude_generated_roots(git.git(), &generated_roots)?;
                stabilize_planning_generated_lockfile(capture, git, &workspace_root)?
            } else {
                None
            };

        // Build the dependency graph from the metadata already loaded above.
        let graph = Arc::new(WorkspaceGraph::from_metadata(cargo.metadata())?);

        let resolution_views = Arc::new(if let Some(inputs) = resolution_inputs.clone() {
            ResolutionViews::new_with_inputs(
                workspace_root.clone(),
                cargo_current_dir,
                cargo.shared_metadata(),
                Arc::clone(&graph),
                inputs,
            )
        } else if let Some(cargo_config) = planning_cargo_config.clone() {
            ResolutionViews::new_with_cargo_config(
                workspace_root.clone(),
                cargo_current_dir,
                cargo.shared_metadata(),
                Arc::clone(&graph),
                cargo_config,
            )
        } else {
            ResolutionViews::new(
                workspace_root.clone(),
                cargo_current_dir,
                cargo.shared_metadata(),
                Arc::clone(&graph),
            )
        });

        // Discover once and retain the exact parsed bytes for snapshot coherence.
        let config_path = config_override.map_or_else(
            || RailConfig::find_config_path(&workspace_root),
            |path| {
                Some(if path.is_absolute() {
                    path.to_path_buf()
                } else {
                    requested_workspace_root.join(path)
                })
            },
        );
        let (config, rail_config, rail_config_discovery_root, captured_config_path) = match config_path {
            Some(path) => {
                let (decoded, bytes) = crate::config::load_decoded(&path)?;
                let parsed = decoded.config;
                let parsed = Arc::new(parsed);
                (
                    Some(Arc::clone(&parsed)),
                    Some(CapturedRailConfig::new(path.clone(), bytes, parsed)),
                    None,
                    Some(path),
                )
            }
            None => (None, None, Some(workspace_root.clone()), None),
        };

        if let Some(ref cfg) = config {
            let workspace_members = cargo
                .workspace_members()
                .into_iter()
                .map(|package| package.name.to_string())
                .collect::<Vec<_>>();
            cfg.validate(&workspace_root, Some(&workspace_members))?;
        }

        // The top-level policy is the only non-host target authority. Surface
        // either inherits it or selects an already-declared subset.
        let mut targets = config.as_ref().map(|c| c.targets.clone()).unwrap_or_default();
        targets.sort();
        targets.dedup();
        let derived_views = Arc::new(DerivedViews::new(
            workspace_root.clone(),
            targets.clone(),
            Arc::clone(&resolution_views),
        ));

        let snapshot = if let Some(inputs) = resolution_inputs {
            let generated_lock_marker = generated_lockfile
                .as_ref()
                .map(|lockfile| (lockfile.path().to_path_buf(), ContentDigest::sha256(lockfile.bytes())));
            let captured_lockfile = generated_lockfile;
            let source = match (&source_capture, &git) {
                (Some(capture), Some(_)) => capture.shared_snapshot(),
                (None, None) => Arc::new(SourceSnapshot::capture_filesystem(
                    &workspace_root,
                    &generated_source_roots(&workspace_root, &cargo),
                )?),
                _ => {
                    return Err(RailError::message(
                        "workspace snapshot source backend is inconsistent with repository state",
                    ));
                }
            };
            let source_root = git.as_ref().map_or(workspace_root.as_path(), |git| git.repo_root());
            let target_identities = capture_target_identities(derived_views.cargo_current_dir(), &targets, &inputs)?;
            let snapshot = WorkspaceSnapshot::capture(super::snapshot::WorkspaceSnapshotCapture {
                source_root,
                source,
                cargo: Arc::clone(&cargo),
                rail_config,
                rail_config_discovery_root,
                generated_lockfile: captured_lockfile,
                resolution_inputs: inputs.clone(),
                targets: target_identities,
                derived: Arc::clone(&derived_views),
            })?;
            if let (Some(capture), Some(git)) = (&source_capture, &git) {
                capture.validate_unchanged(git.git())?;
            }
            snapshot.validate_authoritative_files_unchanged()?;
            let current_inputs = ResolutionViews::capture_inputs(resolution_views.cargo_current_dir())?;
            validate_resolution_inputs_unchanged(&inputs, &current_inputs)?;
            snapshot.validate_external_targets_unchanged()?;
            if let Some((path, digest)) = generated_lock_marker {
                write_generated_lock_marker(&workspace_root, &path, digest)?;
            }
            Some(snapshot)
        } else {
            None
        };

        if let (Some(capture), Some(git)) = (&planning_source_capture, &git) {
            capture.validate_unchanged(git.git())?;
        }
        if let Some(initial) = planning_cargo_config {
            let current = CargoConfigSnapshot::capture(resolution_views.cargo_current_dir())?;
            if current != *initial {
                return Err(RailError::with_help(
                    "Cargo configuration changed while constructing the planning context",
                    "retry after Cargo configuration and environment changes have stopped",
                ));
            }
        }
        if capture == ContextCapture::Planning
            && let Some(lockfile) = planning_generated_lockfile
        {
            write_generated_lock_marker(
                &workspace_root,
                lockfile.path(),
                ContentDigest::sha256(lockfile.bytes()),
            )?;
        }

        let authority_source_root = git
            .as_ref()
            .map_or_else(|| workspace_root.clone(), |git| git.repo_root().to_path_buf());
        Ok(Self {
            workspace_root,
            git,
            cargo,
            workspace_prefix,
            source_capture: source_capture.map(Arc::new),
            planning_source_capture: planning_source_capture.map(Arc::new),
            graph,
            derived_views,
            snapshot,
            config,
            config_path: captured_config_path,
            authority_source_root,
            historical_planning: None,
        })
    }

    /// Get config or error if not found.
    ///
    /// Use this in commands that require rail.toml configuration.
    pub fn require_config(&self) -> RailResult<&Arc<RailConfig>> {
        self.config().ok_or_else(|| {
      crate::error::RailError::message(format!(
        "No rail.toml found in: {}\nSearched: rail.toml, .rail.toml, .cargo/rail.toml, .config/rail.toml\nRun 'cargo rail init' to create one.",
        self.workspace_root.display()
      ))
    })
    }

    /// Return the parsed rail configuration from the authoritative snapshot when present.
    pub fn config(&self) -> Option<&Arc<RailConfig>> {
        self.snapshot
            .as_ref()
            .and_then(WorkspaceSnapshot::shared_config)
            .or(self.config.as_ref())
    }

    pub(crate) fn config_path(&self) -> Option<&Path> {
        self.config_path.as_deref()
    }

    /// Return Cargo state paired with the authoritative snapshot metadata.
    pub fn cargo(&self) -> &CargoState {
        self.snapshot
            .as_ref()
            .map(WorkspaceSnapshot::cargo)
            .unwrap_or(&self.cargo)
    }

    /// Return the exact dependency graph owned by the authoritative base resolution.
    pub fn graph(&self) -> &WorkspaceGraph {
        self.snapshot
            .as_ref()
            .map(|snapshot| snapshot.base_resolution().graph())
            .unwrap_or(&self.graph)
    }

    /// Return Git state for commands that require repository history.
    pub fn git(&self) -> RailResult<&GitState> {
        self.git.as_deref().ok_or_else(|| {
            RailError::Git(GitError::RepoNotFound {
                path: self.workspace_root.clone(),
            })
        })
    }

    /// Return true when this workspace is inside a Git repository.
    pub fn has_git(&self) -> bool {
        self.git.is_some()
    }

    /// Return source captured before metadata loading, when requested by dispatch.
    ///
    /// Ignored paths, the resolved Cargo target/build directories, and
    /// workspace-owned cargo-rail state are absent from this capture.
    pub fn source_capture(&self) -> Option<&GitWorktreeCapture> {
        self.source_capture.as_deref()
    }

    pub(crate) fn planning_source_capture(&self) -> Option<&PlanningSourceCapture> {
        self.planning_source_capture.as_deref()
    }

    pub(crate) fn planning_snapshot_id(&self) -> Option<String> {
        self.historical_planning
            .as_ref()
            .map(|authority| authority.capture.clone())
            .or_else(|| {
                self.planning_source_capture
                    .as_ref()
                    .map(|capture| format!("v1-sha256-{}", capture.identity()))
            })
    }

    pub(crate) fn planning_head_commit(&self) -> Option<&str> {
        self.historical_planning
            .as_ref()
            .map(|authority| authority.to.as_str())
            .or_else(|| self.planning_source_capture().map(PlanningSourceCapture::head_commit))
    }

    pub(crate) fn planning_cargo_configuration_identity(&self) -> RailResult<String> {
        let identity = self
            .derived_views
            .cargo_config()?
            .portable_snapshot_identity(&self.authority_source_root)?;
        Ok(format!(
            "cargo-configuration-v1:sha256:{}",
            ContentDigest::sha256(&identity)
        ))
    }

    /// Return the versioned identity for the complete or sparse authority captured by this context.
    #[doc(hidden)]
    pub fn captured_authority_id(&self) -> Option<String> {
        self.snapshot_id()
            .map(|snapshot| snapshot.to_string())
            .or_else(|| self.planning_snapshot_id())
    }

    pub(crate) fn read_planning_current_files(&self, paths: &[String]) -> RailResult<Vec<Vec<u8>>> {
        if self.historical_planning.is_some() {
            return paths
                .iter()
                .map(|path| {
                    let path = RepositoryPath::new(Path::new(path))?;
                    let absolute = self.workspace_root.join(path.as_path());
                    let metadata = fs::symlink_metadata(&absolute).map_err(|error| {
                        RailError::message(format!("failed to read historical planning input '{}': {error}", path))
                    })?;
                    if !metadata.file_type().is_file() {
                        return Err(RailError::with_help(
                            format!("historical planning input '{}' is not a regular file", path),
                            "replace the declared input with a regular repository file",
                        ));
                    }
                    fs::read(absolute).map_err(Into::into)
                })
                .collect();
        }
        let capture = self
            .planning_source_capture()
            .ok_or_else(|| RailError::message("workspace context was built without sparse planning source capture"))?;
        let repository_paths = paths
            .iter()
            .map(|path| {
                let path = self
                    .workspace_prefix
                    .as_ref()
                    .map_or_else(|| PathBuf::from(path), |prefix| prefix.join(path));
                RepositoryPath::new(&path)
            })
            .collect::<RailResult<Vec<_>>>()?;
        capture.read_current_files(self.git()?.git(), &repository_paths)
    }

    pub(crate) fn capture_worktree_source(&self) -> RailResult<GitWorktreeCapture> {
        let git = self.git()?;
        let generated_roots = validated_generated_source_roots(git.repo_root(), &self.workspace_root, &self.cargo)?;
        GitWorktreeCapture::capture_excluding(git.git(), &generated_roots)
    }

    /// Capture this declared Cargo workspace directly from the filesystem.
    ///
    /// The exact Cargo target/build directories and workspace-owned cargo-rail
    /// state are excluded. Git ignore files are not interpreted, so this remains
    /// deterministic in source archives and sandboxes without repository state.
    ///
    /// # Errors
    ///
    /// Returns an error when this context has a Git backend; callers must use the
    /// Git-backed capture so repository metadata and ignore policy remain authoritative.
    ///
    /// Returns an error when the workspace cannot be walked consistently or a
    /// generated-state root would exclude the complete workspace boundary.
    pub fn capture_filesystem_source(&self) -> RailResult<SourceSnapshot> {
        if self.has_git() {
            return Err(RailError::with_help(
                "filesystem-backed source capture is only available without Git",
                "use the Git-backed worktree capture for repositories",
            ));
        }
        SourceSnapshot::capture_filesystem(
            &self.workspace_root,
            &generated_source_roots(&self.workspace_root, &self.cargo),
        )
    }

    /// Return current non-generated source paths that differ from `HEAD`.
    pub(crate) fn changed_source_paths(&self) -> RailResult<Vec<PathBuf>> {
        let git = self.git()?.git();
        let owned_capture;
        let capture = if let Some(capture) = self.source_capture() {
            capture
        } else {
            owned_capture = self.capture_worktree_source()?;
            &owned_capture
        };
        Ok(capture
            .changes_from(git, "HEAD")?
            .entries()
            .iter()
            .map(|change| change.path.as_path().to_path_buf())
            .collect())
    }

    /// Remove workspace-generated paths from a repository-relative path set.
    pub(crate) fn non_generated_source_paths(&self, paths: &[PathBuf]) -> RailResult<Vec<PathBuf>> {
        let git = self.git()?;
        let generated_roots = validated_generated_source_roots(git.repo_root(), &self.workspace_root, &self.cargo)?;
        let exclusions = SourceExclusions::from_absolute_roots(git.git(), &generated_roots)?;
        let mut source_paths = Vec::with_capacity(paths.len());
        for path in paths {
            if !exclusions.contains(&RepositoryPath::new(path)?) {
                source_paths.push(path.clone());
            }
        }
        Ok(source_paths)
    }

    /// Return final non-generated source paths that differ from `base`.
    ///
    /// With no base, every path in the final source tree is returned. This is
    /// the release-coverage meaning of a crate with no previous release.
    pub(crate) fn source_paths_since(&self, base: Option<&str>) -> RailResult<Vec<PathBuf>> {
        let owned_capture;
        let capture = if let Some(capture) = self.source_capture() {
            capture
        } else {
            owned_capture = self.capture_worktree_source()?;
            &owned_capture
        };

        match base {
            Some(base) => Ok(capture
                .changes_from(self.git()?.git(), base)?
                .entries()
                .iter()
                .map(|change| change.path.as_path().to_path_buf())
                .collect()),
            None => Ok(capture
                .snapshot()
                .tree()
                .entries()
                .iter()
                .map(|entry| entry.path.as_path().to_path_buf())
                .collect()),
        }
    }

    /// Capture one rich source change set between exact Git objects.
    pub(crate) fn object_source_changes(&self, base: &str, head: &str) -> RailResult<ChangeSet> {
        let git = self.git()?;
        let generated_roots = if self.historical_planning.is_some() {
            generated_source_roots(&self.workspace_root, &self.cargo)
                .into_iter()
                .filter_map(|root| {
                    root.strip_prefix(&self.authority_source_root)
                        .ok()
                        .map(|relative| git.repo_root().join(relative))
                })
                .collect()
        } else {
            validated_generated_source_roots(git.repo_root(), &self.workspace_root, &self.cargo)?
        };
        let exclusions = SourceExclusions::from_absolute_roots(git.git(), &generated_roots)?;
        changes_between_objects(git.git(), base, head, &exclusions)
    }

    pub(crate) fn planning_authority_source_root(&self) -> &Path {
        &self.authority_source_root
    }

    pub(crate) fn repository_path_from_workspace(&self, path: &Path) -> RailResult<PathBuf> {
        let relative = if path.is_absolute() {
            path.strip_prefix(&self.workspace_root).map_err(|_| {
                RailError::message(format!(
                    "workspace path '{}' is outside captured workspace '{}'",
                    path.display(),
                    self.workspace_root.display()
                ))
            })?
        } else {
            path
        };
        Ok(self
            .workspace_prefix
            .as_ref()
            .map_or_else(|| relative.to_path_buf(), |prefix| prefix.join(relative)))
    }

    /// Get multi-target metadata, loading lazily on first access.
    ///
    /// This is only used by `cargo rail unify`; other commands do not load it.
    ///
    /// The metadata is cached after first load - subsequent calls return the cached value.
    pub fn multi_target_metadata(&self) -> RailResult<Arc<MultiTargetMetadata>> {
        if let Some(snapshot) = &self.snapshot {
            snapshot.multi_target_metadata()
        } else {
            self.derived_views.multi_target_metadata()
        }
    }

    /// Return the exact lazy Cargo resolution for one package/feature/target request.
    pub fn resolution_view(&self, request: ResolutionRequest) -> RailResult<Arc<ResolutionView>> {
        if let Some(snapshot) = &self.snapshot {
            snapshot.resolution_view(request)
        } else {
            self.derived_views.resolution_view(request)
        }
    }

    /// Return the authoritative snapshot captured by [`Self::build_with_snapshot`].
    ///
    /// Other constructors intentionally avoid this work until command consumers
    /// require the complete snapshot contract.
    ///
    /// # Errors
    ///
    /// Returns an error when this context was built by another constructor.
    pub fn snapshot(&self) -> RailResult<&WorkspaceSnapshot> {
        self.snapshot.as_ref().ok_or_else(|| {
            RailError::with_help(
                "workspace context was built without authoritative snapshot capture",
                "construct it with WorkspaceContext::build_with_snapshot",
            )
        })
    }

    /// Capture the authoritative post-mutation workspace using the same config
    /// selection as this command. This boundary is reserved for verification
    /// after an authorized write invalidates the original snapshot.
    pub(crate) fn recapture_after_mutation(&self) -> RailResult<Self> {
        let config_path = self.snapshot()?.rail_config_path().map(Path::to_path_buf);
        Self::build_with_snapshot_and_config(&self.workspace_root, config_path.as_deref())
    }

    /// Return the authoritative snapshot identity when this context owns one.
    #[doc(hidden)]
    pub fn snapshot_id(&self) -> Option<crate::workspace::SnapshotId> {
        self.snapshot.as_ref().map(WorkspaceSnapshot::id)
    }

    pub(crate) fn validate_snapshot_unchanged(&self) -> RailResult<()> {
        self.validate_snapshot_unchanged_excluding(&[])
    }

    pub(crate) fn validate_snapshot_unchanged_excluding(&self, authorized_outputs: &[PathBuf]) -> RailResult<()> {
        let snapshot = self.snapshot()?;
        if let (Some(capture), Some(git)) = (&self.source_capture, &self.git) {
            if authorized_outputs.is_empty() {
                capture.validate_unchanged(git.git())?;
            } else {
                let mut expected = capture.as_ref().clone();
                expected.exclude_generated_roots(git.git(), authorized_outputs)?;
                expected.validate_unchanged(git.git())?;
            }
        }
        snapshot.validate_live_authoritative_inputs()
    }

    pub(crate) fn validate_planning_source_unchanged(&self) -> RailResult<()> {
        if let (Some(capture), Some(git)) = (&self.planning_source_capture, &self.git) {
            capture.validate_unchanged(git.git())?;
        }
        Ok(())
    }

    /// Load each target's exact rustc cfg set once for the command context.
    pub fn target_cfg_sets(&self) -> RailResult<Arc<std::collections::HashMap<String, TargetCfgSet>>> {
        if let Some(snapshot) = &self.snapshot {
            snapshot.target_cfg_sets()
        } else {
            self.derived_views.target_cfg_sets()
        }
    }

    /// Get workspace root as Path reference (convenience)
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    /// Get the validated relative path from the Git root to the Cargo workspace.
    ///
    /// Returns `Some(prefix)` if workspace is nested inside git repo (e.g., "codex-rs"),
    /// or `None` if they're the same directory.
    ///
    /// This is used to strip the prefix from git-relative paths so they can be
    /// matched against workspace-relative paths (e.g., for crate membership).
    pub fn workspace_prefix(&self) -> Option<PathBuf> {
        self.workspace_prefix.clone()
    }

    /// Convert a git-relative path to a workspace-relative path.
    ///
    /// If the workspace is nested inside the git repo (e.g., git at `/repo`, workspace at `/repo/rust`),
    /// git returns paths like `rust/src/lib.rs` but the workspace expects `src/lib.rs`.
    ///
    /// Returns `None` if the path doesn't belong to this workspace.
    pub fn to_workspace_path(&self, git_path: &Path) -> Option<PathBuf> {
        if let Some(prefix) = &self.workspace_prefix {
            // Git always uses forward slashes, but PathBuf::from converts to platform separators.
            // On Windows, this causes strip_prefix to fail when git_path has / but prefix has \.
            // Normalize git_path by rebuilding through components to use platform separators.
            let normalized = git_path.components().collect::<PathBuf>();
            normalized.strip_prefix(prefix).ok().map(|p| p.to_path_buf())
        } else {
            Some(git_path.to_path_buf())
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ContextCapture {
    None,
    Worktree,
    Planning,
    PlanningVerification,
    Snapshot,
}

impl ContextCapture {
    fn is_planning(self) -> bool {
        matches!(self, Self::Planning | Self::PlanningVerification)
    }
}

fn validate_resolution_inputs_unchanged(initial: &ResolutionInputs, current: &ResolutionInputs) -> RailResult<()> {
    if current.cargo_config != initial.cargo_config {
        return Err(RailError::with_help(
            "Cargo configuration changed while constructing the workspace snapshot",
            "retry after Cargo configuration and environment changes have stopped",
        ));
    }
    if current.toolchain != initial.toolchain {
        return Err(RailError::with_help(
            "Cargo, rustc, rustdoc, or compiler-wrapper identity changed while constructing the workspace snapshot",
            "retry after toolchain updates and overrides have stopped",
        ));
    }
    Ok(())
}

fn validated_generated_source_roots(
    git_root: &Path,
    workspace_root: &Path,
    cargo: &CargoState,
) -> RailResult<Vec<PathBuf>> {
    validate_cargo_output_root(
        "target",
        git_root,
        workspace_root,
        cargo.metadata().target_directory.as_std_path(),
    )?;
    if let Some(build_directory) = &cargo.metadata().build_directory {
        validate_cargo_output_root("build", git_root, workspace_root, build_directory.as_std_path())?;
    }
    Ok(generated_source_roots(workspace_root, cargo))
}

fn generated_source_roots(workspace_root: &Path, cargo: &CargoState) -> Vec<PathBuf> {
    let mut roots = vec![
        super::cargo_rail_state_root(workspace_root),
        cargo.metadata().target_directory.as_std_path().to_path_buf(),
    ];
    if let Some(build_directory) = &cargo.metadata().build_directory {
        roots.push(build_directory.as_std_path().to_path_buf());
    }
    roots
}

fn stabilize_cargo_generated_lockfile(
    initial: &mut GitWorktreeCapture,
    git: &GitState,
    workspace_root: &Path,
    generated_roots: &[PathBuf],
) -> RailResult<Option<CapturedLockfile>> {
    let lockfile = workspace_root.join("Cargo.lock");
    let lockfile_metadata = match fs::symlink_metadata(&lockfile) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    if !lockfile_metadata.file_type().is_file() {
        return Ok(None);
    }
    let relative = crate::utils::path_relative_to(git.repo_root(), &lockfile)?;
    let relative = RepositoryPath::new(&relative)?;
    let initially_captured = initial
        .snapshot()
        .tree()
        .entries()
        .binary_search_by(|entry| entry.path.cmp(&relative))
        .is_ok();
    if initially_captured {
        if initial.is_untracked(&relative) {
            let bytes = fs::read(&lockfile)?;
            let digest = ContentDigest::sha256(&bytes);
            if generated_lock_marker_matches(workspace_root, digest)? {
                initial.exclude_generated_roots(git.git(), std::slice::from_ref(&lockfile))?;
                initial.validate_unchanged(git.git())?;
                return Ok(Some(CapturedLockfile::new(lockfile, bytes)));
            }
        }
        return Ok(None);
    }

    let repeated = GitWorktreeCapture::capture_excluding(git.git(), generated_roots)?;
    let repeated_digest = repeated
        .snapshot()
        .tree()
        .entries()
        .binary_search_by(|entry| entry.path.cmp(&relative))
        .ok()
        .and_then(|index| match repeated.snapshot().tree().entries()[index].kind {
            SourceEntryKind::RegularFile { digest, .. } => Some(digest),
            _ => None,
        });
    let Some(repeated_digest) = repeated_digest else {
        return Ok(None);
    };
    let bytes = fs::read(&lockfile)?;
    if repeated_digest != ContentDigest::sha256(&bytes) {
        return Err(RailError::with_help(
            "Cargo-generated lockfile changed after source capture",
            "retry after workspace input changes have stopped",
        ));
    }
    initial.exclude_generated_roots(git.git(), std::slice::from_ref(&lockfile))?;
    Ok(Some(CapturedLockfile::new(lockfile, bytes)))
}

fn stabilize_planning_generated_lockfile(
    initial: &mut PlanningSourceCapture,
    git: &GitState,
    workspace_root: &Path,
) -> RailResult<Option<CapturedLockfile>> {
    let lockfile = workspace_root.join("Cargo.lock");
    let metadata = match fs::symlink_metadata(&lockfile) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    if !metadata.file_type().is_file() {
        return Ok(None);
    }

    let relative = crate::utils::path_relative_to(git.repo_root(), &lockfile)?;
    let relative = RepositoryPath::new(&relative)?;
    if initial.is_indexed(&relative) {
        return Ok(None);
    }

    let bytes = fs::read(&lockfile)?;
    let digest = ContentDigest::sha256(&bytes);
    if initial.is_untracked(&relative) && !generated_lock_marker_matches(workspace_root, digest)? {
        return Ok(None);
    }

    initial.exclude_generated_roots(git.git(), std::slice::from_ref(&lockfile))?;
    Ok(Some(CapturedLockfile::new(lockfile, bytes)))
}

fn generated_lock_marker_path(workspace_root: &Path) -> PathBuf {
    super::cargo_rail_state_root(workspace_root).join("generated-lockfile-v1")
}

fn generated_lock_marker_value(workspace_root: &Path, digest: ContentDigest) -> RailResult<Vec<u8>> {
    let workspace = workspace_root
        .to_str()
        .ok_or_else(|| RailError::message("workspace root is not valid UTF-8 for generated lockfile provenance"))?;
    let mut marker = Vec::from(&b"cargo-rail-generated-lockfile-v1\0"[..]);
    marker.extend_from_slice(&(workspace.len() as u64).to_le_bytes());
    marker.extend_from_slice(workspace.as_bytes());
    marker.extend_from_slice(digest.as_bytes());
    Ok(marker)
}

fn generated_lock_marker_matches(workspace_root: &Path, digest: ContentDigest) -> RailResult<bool> {
    let marker = generated_lock_marker_path(workspace_root);
    let metadata = match fs::symlink_metadata(&marker) {
        Ok(metadata) if metadata.file_type().is_file() => metadata,
        Ok(_) => return Ok(false),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error.into()),
    };
    let expected = generated_lock_marker_value(workspace_root, digest)?;
    let expected_len = u64::try_from(expected.len())
        .map_err(|_| RailError::message("generated lockfile marker length exceeds the supported range"))?;
    if metadata.len() != expected_len {
        return Ok(false);
    }
    let mut actual = Vec::with_capacity(expected.len());
    fs::File::open(marker)?
        .take(expected_len.saturating_add(1))
        .read_to_end(&mut actual)?;
    Ok(actual == expected)
}

fn write_generated_lock_marker(workspace_root: &Path, lockfile: &Path, digest: ContentDigest) -> RailResult<()> {
    if lockfile != workspace_root.join("Cargo.lock") {
        return Err(RailError::message(format!(
            "refusing to mark unexpected generated lockfile '{}'",
            lockfile.display()
        )));
    }
    let marker = generated_lock_marker_path(workspace_root);
    if fs::symlink_metadata(&marker).is_ok_and(|metadata| !metadata.file_type().is_file()) {
        return Err(RailError::message(format!(
            "generated lockfile marker '{}' is not a regular file",
            marker.display()
        )));
    }
    let parent = marker
        .parent()
        .ok_or_else(|| RailError::message("generated lockfile marker has no parent directory"))?;
    fs::create_dir_all(parent)?;
    fs::write(&marker, generated_lock_marker_value(workspace_root, digest)?).map_err(|error| {
        RailError::message(format!(
            "failed to write generated lockfile marker '{}': {error}",
            marker.display()
        ))
    })
}

fn validate_cargo_output_root(
    kind: &str,
    git_root: &Path,
    workspace_root: &Path,
    output_root: &Path,
) -> RailResult<()> {
    let git_root = crate::utils::canonicalize_existing(git_root)?;
    let workspace_root = crate::utils::canonicalize_existing(workspace_root)?;
    let output_root = crate::utils::canonicalize_allow_missing(output_root)?;
    if output_root.starts_with(&git_root) && workspace_root.starts_with(&output_root) {
        return Err(RailError::with_help(
            format!(
                "Cargo {} directory '{}' contains Cargo workspace root '{}'",
                kind,
                output_root.display(),
                workspace_root.display()
            ),
            "configure Cargo build output in a dedicated directory below or outside the repository",
        ));
    }
    Ok(())
}

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

    #[test]
    fn test_workspace_context_build() {
        // Use current directory as test workspace
        let current_dir = std::env::current_dir().unwrap();

        // Should successfully build workspace context
        let ctx = WorkspaceContext::build(&current_dir);
        assert!(ctx.is_ok(), "Should successfully build workspace context");

        let ctx = ctx.unwrap();

        // Verify all components are initialized
        assert!(ctx.git().unwrap().repo_root().exists(), "Repo root should exist");
        assert!(ctx.workspace_root.exists(), "Workspace root should exist");

        // Git state should be initialized (git root typically == workspace root)
        // We allow them to differ but in most cases they're the same
        let _ = ctx.git().unwrap().repo_root();

        // Cargo state should be initialized
        assert_eq!(
            ctx.cargo().workspace_root(),
            &ctx.workspace_root,
            "Cargo workspace root should match"
        );

        // Should find cargo-rail in workspace
        let packages = ctx.cargo().workspace_members();
        assert!(!packages.is_empty(), "Should have workspace packages");
        assert!(
            packages.iter().any(|p| p.name == "cargo-rail"),
            "Should find cargo-rail package"
        );

        // Graph should be initialized
        let members = ctx.graph().workspace_members();
        assert!(!members.is_empty(), "Graph should have workspace members");
        assert!(
            members.contains(&"cargo-rail".to_string()),
            "Graph should contain cargo-rail"
        );

        // Config may or may not be loaded depending on workspace
        // Just verify it's an Option
        let _ = ctx.config();
    }

    #[test]
    fn test_git_state_wrapper() {
        let current_dir = std::env::current_dir().unwrap();
        let ctx = WorkspaceContext::build(&current_dir).unwrap();

        // Should be able to access git operations via git() accessor
        let head = ctx.git().unwrap().git().head_commit();
        assert!(head.is_ok(), "Should get HEAD commit");

        let head_sha = head.unwrap();
        assert_eq!(head_sha.len(), 40, "HEAD SHA should be 40 characters");

        // Should be able to get current branch
        let branch = ctx.git().unwrap().git().current_branch();
        assert!(branch.is_ok(), "Should get current branch");
    }

    #[test]
    fn test_cargo_state_wrapper() {
        let current_dir = std::env::current_dir().unwrap();
        let ctx = WorkspaceContext::build(&current_dir).unwrap();

        // Should be able to access cargo metadata
        let metadata = ctx.cargo().metadata();
        let packages = metadata.workspace_packages();
        assert!(!packages.is_empty(), "Should have packages");

        // Should be able to get specific package
        let cargo_rail = ctx.cargo().get_package("cargo-rail");
        assert!(cargo_rail.is_some(), "Should find cargo-rail package");

        let pkg = cargo_rail.unwrap();
        assert_eq!(pkg.name.as_str(), "cargo-rail");
    }

    #[test]
    fn test_graph_integration() {
        let current_dir = std::env::current_dir().unwrap();
        let ctx = WorkspaceContext::build(&current_dir).unwrap();

        // Graph should be consistent with cargo metadata
        let graph_members = ctx.graph().workspace_members();
        let cargo_packages: Vec<_> = ctx
            .cargo()
            .workspace_members()
            .iter()
            .map(|p| p.name.as_str())
            .collect();

        for member in graph_members {
            assert!(
                cargo_packages.contains(&member.as_str()),
                "Graph member {} should be in cargo packages",
                member
            );
        }
    }
}