proa_build 0.2.1

Linked RSJS build engine and artifact cache for Proa
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
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! End-to-end orchestration for one exact RSJS Cargo root.
//!
//! This module is deliberately small glue over the independently tested
//! descriptor runner, exact-artifact transport linker, canonical semantic
//! linker, and plan-sensitive final runner. It does not discover artifacts in
//! a target directory or infer a root from a source path. The caller supplies
//! one exact Cargo artifact selector, and every later identity comes from
//! Cargo messages, validated wrapper sidecars, or rustc relocations.

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::sync::Arc;

use rsjs_ir::abi::{AbiVersion, InvocationId, LinkUnitId, ProducerVersion, SemanticHash};
use rsjs_ir::build::ArtifactRole;
use thiserror::Error;

use crate::abi_adapter::{
    adapt_transport_plan, AbiAdapterContext, AbiAdapterError, AdaptedTransportAbi,
};
use crate::build::{
    build_link_unit_manifest, descriptor_run_sealed, join_cargo_enumerated_descriptor_units,
    managed_paths_overlap, normalize_managed_path_identity, remove_successful_descriptor_staging,
    run_descriptor_cargo, validate_descriptor_managed_paths, CargoCompilerArtifact,
    DescriptorCargoOutput, DescriptorCargoReport, DescriptorCargoRequest, DescriptorCargoRun,
    DescriptorCargoRunError, DescriptorCargoUnitId, LinkManifestAssemblyError,
    UnitArtifactJoinError, ValidatedDescriptorUnit,
};
use crate::cache::{run_descriptor_cargo_cached, DescriptorCacheError};
#[cfg(test)]
use crate::final_compile::FinalCargoArtifactReport;
use crate::final_compile::{
    ensure_plain_managed_directory, ensure_plain_managed_file, run_final_cargo_leased,
    run_final_cargo_leased_optimistic, snapshot_final_artifact, FinalCargoError, FinalCargoOutput,
    FinalCargoRequest, FinalCargoRun, FinalSnapshotLease, ManagedPathError,
    OptimisticFinalCargoOutcome, FINAL_SNAPSHOT_ROOT_NAME,
};
use crate::link::{link_transport_manifest, TransportLinkError, TransportLinkPlan};
use crate::semantic_link::{
    link_semantic_plan, write_content_addressed_semantic_plan, SemanticLinkError, SemanticLinkPlan,
    SemanticPlanWriteError,
};

/// Exact Cargo root selected from the descriptor invocation's JSON messages.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DescriptorRootSelector {
    /// Exact Cargo package ID from a `compiler-artifact` message.
    pub package_id: String,
    /// Exact target name.
    pub target_name: String,
    /// Exact normalized Cargo target-kind set.
    pub target_kinds: BTreeSet<String>,
    /// Link-manifest role for this selected root.
    pub role: ArtifactRole,
    /// Exact Cargo-enumerated root filename.
    ///
    /// This may be omitted only when Cargo reported exactly one usable
    /// executable or filename for the selected artifact.
    pub artifact_path: Option<PathBuf>,
}

/// One complete descriptor, link, and final-Cargo request.
#[derive(Clone, Debug)]
pub struct LinkedCargoRequest {
    /// Exact descriptor-pass Cargo request.
    pub descriptor: DescriptorCargoRequest,
    /// Root selector applied only to that invocation's Cargo JSON messages.
    pub root: DescriptorRootSelector,
    /// Pre-Cargo invocation identity.
    pub invocation: InvocationId,
    /// Compiler producer version recorded in canonical descriptor envelopes.
    pub producer: ProducerVersion,
    /// Runtime protocol selected for canonical compatibility checks.
    pub runtime_protocol: AbiVersion,
    /// Absolute content-addressed semantic-plan directory.
    pub plan_directory: PathBuf,
    /// Absolute parent for invocation- and wrapper-policy-scoped final target
    /// directories.
    pub final_target_root: PathBuf,
    /// Cargo arguments for final compilation, without runner-owned
    /// `--message-format` or `--target-dir`.
    /// A final `test --no-run` returns the attested harness without launching it.
    pub final_cargo_args: Vec<OsString>,
    /// Exact additional environment for final Cargo.
    pub final_environment: BTreeMap<OsString, OsString>,
}

/// Successful output of every stage for one selected root.
#[derive(Clone, Debug)]
pub struct LinkedCargoOutput {
    /// Path-free descriptor Cargo diagnostics.
    pub descriptor: DescriptorCargoReport,
    /// Exact selected descriptor unit.
    pub root_unit: DescriptorCargoUnitId,
    /// Relocation-resolved transport graph.
    pub transport: TransportLinkPlan,
    /// Canonical descriptors produced by the compatibility bridge.
    pub adapted: AdaptedTransportAbi,
    /// Canonical semantic owner/helper plan.
    pub semantic: SemanticLinkPlan,
    /// Exact content-addressed semantic-plan path.
    pub semantic_plan_path: PathBuf,
    /// Plan-sensitive final Cargo output.
    pub final_cargo: FinalCargoOutput,
    /// Exact final-phase Cargo artifact attesting the selected descriptor root.
    pub final_root_artifact: CargoCompilerArtifact,
    /// Absolute local inputs Cargo recorded for the final root executable: its
    /// sources, `include_*!` files, declared build-script inputs (files or
    /// directories), and those of every path dependency. `None` when the root
    /// has no executable, its dep-info is unavailable, or a local build script
    /// declares no inputs (Cargo then treats its whole package as an input).
    pub final_root_inputs: Option<Vec<PathBuf>>,
    /// Keeps the executable snapshot from being pruned while any clone of
    /// this output is alive. Hold it until the executable has been spawned.
    pub final_root_lease: Option<Arc<FinalSnapshotLease>>,
}

/// Read Cargo's `<artifact>.d` beside a final executable: one
/// `target: dep dep ...` rule per line, with spaces and backslashes in paths
/// escaped by a backslash. This is not rustc's dep-info dialect (no phony
/// targets, no `# env-dep` records).
fn cargo_dep_info_inputs(executable: &Path) -> Option<Vec<PathBuf>> {
    let name = executable.file_name()?.to_str()?;
    let stem = name
        .strip_suffix(std::env::consts::EXE_SUFFIX)
        .unwrap_or(name);
    let text = fs::read_to_string(executable.with_file_name(format!("{stem}.d"))).ok()?;
    let mut inputs = Vec::new();
    for line in text.lines().filter(|line| !line.is_empty()) {
        let mut tokens = Vec::new();
        let mut token = String::new();
        let mut characters = line.chars();
        while let Some(character) = characters.next() {
            match character {
                '\\' => token.push(characters.next()?),
                ' ' => tokens.push(std::mem::take(&mut token)),
                _ => token.push(character),
            }
        }
        tokens.push(token);
        let mut tokens = tokens.into_iter().filter(|token| !token.is_empty());
        if !tokens.next()?.ends_with(':') {
            return None;
        }
        for input in tokens.map(PathBuf::from) {
            // `build.dep-info-basedir` makes these relative to an unknown base.
            if !input.is_absolute() {
                return None;
            }
            inputs.push(input);
        }
    }
    Some(inputs)
}

/// Run descriptor compilation, exact linking, semantic planning, and final
/// Cargo compilation for one root.
pub fn run_linked_cargo(
    request: &LinkedCargoRequest,
) -> Result<LinkedCargoOutput, LinkedCargoError> {
    validate_request(request)?;
    prepare_linked_managed_directories(request)?;
    let lease =
        run_descriptor_cargo(&request.descriptor).map_err(LinkedCargoError::DescriptorCargo)?;
    let linked = link_descriptor_transport(lease, request.invocation, &request.root)?;
    let prepared = prepare_linked_cargo(request, linked)?;
    let output = finish_prepared_linked_cargo(request, prepared)?;
    remove_successful_descriptor_staging(&request.descriptor)
        .map_err(LinkedCargoError::DescriptorStagingCleanup)?;
    Ok(output)
}

/// Run the exact linked pipeline while reusing descriptor objects admitted by
/// the explicit persistent cache.
///
/// Cargo remains the freshness authority. The cache is used only after the
/// current Cargo JSON stream authorizes unchanged artifacts, and every cached
/// sidecar/object hash is revalidated before linking.
pub fn run_linked_cargo_cached(
    request: &LinkedCargoRequest,
    cache_directory: &std::path::Path,
) -> Result<LinkedCargoOutput, LinkedCargoError> {
    run_linked_cargo_cached_with_progress(request, cache_directory, |_| {})
}

/// Successful output of an optimistic single-pass final build against an empty
/// RSJS semantic plan.
#[derive(Clone, Debug)]
pub struct OptimisticLinkedCargoOutput {
    /// Empty canonical semantic plan consumed by final Cargo.
    pub semantic: SemanticLinkPlan,
    /// Exact content-addressed semantic-plan path.
    pub semantic_plan_path: PathBuf,
    /// Plan-sensitive final Cargo output.
    pub final_cargo: FinalCargoOutput,
    /// Exact final-phase Cargo artifact attesting the selected root.
    pub final_root_artifact: CargoCompilerArtifact,
    /// Absolute local inputs Cargo recorded for the final root executable.
    pub final_root_inputs: Option<Vec<PathBuf>>,
    /// Keeps the executable snapshot from being pruned; see
    /// [`LinkedCargoOutput::final_root_lease`].
    pub final_root_lease: Option<Arc<FinalSnapshotLease>>,
}

/// Result of attempting a single-pass optimistic empty-plan dev build.
#[derive(Clone, Debug)]
#[allow(
    clippy::large_enum_variant,
    reason = "keep the public success payload inline without allocating for each development rebuild"
)]
pub enum OptimisticLinkedCargoOutcome {
    /// Single-pass final Cargo succeeded with zero unmapped RSJS macros.
    Succeeded(OptimisticLinkedCargoOutput),
    /// At least one compiled unit expanded an RSJS macro that requires the full
    /// descriptor + link + final two-pass pipeline.
    NeedsFullLinkedPass,
}

/// Attempt a single-pass final Cargo build against an empty RSJS semantic plan,
/// skipping descriptor compilation, descriptor cache validation, and transport
/// linking when no compiled unit expands an RSJS macro.
///
/// Soundness is enforced fail-closed by `rsjs_macros`: because the empty unit
/// map marks every compiled unit `RSJS_FINAL_CARGO_UNIT_STATUS=unmapped-v1`,
/// any unit that invokes `#[rsjs(...)]`, `#[client]`, or `#[derive(SharedState)]`
/// fails compilation immediately and returns `NeedsFullLinkedPass`.
pub fn try_run_optimistic_empty_linked_cargo(
    request: &LinkedCargoRequest,
) -> Result<OptimisticLinkedCargoOutcome, LinkedCargoError> {
    validate_request(request)?;
    validate_selector(&request.root)?;
    prepare_linked_managed_directories(request)?;

    let mut link_unit_seed = format!(
        "proa.rsjs.optimistic-empty-link-unit.v1\0{}\0{}\0{}",
        request.invocation, request.root.package_id, request.root.target_name,
    );
    for kind in &request.root.target_kinds {
        link_unit_seed.push('\0');
        link_unit_seed.push_str(kind);
    }
    let link_unit = LinkUnitId::derive(&link_unit_seed);
    let empty_adapted = AdaptedTransportAbi {
        components: Vec::new(),
        helpers: Vec::new(),
    };
    let semantic =
        link_semantic_plan(link_unit, &empty_adapted).map_err(LinkedCargoError::SemanticLink)?;
    let semantic_plan_path =
        write_content_addressed_semantic_plan(&request.plan_directory, &semantic)
            .map_err(LinkedCargoError::WriteSemanticPlan)?;

    let final_request = FinalCargoRequest {
        invocation: request.invocation,
        cargo: request.descriptor.cargo.clone(),
        wrapper: request.descriptor.wrapper.clone(),
        working_directory: request.descriptor.working_directory.clone(),
        source_exclusion_directory: request.descriptor.source_exclusion_directory.clone(),
        target_root: request.final_target_root.clone(),
        plan_path: semantic_plan_path.clone(),
        cargo_args: request.final_cargo_args.clone(),
        environment: request.descriptor.environment.clone(),
        root_unit_fingerprint: SemanticHash::derive(&link_unit_seed),
        descriptor_units: Vec::new(),
    };

    let final_cargo_run = match run_final_cargo_leased_optimistic(&final_request, &semantic)
        .map_err(LinkedCargoError::FinalCargo)?
    {
        OptimisticFinalCargoOutcome::NeedsFullLinkedPass => {
            return Ok(OptimisticLinkedCargoOutcome::NeedsFullLinkedPass);
        }
        OptimisticFinalCargoOutcome::Succeeded(run) => run,
    };
    let published = publish_final_root(request, final_cargo_run, None)?;

    Ok(OptimisticLinkedCargoOutcome::Succeeded(
        OptimisticLinkedCargoOutput {
            semantic,
            semantic_plan_path,
            final_cargo: published.final_cargo,
            final_root_artifact: published.final_root_artifact,
            final_root_inputs: published.final_root_inputs,
            final_root_lease: published.final_root_lease,
        },
    ))
}

struct PublishedFinalRoot {
    final_cargo: FinalCargoOutput,
    final_root_artifact: CargoCompilerArtifact,
    final_root_inputs: Option<Vec<PathBuf>>,
    final_root_lease: Option<Arc<FinalSnapshotLease>>,
}

/// Attest the selected root in a finished final Cargo run, publish it into
/// immutable snapshot storage, and run it when the request asks for that.
fn publish_final_root(
    request: &LinkedCargoRequest,
    final_cargo_run: FinalCargoRun,
    descriptor_root: Option<&CargoCompilerArtifact>,
) -> Result<PublishedFinalRoot, LinkedCargoError> {
    let final_root_artifact = attest_final_root(
        final_cargo_run.output(),
        final_cargo_run.cargo_artifacts(),
        &request.root,
        descriptor_root,
    )?;
    // Cargo writes dep-info beside the artifact in the reusable target, not
    // beside the snapshot. Read it while the target lease is still held.
    let final_root_inputs = final_root_artifact
        .executable
        .as_deref()
        .filter(|_| final_cargo_run.local_scripts_declare_inputs)
        .and_then(cargo_dep_info_inputs);
    let (final_root_artifact, final_root_lease) = snapshot_final_artifact(
        &request.descriptor.source_exclusion_directory,
        &request.final_target_root.join(FINAL_SNAPSHOT_ROOT_NAME),
        &final_cargo_run.output().target_directory,
        &final_root_artifact,
    )
    .map_err(LinkedCargoError::FinalCargo)?;
    let final_cargo = final_cargo_run.into_output();
    // The selected root now points only at immutable content-addressed files,
    // so long-running programs never retain the reusable target lease and a
    // later build cannot replace the artifact between attestation and spawn.
    execute_requested_final_root(request, &final_root_artifact)?;
    Ok(PublishedFinalRoot {
        final_cargo,
        final_root_artifact,
        final_root_inputs,
        final_root_lease: final_root_lease.map(Arc::new),
    })
}

pub enum LinkedCargoStage {
    Descriptor,
    Link,
    Final,
}

pub fn run_linked_cargo_cached_with_progress(
    request: &LinkedCargoRequest,
    cache_directory: &Path,
    mut progress: impl FnMut(LinkedCargoStage),
) -> Result<LinkedCargoOutput, LinkedCargoError> {
    let managed = validate_request(request)?;
    validate_cache_against_linked_paths(cache_directory, &managed)?;
    prepare_linked_managed_directories(request)?;
    progress(LinkedCargoStage::Descriptor);
    let lease = run_descriptor_cargo_cached(&request.descriptor, cache_directory)
        .map_err(LinkedCargoError::DescriptorCache)?;
    progress(LinkedCargoStage::Link);
    let linked = link_descriptor_transport(lease, request.invocation, &request.root)?;
    let prepared = prepare_linked_cargo(request, linked)?;
    progress(LinkedCargoStage::Final);
    finish_prepared_linked_cargo(request, prepared)
}

fn validate_cache_against_linked_paths(
    cache_directory: &Path,
    managed: &ValidatedLinkedManagedPaths,
) -> Result<(), LinkedCargoError> {
    let cache = normalize_linked_managed_path("descriptor cache", cache_directory)?;
    for (kind, path) in [
        ("semantic plans", &managed.plan),
        ("final targets", &managed.final_target),
    ] {
        if managed_paths_overlap(&cache, path) {
            return Err(LinkedCargoError::ManagedDirectoryOverlap {
                first_kind: "descriptor cache",
                first: cache.clone(),
                second_kind: kind,
                second: path.clone(),
            });
        }
    }
    Ok(())
}

struct PreparedLinkedCargo {
    descriptor: DescriptorCargoReport,
    selected: SelectedDescriptorRoot,
    transport: TransportLinkPlan,
    adapted: AdaptedTransportAbi,
    semantic: SemanticLinkPlan,
    semantic_plan_path: PathBuf,
    final_descriptor_units: Vec<ValidatedDescriptorUnit>,
}

/// Descriptor artifacts fully hashed and transport-linked while their target
/// and optional cache generation remained exclusively leased.
#[derive(Debug)]
pub struct LinkedDescriptorTransport {
    /// Path-free descriptor diagnostics.
    pub descriptor: DescriptorCargoReport,
    /// Exact selected descriptor unit.
    pub root_unit: DescriptorCargoUnitId,
    /// Relocation-resolved transport graph, independent of target paths.
    pub transport: TransportLinkPlan,
    selected: SelectedDescriptorRoot,
    final_descriptor_units: Vec<ValidatedDescriptorUnit>,
}

/// Consume a cached or uncached descriptor run and materialize every mutable
/// target byte needed by the transport linker before releasing its leases.
pub fn link_descriptor_transport<R: DescriptorCargoRun>(
    run: R,
    invocation: InvocationId,
    selector: &DescriptorRootSelector,
) -> Result<LinkedDescriptorTransport, LinkedCargoError> {
    let mut timing = super::timing::StageTimer::new();
    let linked = {
        let descriptor = descriptor_run_sealed::Sealed::output(&run);
        let selected = select_descriptor_root(descriptor, selector)?;
        let manifest = build_link_unit_manifest(
            invocation,
            selected.unit,
            &selected.artifact,
            selector.role,
            descriptor,
        )
        .map_err(LinkedCargoError::LinkManifest)?;
        timing.mark("transport manifest and root selection");
        let transport = link_transport_manifest(&manifest, &descriptor.units, &descriptor.objects)
            .map_err(LinkedCargoError::TransportLink)?;
        timing.mark("transport graph");
        let cargo_enumerated_units =
            join_cargo_enumerated_descriptor_units(&descriptor.units, &descriptor.cargo_artifacts)
                .map_err(LinkedCargoError::JoinDescriptorArtifacts)?;
        let final_descriptor_units = descriptor
            .units
            .iter()
            .filter(|unit| cargo_enumerated_units.contains_key(&unit.unit))
            .cloned()
            .collect();

        LinkedDescriptorTransport {
            descriptor: DescriptorCargoReport::from_output(descriptor),
            root_unit: selected.unit,
            transport,
            selected,
            final_descriptor_units,
        }
    };

    // `linked` owns only extracted/path-free material plus private final-map
    // inputs. Releasing the lease here keeps semantic-plan writes and final
    // Cargo outside both descriptor and cache critical sections.
    drop(descriptor_run_sealed::Sealed::into_output(run));
    timing.mark("transport final-unit selection");
    Ok(linked)
}

fn prepare_linked_cargo(
    request: &LinkedCargoRequest,
    linked: LinkedDescriptorTransport,
) -> Result<PreparedLinkedCargo, LinkedCargoError> {
    let LinkedDescriptorTransport {
        descriptor,
        selected,
        transport,
        final_descriptor_units,
        ..
    } = linked;
    let mut timing = super::timing::StageTimer::new();
    let abi = AbiAdapterContext::from_transport_plan(
        request.producer,
        request.runtime_protocol,
        &transport,
    )
    .map_err(LinkedCargoError::AbiAdapter)?;
    let adapted = adapt_transport_plan(&abi, &transport).map_err(LinkedCargoError::AbiAdapter)?;
    timing.mark("ABI adaptation");
    let semantic = link_semantic_plan(transport.link_unit, &adapted)
        .map_err(LinkedCargoError::SemanticLink)?;
    timing.mark("semantic planning");
    let semantic_plan_path =
        write_content_addressed_semantic_plan(&request.plan_directory, &semantic)
            .map_err(LinkedCargoError::WriteSemanticPlan)?;
    timing.mark("semantic plan publication");
    Ok(PreparedLinkedCargo {
        descriptor,
        selected,
        transport,
        adapted,
        semantic,
        semantic_plan_path,
        final_descriptor_units,
    })
}

fn finish_prepared_linked_cargo(
    request: &LinkedCargoRequest,
    prepared: PreparedLinkedCargo,
) -> Result<LinkedCargoOutput, LinkedCargoError> {
    let PreparedLinkedCargo {
        descriptor,
        selected,
        transport,
        adapted,
        semantic,
        semantic_plan_path,
        final_descriptor_units,
    } = prepared;

    let final_request = FinalCargoRequest {
        invocation: request.invocation,
        cargo: request.descriptor.cargo.clone(),
        wrapper: request.descriptor.wrapper.clone(),
        working_directory: request.descriptor.working_directory.clone(),
        source_exclusion_directory: request.descriptor.source_exclusion_directory.clone(),
        target_root: request.final_target_root.clone(),
        plan_path: semantic_plan_path.clone(),
        cargo_args: request.final_cargo_args.clone(),
        // validate_request proves both phase maps are byte-for-byte equal;
        // keep one frozen source of truth for all caller-supplied variables.
        environment: request.descriptor.environment.clone(),
        root_unit_fingerprint: SemanticHash::derive(&selected.unit.as_abi_id()),
        descriptor_units: final_descriptor_units,
    };
    let final_cargo_run =
        run_final_cargo_leased(&final_request, &semantic).map_err(LinkedCargoError::FinalCargo)?;
    let published = publish_final_root(request, final_cargo_run, Some(&selected.cargo_artifact))?;

    Ok(LinkedCargoOutput {
        descriptor,
        root_unit: selected.unit,
        transport,
        adapted,
        semantic,
        semantic_plan_path,
        final_cargo: published.final_cargo,
        final_root_artifact: published.final_root_artifact,
        final_root_inputs: published.final_root_inputs,
        final_root_lease: published.final_root_lease,
    })
}

#[derive(Clone, Debug)]
struct SelectedDescriptorRoot {
    unit: DescriptorCargoUnitId,
    artifact: PathBuf,
    cargo_artifact: CargoCompilerArtifact,
}

fn select_descriptor_root(
    output: &DescriptorCargoOutput,
    selector: &DescriptorRootSelector,
) -> Result<SelectedDescriptorRoot, LinkedCargoError> {
    validate_selector(selector)?;
    let joined = join_cargo_enumerated_descriptor_units(&output.units, &output.cargo_artifacts)
        .map_err(LinkedCargoError::JoinDescriptorArtifacts)?;
    let mut matches = joined
        .into_iter()
        .filter(|(_, artifact)| root_artifact_matches(artifact, selector))
        .collect::<Vec<_>>();
    matches.sort_by(|left, right| left.0.as_bytes().cmp(right.0.as_bytes()));

    let (unit, artifact) = match matches.as_slice() {
        [] => {
            return Err(LinkedCargoError::MissingRoot {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
            });
        }
        [(unit, artifact)] => (*unit, artifact),
        _ => {
            return Err(LinkedCargoError::AmbiguousRoot {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
                matches: matches.len(),
            });
        }
    };
    let artifact_path = select_root_path(artifact, selector)?;
    Ok(SelectedDescriptorRoot {
        unit,
        artifact: artifact_path,
        cargo_artifact: artifact.clone(),
    })
}

fn root_artifact_matches(
    artifact: &CargoCompilerArtifact,
    selector: &DescriptorRootSelector,
) -> bool {
    artifact.package_id == selector.package_id
        && artifact.target.name == selector.target_name
        && artifact.target.kind == selector.target_kinds
}

fn select_root_path(
    artifact: &CargoCompilerArtifact,
    selector: &DescriptorRootSelector,
) -> Result<PathBuf, LinkedCargoError> {
    if let Some(requested) = &selector.artifact_path {
        if !requested.is_absolute() {
            return Err(LinkedCargoError::RelativeRootArtifact(requested.clone()));
        }
        if artifact.executable.as_ref() == Some(requested) || artifact.filenames.contains(requested)
        {
            return Ok(requested.clone());
        }
        return Err(LinkedCargoError::RootArtifactNotEnumerated(
            requested.clone(),
        ));
    }

    // Cargo's executable field is authoritative. MSVC also enumerates a PDB,
    // which is a debug companion rather than a second possible root.
    if let Some(executable) = &artifact.executable {
        return Ok(executable.clone());
    }
    let candidates = artifact
        .filenames
        .iter()
        .filter(|path| {
            !path
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("pdb"))
        })
        .cloned()
        .collect::<BTreeSet<_>>();
    match candidates.len() {
        0 => Err(LinkedCargoError::RootHasNoArtifact),
        1 => Ok(candidates
            .into_iter()
            .next()
            .expect("one candidate was counted")),
        count => Err(LinkedCargoError::AmbiguousRootArtifact { matches: count }),
    }
}

/// Select the requested root among final Cargo artifacts.
///
/// With a descriptor root (the two-pass pipeline), the final root must keep
/// the descriptor root's exact Cargo coordinate. The optimistic single pass
/// has no descriptor root to compare against.
fn attest_final_root(
    output: &FinalCargoOutput,
    cargo_artifacts: &[CargoCompilerArtifact],
    selector: &DescriptorRootSelector,
    descriptor_root: Option<&CargoCompilerArtifact>,
) -> Result<CargoCompilerArtifact, LinkedCargoError> {
    let mut matches = cargo_artifacts
        .iter()
        .filter(|artifact| root_artifact_matches(artifact, selector))
        .collect::<Vec<_>>();
    matches.sort_by(|left, right| {
        left.manifest_path
            .cmp(&right.manifest_path)
            .then_with(|| left.target.src_path.cmp(&right.target.src_path))
    });
    let final_root = match matches.as_slice() {
        [] => {
            return Err(LinkedCargoError::MissingFinalRoot {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
            });
        }
        [artifact] => *artifact,
        artifacts => {
            return Err(LinkedCargoError::AmbiguousFinalRoot {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
                matches: artifacts.len(),
            });
        }
    };

    if let Some(descriptor_root) = descriptor_root {
        if final_root.manifest_path != descriptor_root.manifest_path
            || final_root.target != descriptor_root.target
            || final_root.profile != descriptor_root.profile
            || final_root.features != descriptor_root.features
        {
            return Err(LinkedCargoError::FinalRootCoordinateMismatch {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
            });
        }
    }

    let expects_executable = descriptor_root.map_or(final_root.executable.is_some(), |root| {
        root.executable.is_some()
    });
    let materialized = match (expects_executable, final_root.executable.as_ref()) {
        (true, Some(executable)) => executable,
        (true, None) => {
            return Err(LinkedCargoError::MissingFinalRootExecutable {
                package_id: selector.package_id.clone(),
                target_name: selector.target_name.clone(),
            });
        }
        (false, _) => final_root
            .filenames
            .iter()
            .next()
            .ok_or(LinkedCargoError::FinalRootHasNoArtifact)?,
    };
    ensure_plain_managed_file(&output.target_directory, materialized)
        .map_err(LinkedCargoError::ManagedPath)?;
    let metadata = fs::symlink_metadata(materialized).map_err(|source| {
        LinkedCargoError::InspectFinalRootArtifact {
            path: materialized.clone(),
            source,
        }
    })?;
    if !metadata.file_type().is_file() {
        return Err(LinkedCargoError::FinalRootArtifactNotFile(
            materialized.clone(),
        ));
    }

    Ok(final_root.clone())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FinalExecution<'a> {
    None,
    Run(&'a [OsString]),
    Test(&'a [OsString]),
}

fn requested_final_execution(arguments: &[OsString]) -> FinalExecution<'_> {
    let (compile_arguments, runtime_arguments) = split_cargo_runtime_arguments(arguments);
    let runtime_arguments = runtime_arguments.unwrap_or_default();
    match compile_arguments.first().map(OsString::as_os_str) {
        Some(subcommand) if subcommand == OsStr::new("run") => {
            FinalExecution::Run(runtime_arguments)
        }
        Some(subcommand) if subcommand == OsStr::new("test") => {
            if compile_arguments.iter().any(|arg| arg == "--no-run") {
                FinalExecution::None
            } else {
                FinalExecution::Test(runtime_arguments)
            }
        }
        _ => FinalExecution::None,
    }
}

fn execute_requested_final_root(
    request: &LinkedCargoRequest,
    artifact: &CargoCompilerArtifact,
) -> Result<(), LinkedCargoError> {
    let execution = requested_final_execution(&request.final_cargo_args);
    let (runtime_arguments, working_directory) = match execution {
        FinalExecution::None => return Ok(()),
        FinalExecution::Run(arguments) => {
            (arguments, request.descriptor.working_directory.as_path())
        }
        FinalExecution::Test(arguments) => {
            let working_directory = artifact.manifest_path.parent().ok_or_else(|| {
                LinkedCargoError::FinalRootManifestWithoutParent(artifact.manifest_path.clone())
            })?;
            (arguments, working_directory)
        }
    };
    let executable = artifact.executable.as_ref().ok_or_else(|| {
        LinkedCargoError::FinalRootNotHostExecutable {
            package_id: artifact.package_id.clone(),
            target_name: artifact.target.name.clone(),
        }
    })?;

    let status = Command::new(executable)
        .current_dir(working_directory)
        .args(runtime_arguments)
        .envs(&request.final_environment)
        // `status` inherits the caller's raw stdin/stdout/stderr. The direct
        // child also inherits the normal local environment; only explicit
        // request variables override it, matching the Cargo invocation.
        .status()
        .map_err(|source| LinkedCargoError::ExecuteFinalRoot {
            path: executable.clone(),
            source,
        })?;
    if !status.success() {
        return Err(LinkedCargoError::FinalRootExited {
            path: executable.clone(),
            status,
        });
    }
    Ok(())
}

fn validate_phase_cargo_arguments(
    descriptor: &[OsString],
    final_args: &[OsString],
) -> Result<(), LinkedCargoError> {
    let (descriptor_compile, descriptor_runtime) = split_cargo_runtime_arguments(descriptor);
    if descriptor_runtime.is_some() {
        return Err(LinkedCargoError::DescriptorRuntimeArguments);
    }
    let (final_compile, final_runtime) = split_cargo_runtime_arguments(final_args);
    let descriptor_subcommand = descriptor_compile
        .first()
        .ok_or(LinkedCargoError::MissingDescriptorCargoArguments)?;
    let final_subcommand = final_compile
        .first()
        .ok_or(LinkedCargoError::MissingFinalCargoArguments)?;

    let supported_pair = (
        descriptor_subcommand.as_os_str(),
        final_subcommand.as_os_str(),
    );
    if !matches!(
        supported_pair,
        (descriptor, final_phase)
            if (descriptor == OsStr::new("build")
                && (final_phase == OsStr::new("build")
                    || final_phase == OsStr::new("run")))
                || (descriptor == OsStr::new("check")
                    && final_phase == OsStr::new("check"))
                || (descriptor == OsStr::new("test")
                    && final_phase == OsStr::new("test"))
    ) {
        return Err(LinkedCargoError::UnsupportedPhaseSubcommands {
            descriptor: descriptor_subcommand.clone(),
            final_phase: final_subcommand.clone(),
        });
    }
    if final_runtime.is_some()
        && final_subcommand != OsStr::new("run")
        && final_subcommand != OsStr::new("test")
    {
        return Err(LinkedCargoError::UnsupportedFinalRuntimeArguments(
            final_subcommand.clone(),
        ));
    }

    let mut normalized_descriptor = descriptor_compile.to_vec();
    let mut normalized_final = final_compile.to_vec();
    normalized_descriptor[0] = OsString::from("<linked-phase>");
    normalized_final[0] = OsString::from("<linked-phase>");

    let descriptor_len = normalized_descriptor.len();
    normalized_descriptor.retain(|argument| argument != "--no-run");
    let descriptor_no_run = descriptor_len - normalized_descriptor.len();
    let final_len = normalized_final.len();
    normalized_final.retain(|argument| argument != "--no-run");
    let final_no_run = final_len - normalized_final.len();
    if descriptor_subcommand == OsStr::new("test") {
        if descriptor_no_run != 1
            || final_no_run > 1
            || (final_no_run == 1 && final_runtime.is_some())
        {
            return Err(LinkedCargoError::InvalidTestPhaseNoRun);
        }
    } else if descriptor_no_run != 0 || final_no_run != 0 {
        return Err(LinkedCargoError::InvalidTestPhaseNoRun);
    }

    if normalized_descriptor != normalized_final {
        return Err(LinkedCargoError::PhaseCargoArgumentsMismatch {
            descriptor: normalized_descriptor,
            final_phase: normalized_final,
        });
    }
    Ok(())
}

fn split_cargo_runtime_arguments(arguments: &[OsString]) -> (&[OsString], Option<&[OsString]>) {
    match arguments
        .iter()
        .position(|argument| argument == OsStr::new("--"))
    {
        Some(index) => (&arguments[..index], Some(&arguments[index + 1..])),
        None => (arguments, None),
    }
}

pub(crate) struct ValidatedLinkedManagedPaths {
    plan: PathBuf,
    final_target: PathBuf,
}

/// Check managed-path and invocation constraints without starting a build.
pub fn validate_linked_cargo_request(request: &LinkedCargoRequest) -> Result<(), LinkedCargoError> {
    validate_request(request).map(|_| ())
}

pub(crate) fn validate_request(
    request: &LinkedCargoRequest,
) -> Result<ValidatedLinkedManagedPaths, LinkedCargoError> {
    if !request.plan_directory.is_absolute() {
        return Err(LinkedCargoError::RelativePlanDirectory(
            request.plan_directory.clone(),
        ));
    }
    if !request.final_target_root.is_absolute() {
        return Err(LinkedCargoError::RelativeFinalTargetRoot(
            request.final_target_root.clone(),
        ));
    }
    if request.final_cargo_args.is_empty() {
        return Err(LinkedCargoError::MissingFinalCargoArguments);
    }
    validate_phase_cargo_arguments(&request.descriptor.cargo_args, &request.final_cargo_args)?;
    if request.descriptor.environment != request.final_environment {
        let names = request
            .descriptor
            .environment
            .keys()
            .chain(request.final_environment.keys())
            .collect::<BTreeSet<_>>()
            .into_iter()
            .filter(|name| {
                request.descriptor.environment.get(*name) != request.final_environment.get(*name)
            })
            .cloned()
            .collect();
        return Err(LinkedCargoError::PhaseEnvironmentMismatch { names });
    }
    let descriptor = validate_descriptor_managed_paths(&request.descriptor)
        .map_err(LinkedCargoError::DescriptorManagedPaths)?;
    let plan = normalize_linked_managed_path("semantic plans", &request.plan_directory)?;
    let final_target = normalize_linked_managed_path("final targets", &request.final_target_root)?;
    let managed_roots = [
        ("descriptor staging", &descriptor.staging),
        ("descriptor target", &descriptor.target),
        ("semantic plans", &plan),
        ("final targets", &final_target),
    ];
    for (index, (first_kind, first)) in managed_roots.iter().enumerate() {
        for (second_kind, second) in &managed_roots[index + 1..] {
            if managed_paths_overlap(first, second) {
                return Err(LinkedCargoError::ManagedDirectoryOverlap {
                    first_kind,
                    first: (*first).clone(),
                    second_kind,
                    second: (*second).clone(),
                });
            }
        }
    }
    Ok(ValidatedLinkedManagedPaths { plan, final_target })
}

fn prepare_linked_managed_directories(
    request: &LinkedCargoRequest,
) -> Result<(), LinkedCargoError> {
    ensure_plain_managed_directory(
        &request.descriptor.source_exclusion_directory,
        &request.plan_directory,
    )
    .map_err(LinkedCargoError::ManagedPath)?;
    ensure_plain_managed_directory(
        &request.descriptor.source_exclusion_directory,
        &request.final_target_root,
    )
    .map_err(LinkedCargoError::ManagedPath)?;
    Ok(())
}

fn normalize_linked_managed_path(
    kind: &'static str,
    path: &Path,
) -> Result<PathBuf, LinkedCargoError> {
    normalize_managed_path_identity(path).map_err(|source| {
        LinkedCargoError::NormalizeManagedDirectory {
            kind,
            path: path.to_path_buf(),
            source,
        }
    })
}

fn validate_selector(selector: &DescriptorRootSelector) -> Result<(), LinkedCargoError> {
    if selector.package_id.is_empty() {
        return Err(LinkedCargoError::EmptyRootSelector("package_id"));
    }
    if selector.target_name.is_empty() {
        return Err(LinkedCargoError::EmptyRootSelector("target_name"));
    }
    if selector.target_kinds.is_empty() || selector.target_kinds.iter().any(String::is_empty) {
        return Err(LinkedCargoError::EmptyRootSelector("target_kinds"));
    }
    if !selector.role.is_root() {
        return Err(LinkedCargoError::NonRootRole(selector.role));
    }
    Ok(())
}

/// End-to-end orchestration failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum LinkedCargoError {
    /// Descriptor Cargo must receive an explicit subcommand/selection too.
    #[error("RSJS descriptor Cargo arguments are empty")]
    MissingDescriptorCargoArguments,
    /// Plan storage must be cwd-independent.
    #[error("RSJS semantic-plan directory must be absolute: `{0}`")]
    RelativePlanDirectory(PathBuf),
    /// Final artifacts live in an invocation- and wrapper-policy-scoped
    /// absolute namespace.
    #[error("RSJS final target root must be absolute: `{0}`")]
    RelativeFinalTargetRoot(PathBuf),
    /// Final Cargo must receive an explicit subcommand/selection.
    #[error("RSJS final Cargo arguments are empty")]
    MissingFinalCargoArguments,
    /// Descriptor compilation may never execute a selected program.
    #[error("descriptor Cargo arguments may not contain a runtime `-- ...` suffix")]
    DescriptorRuntimeArguments,
    /// Only the lifecycle's known phase pairs preserve one Cargo unit model.
    #[error(
        "unsupported linked Cargo phase pair: descriptor {descriptor:?}, final {final_phase:?}"
    )]
    UnsupportedPhaseSubcommands {
        /// Descriptor-pass Cargo subcommand.
        descriptor: OsString,
        /// Final-pass Cargo subcommand.
        final_phase: OsString,
    },
    /// Runtime arguments are meaningful only for final run/test invocations.
    #[error("final Cargo subcommand {0:?} may not contain runtime arguments after `--`")]
    UnsupportedFinalRuntimeArguments(OsString),
    /// Tests compile without execution in the descriptor phase. The final
    /// phase may return a harness for a caller to launch with runtime setup.
    #[error(
        "`--no-run` is required exactly once for the descriptor test pass and is allowed once for a final test pass without harness arguments"
    )]
    InvalidTestPhaseNoRun,
    /// After the controlled phase rewrite, every Cargo selection/config input
    /// must be byte-for-byte identical.
    #[error(
        "descriptor and final Cargo selection/config arguments diverge after phase normalization: descriptor {descriptor:?}, final {final_phase:?}"
    )]
    PhaseCargoArgumentsMismatch {
        /// Normalized descriptor arguments.
        descriptor: Vec<OsString>,
        /// Normalized final arguments.
        final_phase: Vec<OsString>,
    },
    /// Caller-supplied compilation environment must be frozen across phases.
    #[error(
        "descriptor and final Cargo environments differ for variable names {names:?}; use one identical environment map for both phases"
    )]
    PhaseEnvironmentMismatch {
        /// Names only; potentially secret values are never included.
        names: Vec<OsString>,
    },
    /// Every generated namespace is a separate identity/deletion boundary.
    #[error(
        "RSJS managed {first_kind} directory `{first}` overlaps {second_kind} directory `{second}`"
    )]
    ManagedDirectoryOverlap {
        /// First managed namespace role.
        first_kind: &'static str,
        /// First managed namespace root.
        first: PathBuf,
        /// Second managed namespace role.
        second_kind: &'static str,
        /// Second managed namespace root.
        second: PathBuf,
    },
    /// Managed output confinement or plain-entry validation failed.
    #[error(transparent)]
    ManagedPath(#[from] ManagedPathError),
    /// Descriptor path relationships must be validated before any linked
    /// namespace is created.
    #[error("invalid descriptor managed paths: {0}")]
    DescriptorManagedPaths(#[source] DescriptorCargoRunError),
    /// Cross-subsystem comparisons use one canonical managed-path identity.
    #[error("failed to normalize RSJS managed {kind} directory `{path}`: {source}")]
    NormalizeManagedDirectory {
        /// Managed namespace role.
        kind: &'static str,
        /// Caller-supplied path.
        path: PathBuf,
        /// Canonicalization failure.
        #[source]
        source: std::io::Error,
    },
    /// Root selection fields are exact and nonempty.
    #[error("RSJS root selector field `{0}` must not be empty")]
    EmptyRootSelector(&'static str),
    /// A dependency role cannot be selected as a root.
    #[error("RSJS root selector uses non-root artifact role {0:?}")]
    NonRootRole(ArtifactRole),
    /// Descriptor Cargo failed.
    #[error("RSJS descriptor compilation failed: {0}")]
    DescriptorCargo(#[source] DescriptorCargoRunError),
    /// A fully successful uncached run could not remove only its exact,
    /// marker-owned invocation staging tree.
    #[error("failed to clean successful RSJS descriptor staging: {0}")]
    DescriptorStagingCleanup(#[source] DescriptorCargoRunError),
    /// Persistent descriptor reuse failed closed.
    #[error("RSJS descriptor cache validation failed: {0}")]
    DescriptorCache(#[source] DescriptorCacheError),
    /// Wrapper sidecars could not be joined to this invocation's Cargo
    /// messages.
    #[error("failed to join RSJS descriptor units to Cargo artifacts: {0}")]
    JoinDescriptorArtifacts(#[source] UnitArtifactJoinError),
    /// The exact selected Cargo root did not exist.
    #[error(
        "descriptor Cargo emitted no exact root for package `{package_id}` target `{target_name}`"
    )]
    MissingRoot {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
    },
    /// More than one unit matched an exact root selector.
    #[error(
        "descriptor Cargo emitted {matches} roots for package `{package_id}` target `{target_name}`"
    )]
    AmbiguousRoot {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
        /// Candidate count.
        matches: usize,
    },
    /// Final Cargo must emit the exact root selected from descriptor Cargo.
    #[error(
        "final Cargo emitted no exact root for descriptor package `{package_id}` target `{target_name}`"
    )]
    MissingFinalRoot {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
    },
    /// One exact root selection must remain unique in the final phase.
    #[error(
        "final Cargo emitted {matches} exact roots for descriptor package `{package_id}` target `{target_name}`"
    )]
    AmbiguousFinalRoot {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
        /// Candidate count.
        matches: usize,
    },
    /// Profile, features, manifest, and target metadata are part of root
    /// identity across phases.
    #[error(
        "final Cargo root coordinate differs from descriptor root for package `{package_id}` target `{target_name}`"
    )]
    FinalRootCoordinateMismatch {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
    },
    /// Executable roots must remain executable roots in the final phase.
    #[error(
        "final Cargo root for package `{package_id}` target `{target_name}` has no executable"
    )]
    MissingFinalRootExecutable {
        /// Exact package ID.
        package_id: String,
        /// Exact target name.
        target_name: String,
    },
    /// A final check root still needs one Cargo-enumerated materialized file.
    #[error("selected final RSJS root has no Cargo-enumerated artifact")]
    FinalRootHasNoArtifact,
    /// Final root output inspection failed.
    #[error("failed to inspect selected final root artifact `{path}`: {source}")]
    InspectFinalRootArtifact {
        /// Cargo-enumerated artifact path.
        path: PathBuf,
        /// Filesystem failure.
        #[source]
        source: std::io::Error,
    },
    /// Cargo-enumerated final root material must be an ordinary file.
    #[error("selected final root artifact is not a plain regular file: `{0}`")]
    FinalRootArtifactNotFile(PathBuf),
    /// Run/test requests require a directly host-executable attested root.
    #[error(
        "attested final root for package `{package_id}` target `{target_name}` is not directly executable on this host"
    )]
    FinalRootNotHostExecutable {
        /// Exact Cargo package ID.
        package_id: String,
        /// Exact Cargo target name.
        target_name: String,
    },
    /// Cargo manifest paths must identify the test package directory.
    #[error("attested final root manifest has no parent directory: `{0}`")]
    FinalRootManifestWithoutParent(PathBuf),
    /// The attested executable could not be launched directly.
    #[error(
        "failed to execute attested final root `{path}` directly on this host: {source}; cargo-proa will not rerun Cargo target selection"
    )]
    ExecuteFinalRoot {
        /// Attested executable or test harness.
        path: PathBuf,
        /// Host spawn failure.
        #[source]
        source: std::io::Error,
    },
    /// User programs and test harnesses propagate a nonzero result.
    #[error("attested final root `{path}` exited unsuccessfully with {status}")]
    FinalRootExited {
        /// Attested executable or test harness.
        path: PathBuf,
        /// Exact host exit status.
        status: ExitStatus,
    },
    /// Caller-supplied artifact paths must be exact absolute Cargo paths.
    #[error("selected RSJS root artifact must be absolute: `{0}`")]
    RelativeRootArtifact(PathBuf),
    /// Caller-supplied root path was not in the matching Cargo message.
    #[error("selected RSJS root artifact was not enumerated by Cargo: `{0}`")]
    RootArtifactNotEnumerated(PathBuf),
    /// Cargo published no usable root artifact.
    #[error("selected RSJS root has no Cargo-enumerated artifact")]
    RootHasNoArtifact,
    /// Automatic root-filename selection is intentionally fail-closed.
    #[error(
        "selected RSJS root has {matches} Cargo-enumerated filenames; supply `artifact_path` exactly"
    )]
    AmbiguousRootArtifact {
        /// Candidate count.
        matches: usize,
    },
    /// Exact external root graph assembly failed.
    #[error("failed to assemble RSJS link manifest: {0}")]
    LinkManifest(#[source] LinkManifestAssemblyError),
    /// Object extraction/relocation resolution failed.
    #[error("failed to resolve RSJS transport records: {0}")]
    TransportLink(#[source] TransportLinkError),
    /// Legacy producer data could not become canonical ABI.
    #[error("failed to adapt RSJS descriptors: {0}")]
    AbiAdapter(#[source] AbiAdapterError),
    /// Canonical graph/owner linking failed.
    #[error("failed to link canonical RSJS plan: {0}")]
    SemanticLink(#[source] SemanticLinkError),
    /// Semantic plan persistence failed.
    #[error("failed to persist canonical RSJS plan: {0}")]
    WriteSemanticPlan(#[source] SemanticPlanWriteError),
    /// Plan-sensitive final compilation failed.
    #[error("RSJS final compilation failed")]
    FinalCargo(#[source] FinalCargoError),
}

#[cfg(test)]
mod tests;