Skip to main content

proa_build/
pipeline.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! End-to-end orchestration for one exact RSJS Cargo root.
5//!
6//! This module is deliberately small glue over the independently tested
7//! descriptor runner, exact-artifact transport linker, canonical semantic
8//! linker, and plan-sensitive final runner. It does not discover artifacts in
9//! a target directory or infer a root from a source path. The caller supplies
10//! one exact Cargo artifact selector, and every later identity comes from
11//! Cargo messages, validated wrapper sidecars, or rustc relocations.
12
13use std::collections::{BTreeMap, BTreeSet};
14use std::ffi::{OsStr, OsString};
15use std::fs;
16use std::path::{Path, PathBuf};
17use std::process::{Command, ExitStatus};
18use std::sync::Arc;
19
20use rsjs_ir::abi::{AbiVersion, InvocationId, LinkUnitId, ProducerVersion, SemanticHash};
21use rsjs_ir::build::ArtifactRole;
22use thiserror::Error;
23
24use crate::abi_adapter::{
25    adapt_transport_plan, AbiAdapterContext, AbiAdapterError, AdaptedTransportAbi,
26};
27use crate::build::{
28    build_link_unit_manifest, descriptor_run_sealed, join_cargo_enumerated_descriptor_units,
29    managed_paths_overlap, normalize_managed_path_identity, remove_successful_descriptor_staging,
30    run_descriptor_cargo, validate_descriptor_managed_paths, CargoCompilerArtifact,
31    DescriptorCargoOutput, DescriptorCargoReport, DescriptorCargoRequest, DescriptorCargoRun,
32    DescriptorCargoRunError, DescriptorCargoUnitId, LinkManifestAssemblyError,
33    UnitArtifactJoinError, ValidatedDescriptorUnit,
34};
35use crate::cache::{run_descriptor_cargo_cached, DescriptorCacheError};
36#[cfg(test)]
37use crate::final_compile::FinalCargoArtifactReport;
38use crate::final_compile::{
39    ensure_plain_managed_directory, ensure_plain_managed_file, run_final_cargo_leased,
40    run_final_cargo_leased_optimistic, snapshot_final_artifact, FinalCargoError, FinalCargoOutput,
41    FinalCargoRequest, FinalCargoRun, FinalSnapshotLease, ManagedPathError,
42    OptimisticFinalCargoOutcome, FINAL_SNAPSHOT_ROOT_NAME,
43};
44use crate::link::{link_transport_manifest, TransportLinkError, TransportLinkPlan};
45use crate::semantic_link::{
46    link_semantic_plan, write_content_addressed_semantic_plan, SemanticLinkError, SemanticLinkPlan,
47    SemanticPlanWriteError,
48};
49
50/// Exact Cargo root selected from the descriptor invocation's JSON messages.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct DescriptorRootSelector {
53    /// Exact Cargo package ID from a `compiler-artifact` message.
54    pub package_id: String,
55    /// Exact target name.
56    pub target_name: String,
57    /// Exact normalized Cargo target-kind set.
58    pub target_kinds: BTreeSet<String>,
59    /// Link-manifest role for this selected root.
60    pub role: ArtifactRole,
61    /// Exact Cargo-enumerated root filename.
62    ///
63    /// This may be omitted only when Cargo reported exactly one usable
64    /// executable or filename for the selected artifact.
65    pub artifact_path: Option<PathBuf>,
66}
67
68/// One complete descriptor, link, and final-Cargo request.
69#[derive(Clone, Debug)]
70pub struct LinkedCargoRequest {
71    /// Exact descriptor-pass Cargo request.
72    pub descriptor: DescriptorCargoRequest,
73    /// Root selector applied only to that invocation's Cargo JSON messages.
74    pub root: DescriptorRootSelector,
75    /// Pre-Cargo invocation identity.
76    pub invocation: InvocationId,
77    /// Compiler producer version recorded in canonical descriptor envelopes.
78    pub producer: ProducerVersion,
79    /// Runtime protocol selected for canonical compatibility checks.
80    pub runtime_protocol: AbiVersion,
81    /// Absolute content-addressed semantic-plan directory.
82    pub plan_directory: PathBuf,
83    /// Absolute parent for invocation- and wrapper-policy-scoped final target
84    /// directories.
85    pub final_target_root: PathBuf,
86    /// Cargo arguments for final compilation, without runner-owned
87    /// `--message-format` or `--target-dir`.
88    /// A final `test --no-run` returns the attested harness without launching it.
89    pub final_cargo_args: Vec<OsString>,
90    /// Exact additional environment for final Cargo.
91    pub final_environment: BTreeMap<OsString, OsString>,
92}
93
94/// Successful output of every stage for one selected root.
95#[derive(Clone, Debug)]
96pub struct LinkedCargoOutput {
97    /// Path-free descriptor Cargo diagnostics.
98    pub descriptor: DescriptorCargoReport,
99    /// Exact selected descriptor unit.
100    pub root_unit: DescriptorCargoUnitId,
101    /// Relocation-resolved transport graph.
102    pub transport: TransportLinkPlan,
103    /// Canonical descriptors produced by the compatibility bridge.
104    pub adapted: AdaptedTransportAbi,
105    /// Canonical semantic owner/helper plan.
106    pub semantic: SemanticLinkPlan,
107    /// Exact content-addressed semantic-plan path.
108    pub semantic_plan_path: PathBuf,
109    /// Plan-sensitive final Cargo output.
110    pub final_cargo: FinalCargoOutput,
111    /// Exact final-phase Cargo artifact attesting the selected descriptor root.
112    pub final_root_artifact: CargoCompilerArtifact,
113    /// Absolute local inputs Cargo recorded for the final root executable: its
114    /// sources, `include_*!` files, declared build-script inputs (files or
115    /// directories), and those of every path dependency. `None` when the root
116    /// has no executable, its dep-info is unavailable, or a local build script
117    /// declares no inputs (Cargo then treats its whole package as an input).
118    pub final_root_inputs: Option<Vec<PathBuf>>,
119    /// Keeps the executable snapshot from being pruned while any clone of
120    /// this output is alive. Hold it until the executable has been spawned.
121    pub final_root_lease: Option<Arc<FinalSnapshotLease>>,
122}
123
124/// Read Cargo's `<artifact>.d` beside a final executable: one
125/// `target: dep dep ...` rule per line, with spaces and backslashes in paths
126/// escaped by a backslash. This is not rustc's dep-info dialect (no phony
127/// targets, no `# env-dep` records).
128fn cargo_dep_info_inputs(executable: &Path) -> Option<Vec<PathBuf>> {
129    let name = executable.file_name()?.to_str()?;
130    let stem = name
131        .strip_suffix(std::env::consts::EXE_SUFFIX)
132        .unwrap_or(name);
133    let text = fs::read_to_string(executable.with_file_name(format!("{stem}.d"))).ok()?;
134    let mut inputs = Vec::new();
135    for line in text.lines().filter(|line| !line.is_empty()) {
136        let mut tokens = Vec::new();
137        let mut token = String::new();
138        let mut characters = line.chars();
139        while let Some(character) = characters.next() {
140            match character {
141                '\\' => token.push(characters.next()?),
142                ' ' => tokens.push(std::mem::take(&mut token)),
143                _ => token.push(character),
144            }
145        }
146        tokens.push(token);
147        let mut tokens = tokens.into_iter().filter(|token| !token.is_empty());
148        if !tokens.next()?.ends_with(':') {
149            return None;
150        }
151        for input in tokens.map(PathBuf::from) {
152            // `build.dep-info-basedir` makes these relative to an unknown base.
153            if !input.is_absolute() {
154                return None;
155            }
156            inputs.push(input);
157        }
158    }
159    Some(inputs)
160}
161
162/// Run descriptor compilation, exact linking, semantic planning, and final
163/// Cargo compilation for one root.
164pub fn run_linked_cargo(
165    request: &LinkedCargoRequest,
166) -> Result<LinkedCargoOutput, LinkedCargoError> {
167    validate_request(request)?;
168    prepare_linked_managed_directories(request)?;
169    let lease =
170        run_descriptor_cargo(&request.descriptor).map_err(LinkedCargoError::DescriptorCargo)?;
171    let linked = link_descriptor_transport(lease, request.invocation, &request.root)?;
172    let prepared = prepare_linked_cargo(request, linked)?;
173    let output = finish_prepared_linked_cargo(request, prepared)?;
174    remove_successful_descriptor_staging(&request.descriptor)
175        .map_err(LinkedCargoError::DescriptorStagingCleanup)?;
176    Ok(output)
177}
178
179/// Run the exact linked pipeline while reusing descriptor objects admitted by
180/// the explicit persistent cache.
181///
182/// Cargo remains the freshness authority. The cache is used only after the
183/// current Cargo JSON stream authorizes unchanged artifacts, and every cached
184/// sidecar/object hash is revalidated before linking.
185pub fn run_linked_cargo_cached(
186    request: &LinkedCargoRequest,
187    cache_directory: &std::path::Path,
188) -> Result<LinkedCargoOutput, LinkedCargoError> {
189    run_linked_cargo_cached_with_progress(request, cache_directory, |_| {})
190}
191
192/// Successful output of an optimistic single-pass final build against an empty
193/// RSJS semantic plan.
194#[derive(Clone, Debug)]
195pub struct OptimisticLinkedCargoOutput {
196    /// Empty canonical semantic plan consumed by final Cargo.
197    pub semantic: SemanticLinkPlan,
198    /// Exact content-addressed semantic-plan path.
199    pub semantic_plan_path: PathBuf,
200    /// Plan-sensitive final Cargo output.
201    pub final_cargo: FinalCargoOutput,
202    /// Exact final-phase Cargo artifact attesting the selected root.
203    pub final_root_artifact: CargoCompilerArtifact,
204    /// Absolute local inputs Cargo recorded for the final root executable.
205    pub final_root_inputs: Option<Vec<PathBuf>>,
206    /// Keeps the executable snapshot from being pruned; see
207    /// [`LinkedCargoOutput::final_root_lease`].
208    pub final_root_lease: Option<Arc<FinalSnapshotLease>>,
209}
210
211/// Result of attempting a single-pass optimistic empty-plan dev build.
212#[derive(Clone, Debug)]
213#[allow(
214    clippy::large_enum_variant,
215    reason = "keep the public success payload inline without allocating for each development rebuild"
216)]
217pub enum OptimisticLinkedCargoOutcome {
218    /// Single-pass final Cargo succeeded with zero unmapped RSJS macros.
219    Succeeded(OptimisticLinkedCargoOutput),
220    /// At least one compiled unit expanded an RSJS macro that requires the full
221    /// descriptor + link + final two-pass pipeline.
222    NeedsFullLinkedPass,
223}
224
225/// Attempt a single-pass final Cargo build against an empty RSJS semantic plan,
226/// skipping descriptor compilation, descriptor cache validation, and transport
227/// linking when no compiled unit expands an RSJS macro.
228///
229/// Soundness is enforced fail-closed by `rsjs_macros`: because the empty unit
230/// map marks every compiled unit `RSJS_FINAL_CARGO_UNIT_STATUS=unmapped-v1`,
231/// any unit that invokes `#[rsjs(...)]`, `#[client]`, or `#[derive(SharedState)]`
232/// fails compilation immediately and returns `NeedsFullLinkedPass`.
233pub fn try_run_optimistic_empty_linked_cargo(
234    request: &LinkedCargoRequest,
235) -> Result<OptimisticLinkedCargoOutcome, LinkedCargoError> {
236    validate_request(request)?;
237    validate_selector(&request.root)?;
238    prepare_linked_managed_directories(request)?;
239
240    let mut link_unit_seed = format!(
241        "proa.rsjs.optimistic-empty-link-unit.v1\0{}\0{}\0{}",
242        request.invocation, request.root.package_id, request.root.target_name,
243    );
244    for kind in &request.root.target_kinds {
245        link_unit_seed.push('\0');
246        link_unit_seed.push_str(kind);
247    }
248    let link_unit = LinkUnitId::derive(&link_unit_seed);
249    let empty_adapted = AdaptedTransportAbi {
250        components: Vec::new(),
251        helpers: Vec::new(),
252    };
253    let semantic =
254        link_semantic_plan(link_unit, &empty_adapted).map_err(LinkedCargoError::SemanticLink)?;
255    let semantic_plan_path =
256        write_content_addressed_semantic_plan(&request.plan_directory, &semantic)
257            .map_err(LinkedCargoError::WriteSemanticPlan)?;
258
259    let final_request = FinalCargoRequest {
260        invocation: request.invocation,
261        cargo: request.descriptor.cargo.clone(),
262        wrapper: request.descriptor.wrapper.clone(),
263        working_directory: request.descriptor.working_directory.clone(),
264        source_exclusion_directory: request.descriptor.source_exclusion_directory.clone(),
265        target_root: request.final_target_root.clone(),
266        plan_path: semantic_plan_path.clone(),
267        cargo_args: request.final_cargo_args.clone(),
268        environment: request.descriptor.environment.clone(),
269        root_unit_fingerprint: SemanticHash::derive(&link_unit_seed),
270        descriptor_units: Vec::new(),
271    };
272
273    let final_cargo_run = match run_final_cargo_leased_optimistic(&final_request, &semantic)
274        .map_err(LinkedCargoError::FinalCargo)?
275    {
276        OptimisticFinalCargoOutcome::NeedsFullLinkedPass => {
277            return Ok(OptimisticLinkedCargoOutcome::NeedsFullLinkedPass);
278        }
279        OptimisticFinalCargoOutcome::Succeeded(run) => run,
280    };
281    let published = publish_final_root(request, final_cargo_run, None)?;
282
283    Ok(OptimisticLinkedCargoOutcome::Succeeded(
284        OptimisticLinkedCargoOutput {
285            semantic,
286            semantic_plan_path,
287            final_cargo: published.final_cargo,
288            final_root_artifact: published.final_root_artifact,
289            final_root_inputs: published.final_root_inputs,
290            final_root_lease: published.final_root_lease,
291        },
292    ))
293}
294
295struct PublishedFinalRoot {
296    final_cargo: FinalCargoOutput,
297    final_root_artifact: CargoCompilerArtifact,
298    final_root_inputs: Option<Vec<PathBuf>>,
299    final_root_lease: Option<Arc<FinalSnapshotLease>>,
300}
301
302/// Attest the selected root in a finished final Cargo run, publish it into
303/// immutable snapshot storage, and run it when the request asks for that.
304fn publish_final_root(
305    request: &LinkedCargoRequest,
306    final_cargo_run: FinalCargoRun,
307    descriptor_root: Option<&CargoCompilerArtifact>,
308) -> Result<PublishedFinalRoot, LinkedCargoError> {
309    let final_root_artifact = attest_final_root(
310        final_cargo_run.output(),
311        final_cargo_run.cargo_artifacts(),
312        &request.root,
313        descriptor_root,
314    )?;
315    // Cargo writes dep-info beside the artifact in the reusable target, not
316    // beside the snapshot. Read it while the target lease is still held.
317    let final_root_inputs = final_root_artifact
318        .executable
319        .as_deref()
320        .filter(|_| final_cargo_run.local_scripts_declare_inputs)
321        .and_then(cargo_dep_info_inputs);
322    let (final_root_artifact, final_root_lease) = snapshot_final_artifact(
323        &request.descriptor.source_exclusion_directory,
324        &request.final_target_root.join(FINAL_SNAPSHOT_ROOT_NAME),
325        &final_cargo_run.output().target_directory,
326        &final_root_artifact,
327    )
328    .map_err(LinkedCargoError::FinalCargo)?;
329    let final_cargo = final_cargo_run.into_output();
330    // The selected root now points only at immutable content-addressed files,
331    // so long-running programs never retain the reusable target lease and a
332    // later build cannot replace the artifact between attestation and spawn.
333    execute_requested_final_root(request, &final_root_artifact)?;
334    Ok(PublishedFinalRoot {
335        final_cargo,
336        final_root_artifact,
337        final_root_inputs,
338        final_root_lease: final_root_lease.map(Arc::new),
339    })
340}
341
342pub enum LinkedCargoStage {
343    Descriptor,
344    Link,
345    Final,
346}
347
348pub fn run_linked_cargo_cached_with_progress(
349    request: &LinkedCargoRequest,
350    cache_directory: &Path,
351    mut progress: impl FnMut(LinkedCargoStage),
352) -> Result<LinkedCargoOutput, LinkedCargoError> {
353    let managed = validate_request(request)?;
354    validate_cache_against_linked_paths(cache_directory, &managed)?;
355    prepare_linked_managed_directories(request)?;
356    progress(LinkedCargoStage::Descriptor);
357    let lease = run_descriptor_cargo_cached(&request.descriptor, cache_directory)
358        .map_err(LinkedCargoError::DescriptorCache)?;
359    progress(LinkedCargoStage::Link);
360    let linked = link_descriptor_transport(lease, request.invocation, &request.root)?;
361    let prepared = prepare_linked_cargo(request, linked)?;
362    progress(LinkedCargoStage::Final);
363    finish_prepared_linked_cargo(request, prepared)
364}
365
366fn validate_cache_against_linked_paths(
367    cache_directory: &Path,
368    managed: &ValidatedLinkedManagedPaths,
369) -> Result<(), LinkedCargoError> {
370    let cache = normalize_linked_managed_path("descriptor cache", cache_directory)?;
371    for (kind, path) in [
372        ("semantic plans", &managed.plan),
373        ("final targets", &managed.final_target),
374    ] {
375        if managed_paths_overlap(&cache, path) {
376            return Err(LinkedCargoError::ManagedDirectoryOverlap {
377                first_kind: "descriptor cache",
378                first: cache.clone(),
379                second_kind: kind,
380                second: path.clone(),
381            });
382        }
383    }
384    Ok(())
385}
386
387struct PreparedLinkedCargo {
388    descriptor: DescriptorCargoReport,
389    selected: SelectedDescriptorRoot,
390    transport: TransportLinkPlan,
391    adapted: AdaptedTransportAbi,
392    semantic: SemanticLinkPlan,
393    semantic_plan_path: PathBuf,
394    final_descriptor_units: Vec<ValidatedDescriptorUnit>,
395}
396
397/// Descriptor artifacts fully hashed and transport-linked while their target
398/// and optional cache generation remained exclusively leased.
399#[derive(Debug)]
400pub struct LinkedDescriptorTransport {
401    /// Path-free descriptor diagnostics.
402    pub descriptor: DescriptorCargoReport,
403    /// Exact selected descriptor unit.
404    pub root_unit: DescriptorCargoUnitId,
405    /// Relocation-resolved transport graph, independent of target paths.
406    pub transport: TransportLinkPlan,
407    selected: SelectedDescriptorRoot,
408    final_descriptor_units: Vec<ValidatedDescriptorUnit>,
409}
410
411/// Consume a cached or uncached descriptor run and materialize every mutable
412/// target byte needed by the transport linker before releasing its leases.
413pub fn link_descriptor_transport<R: DescriptorCargoRun>(
414    run: R,
415    invocation: InvocationId,
416    selector: &DescriptorRootSelector,
417) -> Result<LinkedDescriptorTransport, LinkedCargoError> {
418    let mut timing = super::timing::StageTimer::new();
419    let linked = {
420        let descriptor = descriptor_run_sealed::Sealed::output(&run);
421        let selected = select_descriptor_root(descriptor, selector)?;
422        let manifest = build_link_unit_manifest(
423            invocation,
424            selected.unit,
425            &selected.artifact,
426            selector.role,
427            descriptor,
428        )
429        .map_err(LinkedCargoError::LinkManifest)?;
430        timing.mark("transport manifest and root selection");
431        let transport = link_transport_manifest(&manifest, &descriptor.units, &descriptor.objects)
432            .map_err(LinkedCargoError::TransportLink)?;
433        timing.mark("transport graph");
434        let cargo_enumerated_units =
435            join_cargo_enumerated_descriptor_units(&descriptor.units, &descriptor.cargo_artifacts)
436                .map_err(LinkedCargoError::JoinDescriptorArtifacts)?;
437        let final_descriptor_units = descriptor
438            .units
439            .iter()
440            .filter(|unit| cargo_enumerated_units.contains_key(&unit.unit))
441            .cloned()
442            .collect();
443
444        LinkedDescriptorTransport {
445            descriptor: DescriptorCargoReport::from_output(descriptor),
446            root_unit: selected.unit,
447            transport,
448            selected,
449            final_descriptor_units,
450        }
451    };
452
453    // `linked` owns only extracted/path-free material plus private final-map
454    // inputs. Releasing the lease here keeps semantic-plan writes and final
455    // Cargo outside both descriptor and cache critical sections.
456    drop(descriptor_run_sealed::Sealed::into_output(run));
457    timing.mark("transport final-unit selection");
458    Ok(linked)
459}
460
461fn prepare_linked_cargo(
462    request: &LinkedCargoRequest,
463    linked: LinkedDescriptorTransport,
464) -> Result<PreparedLinkedCargo, LinkedCargoError> {
465    let LinkedDescriptorTransport {
466        descriptor,
467        selected,
468        transport,
469        final_descriptor_units,
470        ..
471    } = linked;
472    let mut timing = super::timing::StageTimer::new();
473    let abi = AbiAdapterContext::from_transport_plan(
474        request.producer,
475        request.runtime_protocol,
476        &transport,
477    )
478    .map_err(LinkedCargoError::AbiAdapter)?;
479    let adapted = adapt_transport_plan(&abi, &transport).map_err(LinkedCargoError::AbiAdapter)?;
480    timing.mark("ABI adaptation");
481    let semantic = link_semantic_plan(transport.link_unit, &adapted)
482        .map_err(LinkedCargoError::SemanticLink)?;
483    timing.mark("semantic planning");
484    let semantic_plan_path =
485        write_content_addressed_semantic_plan(&request.plan_directory, &semantic)
486            .map_err(LinkedCargoError::WriteSemanticPlan)?;
487    timing.mark("semantic plan publication");
488    Ok(PreparedLinkedCargo {
489        descriptor,
490        selected,
491        transport,
492        adapted,
493        semantic,
494        semantic_plan_path,
495        final_descriptor_units,
496    })
497}
498
499fn finish_prepared_linked_cargo(
500    request: &LinkedCargoRequest,
501    prepared: PreparedLinkedCargo,
502) -> Result<LinkedCargoOutput, LinkedCargoError> {
503    let PreparedLinkedCargo {
504        descriptor,
505        selected,
506        transport,
507        adapted,
508        semantic,
509        semantic_plan_path,
510        final_descriptor_units,
511    } = prepared;
512
513    let final_request = FinalCargoRequest {
514        invocation: request.invocation,
515        cargo: request.descriptor.cargo.clone(),
516        wrapper: request.descriptor.wrapper.clone(),
517        working_directory: request.descriptor.working_directory.clone(),
518        source_exclusion_directory: request.descriptor.source_exclusion_directory.clone(),
519        target_root: request.final_target_root.clone(),
520        plan_path: semantic_plan_path.clone(),
521        cargo_args: request.final_cargo_args.clone(),
522        // validate_request proves both phase maps are byte-for-byte equal;
523        // keep one frozen source of truth for all caller-supplied variables.
524        environment: request.descriptor.environment.clone(),
525        root_unit_fingerprint: SemanticHash::derive(&selected.unit.as_abi_id()),
526        descriptor_units: final_descriptor_units,
527    };
528    let final_cargo_run =
529        run_final_cargo_leased(&final_request, &semantic).map_err(LinkedCargoError::FinalCargo)?;
530    let published = publish_final_root(request, final_cargo_run, Some(&selected.cargo_artifact))?;
531
532    Ok(LinkedCargoOutput {
533        descriptor,
534        root_unit: selected.unit,
535        transport,
536        adapted,
537        semantic,
538        semantic_plan_path,
539        final_cargo: published.final_cargo,
540        final_root_artifact: published.final_root_artifact,
541        final_root_inputs: published.final_root_inputs,
542        final_root_lease: published.final_root_lease,
543    })
544}
545
546#[derive(Clone, Debug)]
547struct SelectedDescriptorRoot {
548    unit: DescriptorCargoUnitId,
549    artifact: PathBuf,
550    cargo_artifact: CargoCompilerArtifact,
551}
552
553fn select_descriptor_root(
554    output: &DescriptorCargoOutput,
555    selector: &DescriptorRootSelector,
556) -> Result<SelectedDescriptorRoot, LinkedCargoError> {
557    validate_selector(selector)?;
558    let joined = join_cargo_enumerated_descriptor_units(&output.units, &output.cargo_artifacts)
559        .map_err(LinkedCargoError::JoinDescriptorArtifacts)?;
560    let mut matches = joined
561        .into_iter()
562        .filter(|(_, artifact)| root_artifact_matches(artifact, selector))
563        .collect::<Vec<_>>();
564    matches.sort_by(|left, right| left.0.as_bytes().cmp(right.0.as_bytes()));
565
566    let (unit, artifact) = match matches.as_slice() {
567        [] => {
568            return Err(LinkedCargoError::MissingRoot {
569                package_id: selector.package_id.clone(),
570                target_name: selector.target_name.clone(),
571            });
572        }
573        [(unit, artifact)] => (*unit, artifact),
574        _ => {
575            return Err(LinkedCargoError::AmbiguousRoot {
576                package_id: selector.package_id.clone(),
577                target_name: selector.target_name.clone(),
578                matches: matches.len(),
579            });
580        }
581    };
582    let artifact_path = select_root_path(artifact, selector)?;
583    Ok(SelectedDescriptorRoot {
584        unit,
585        artifact: artifact_path,
586        cargo_artifact: artifact.clone(),
587    })
588}
589
590fn root_artifact_matches(
591    artifact: &CargoCompilerArtifact,
592    selector: &DescriptorRootSelector,
593) -> bool {
594    artifact.package_id == selector.package_id
595        && artifact.target.name == selector.target_name
596        && artifact.target.kind == selector.target_kinds
597}
598
599fn select_root_path(
600    artifact: &CargoCompilerArtifact,
601    selector: &DescriptorRootSelector,
602) -> Result<PathBuf, LinkedCargoError> {
603    if let Some(requested) = &selector.artifact_path {
604        if !requested.is_absolute() {
605            return Err(LinkedCargoError::RelativeRootArtifact(requested.clone()));
606        }
607        if artifact.executable.as_ref() == Some(requested) || artifact.filenames.contains(requested)
608        {
609            return Ok(requested.clone());
610        }
611        return Err(LinkedCargoError::RootArtifactNotEnumerated(
612            requested.clone(),
613        ));
614    }
615
616    // Cargo's executable field is authoritative. MSVC also enumerates a PDB,
617    // which is a debug companion rather than a second possible root.
618    if let Some(executable) = &artifact.executable {
619        return Ok(executable.clone());
620    }
621    let candidates = artifact
622        .filenames
623        .iter()
624        .filter(|path| {
625            !path
626                .extension()
627                .is_some_and(|ext| ext.eq_ignore_ascii_case("pdb"))
628        })
629        .cloned()
630        .collect::<BTreeSet<_>>();
631    match candidates.len() {
632        0 => Err(LinkedCargoError::RootHasNoArtifact),
633        1 => Ok(candidates
634            .into_iter()
635            .next()
636            .expect("one candidate was counted")),
637        count => Err(LinkedCargoError::AmbiguousRootArtifact { matches: count }),
638    }
639}
640
641/// Select the requested root among final Cargo artifacts.
642///
643/// With a descriptor root (the two-pass pipeline), the final root must keep
644/// the descriptor root's exact Cargo coordinate. The optimistic single pass
645/// has no descriptor root to compare against.
646fn attest_final_root(
647    output: &FinalCargoOutput,
648    cargo_artifacts: &[CargoCompilerArtifact],
649    selector: &DescriptorRootSelector,
650    descriptor_root: Option<&CargoCompilerArtifact>,
651) -> Result<CargoCompilerArtifact, LinkedCargoError> {
652    let mut matches = cargo_artifacts
653        .iter()
654        .filter(|artifact| root_artifact_matches(artifact, selector))
655        .collect::<Vec<_>>();
656    matches.sort_by(|left, right| {
657        left.manifest_path
658            .cmp(&right.manifest_path)
659            .then_with(|| left.target.src_path.cmp(&right.target.src_path))
660    });
661    let final_root = match matches.as_slice() {
662        [] => {
663            return Err(LinkedCargoError::MissingFinalRoot {
664                package_id: selector.package_id.clone(),
665                target_name: selector.target_name.clone(),
666            });
667        }
668        [artifact] => *artifact,
669        artifacts => {
670            return Err(LinkedCargoError::AmbiguousFinalRoot {
671                package_id: selector.package_id.clone(),
672                target_name: selector.target_name.clone(),
673                matches: artifacts.len(),
674            });
675        }
676    };
677
678    if let Some(descriptor_root) = descriptor_root {
679        if final_root.manifest_path != descriptor_root.manifest_path
680            || final_root.target != descriptor_root.target
681            || final_root.profile != descriptor_root.profile
682            || final_root.features != descriptor_root.features
683        {
684            return Err(LinkedCargoError::FinalRootCoordinateMismatch {
685                package_id: selector.package_id.clone(),
686                target_name: selector.target_name.clone(),
687            });
688        }
689    }
690
691    let expects_executable = descriptor_root.map_or(final_root.executable.is_some(), |root| {
692        root.executable.is_some()
693    });
694    let materialized = match (expects_executable, final_root.executable.as_ref()) {
695        (true, Some(executable)) => executable,
696        (true, None) => {
697            return Err(LinkedCargoError::MissingFinalRootExecutable {
698                package_id: selector.package_id.clone(),
699                target_name: selector.target_name.clone(),
700            });
701        }
702        (false, _) => final_root
703            .filenames
704            .iter()
705            .next()
706            .ok_or(LinkedCargoError::FinalRootHasNoArtifact)?,
707    };
708    ensure_plain_managed_file(&output.target_directory, materialized)
709        .map_err(LinkedCargoError::ManagedPath)?;
710    let metadata = fs::symlink_metadata(materialized).map_err(|source| {
711        LinkedCargoError::InspectFinalRootArtifact {
712            path: materialized.clone(),
713            source,
714        }
715    })?;
716    if !metadata.file_type().is_file() {
717        return Err(LinkedCargoError::FinalRootArtifactNotFile(
718            materialized.clone(),
719        ));
720    }
721
722    Ok(final_root.clone())
723}
724
725#[derive(Clone, Copy, Debug, PartialEq, Eq)]
726enum FinalExecution<'a> {
727    None,
728    Run(&'a [OsString]),
729    Test(&'a [OsString]),
730}
731
732fn requested_final_execution(arguments: &[OsString]) -> FinalExecution<'_> {
733    let (compile_arguments, runtime_arguments) = split_cargo_runtime_arguments(arguments);
734    let runtime_arguments = runtime_arguments.unwrap_or_default();
735    match compile_arguments.first().map(OsString::as_os_str) {
736        Some(subcommand) if subcommand == OsStr::new("run") => {
737            FinalExecution::Run(runtime_arguments)
738        }
739        Some(subcommand) if subcommand == OsStr::new("test") => {
740            if compile_arguments.iter().any(|arg| arg == "--no-run") {
741                FinalExecution::None
742            } else {
743                FinalExecution::Test(runtime_arguments)
744            }
745        }
746        _ => FinalExecution::None,
747    }
748}
749
750fn execute_requested_final_root(
751    request: &LinkedCargoRequest,
752    artifact: &CargoCompilerArtifact,
753) -> Result<(), LinkedCargoError> {
754    let execution = requested_final_execution(&request.final_cargo_args);
755    let (runtime_arguments, working_directory) = match execution {
756        FinalExecution::None => return Ok(()),
757        FinalExecution::Run(arguments) => {
758            (arguments, request.descriptor.working_directory.as_path())
759        }
760        FinalExecution::Test(arguments) => {
761            let working_directory = artifact.manifest_path.parent().ok_or_else(|| {
762                LinkedCargoError::FinalRootManifestWithoutParent(artifact.manifest_path.clone())
763            })?;
764            (arguments, working_directory)
765        }
766    };
767    let executable = artifact.executable.as_ref().ok_or_else(|| {
768        LinkedCargoError::FinalRootNotHostExecutable {
769            package_id: artifact.package_id.clone(),
770            target_name: artifact.target.name.clone(),
771        }
772    })?;
773
774    let status = Command::new(executable)
775        .current_dir(working_directory)
776        .args(runtime_arguments)
777        .envs(&request.final_environment)
778        // `status` inherits the caller's raw stdin/stdout/stderr. The direct
779        // child also inherits the normal local environment; only explicit
780        // request variables override it, matching the Cargo invocation.
781        .status()
782        .map_err(|source| LinkedCargoError::ExecuteFinalRoot {
783            path: executable.clone(),
784            source,
785        })?;
786    if !status.success() {
787        return Err(LinkedCargoError::FinalRootExited {
788            path: executable.clone(),
789            status,
790        });
791    }
792    Ok(())
793}
794
795fn validate_phase_cargo_arguments(
796    descriptor: &[OsString],
797    final_args: &[OsString],
798) -> Result<(), LinkedCargoError> {
799    let (descriptor_compile, descriptor_runtime) = split_cargo_runtime_arguments(descriptor);
800    if descriptor_runtime.is_some() {
801        return Err(LinkedCargoError::DescriptorRuntimeArguments);
802    }
803    let (final_compile, final_runtime) = split_cargo_runtime_arguments(final_args);
804    let descriptor_subcommand = descriptor_compile
805        .first()
806        .ok_or(LinkedCargoError::MissingDescriptorCargoArguments)?;
807    let final_subcommand = final_compile
808        .first()
809        .ok_or(LinkedCargoError::MissingFinalCargoArguments)?;
810
811    let supported_pair = (
812        descriptor_subcommand.as_os_str(),
813        final_subcommand.as_os_str(),
814    );
815    if !matches!(
816        supported_pair,
817        (descriptor, final_phase)
818            if (descriptor == OsStr::new("build")
819                && (final_phase == OsStr::new("build")
820                    || final_phase == OsStr::new("run")))
821                || (descriptor == OsStr::new("check")
822                    && final_phase == OsStr::new("check"))
823                || (descriptor == OsStr::new("test")
824                    && final_phase == OsStr::new("test"))
825    ) {
826        return Err(LinkedCargoError::UnsupportedPhaseSubcommands {
827            descriptor: descriptor_subcommand.clone(),
828            final_phase: final_subcommand.clone(),
829        });
830    }
831    if final_runtime.is_some()
832        && final_subcommand != OsStr::new("run")
833        && final_subcommand != OsStr::new("test")
834    {
835        return Err(LinkedCargoError::UnsupportedFinalRuntimeArguments(
836            final_subcommand.clone(),
837        ));
838    }
839
840    let mut normalized_descriptor = descriptor_compile.to_vec();
841    let mut normalized_final = final_compile.to_vec();
842    normalized_descriptor[0] = OsString::from("<linked-phase>");
843    normalized_final[0] = OsString::from("<linked-phase>");
844
845    let descriptor_len = normalized_descriptor.len();
846    normalized_descriptor.retain(|argument| argument != "--no-run");
847    let descriptor_no_run = descriptor_len - normalized_descriptor.len();
848    let final_len = normalized_final.len();
849    normalized_final.retain(|argument| argument != "--no-run");
850    let final_no_run = final_len - normalized_final.len();
851    if descriptor_subcommand == OsStr::new("test") {
852        if descriptor_no_run != 1
853            || final_no_run > 1
854            || (final_no_run == 1 && final_runtime.is_some())
855        {
856            return Err(LinkedCargoError::InvalidTestPhaseNoRun);
857        }
858    } else if descriptor_no_run != 0 || final_no_run != 0 {
859        return Err(LinkedCargoError::InvalidTestPhaseNoRun);
860    }
861
862    if normalized_descriptor != normalized_final {
863        return Err(LinkedCargoError::PhaseCargoArgumentsMismatch {
864            descriptor: normalized_descriptor,
865            final_phase: normalized_final,
866        });
867    }
868    Ok(())
869}
870
871fn split_cargo_runtime_arguments(arguments: &[OsString]) -> (&[OsString], Option<&[OsString]>) {
872    match arguments
873        .iter()
874        .position(|argument| argument == OsStr::new("--"))
875    {
876        Some(index) => (&arguments[..index], Some(&arguments[index + 1..])),
877        None => (arguments, None),
878    }
879}
880
881pub(crate) struct ValidatedLinkedManagedPaths {
882    plan: PathBuf,
883    final_target: PathBuf,
884}
885
886/// Check managed-path and invocation constraints without starting a build.
887pub fn validate_linked_cargo_request(request: &LinkedCargoRequest) -> Result<(), LinkedCargoError> {
888    validate_request(request).map(|_| ())
889}
890
891pub(crate) fn validate_request(
892    request: &LinkedCargoRequest,
893) -> Result<ValidatedLinkedManagedPaths, LinkedCargoError> {
894    if !request.plan_directory.is_absolute() {
895        return Err(LinkedCargoError::RelativePlanDirectory(
896            request.plan_directory.clone(),
897        ));
898    }
899    if !request.final_target_root.is_absolute() {
900        return Err(LinkedCargoError::RelativeFinalTargetRoot(
901            request.final_target_root.clone(),
902        ));
903    }
904    if request.final_cargo_args.is_empty() {
905        return Err(LinkedCargoError::MissingFinalCargoArguments);
906    }
907    validate_phase_cargo_arguments(&request.descriptor.cargo_args, &request.final_cargo_args)?;
908    if request.descriptor.environment != request.final_environment {
909        let names = request
910            .descriptor
911            .environment
912            .keys()
913            .chain(request.final_environment.keys())
914            .collect::<BTreeSet<_>>()
915            .into_iter()
916            .filter(|name| {
917                request.descriptor.environment.get(*name) != request.final_environment.get(*name)
918            })
919            .cloned()
920            .collect();
921        return Err(LinkedCargoError::PhaseEnvironmentMismatch { names });
922    }
923    let descriptor = validate_descriptor_managed_paths(&request.descriptor)
924        .map_err(LinkedCargoError::DescriptorManagedPaths)?;
925    let plan = normalize_linked_managed_path("semantic plans", &request.plan_directory)?;
926    let final_target = normalize_linked_managed_path("final targets", &request.final_target_root)?;
927    let managed_roots = [
928        ("descriptor staging", &descriptor.staging),
929        ("descriptor target", &descriptor.target),
930        ("semantic plans", &plan),
931        ("final targets", &final_target),
932    ];
933    for (index, (first_kind, first)) in managed_roots.iter().enumerate() {
934        for (second_kind, second) in &managed_roots[index + 1..] {
935            if managed_paths_overlap(first, second) {
936                return Err(LinkedCargoError::ManagedDirectoryOverlap {
937                    first_kind,
938                    first: (*first).clone(),
939                    second_kind,
940                    second: (*second).clone(),
941                });
942            }
943        }
944    }
945    Ok(ValidatedLinkedManagedPaths { plan, final_target })
946}
947
948fn prepare_linked_managed_directories(
949    request: &LinkedCargoRequest,
950) -> Result<(), LinkedCargoError> {
951    ensure_plain_managed_directory(
952        &request.descriptor.source_exclusion_directory,
953        &request.plan_directory,
954    )
955    .map_err(LinkedCargoError::ManagedPath)?;
956    ensure_plain_managed_directory(
957        &request.descriptor.source_exclusion_directory,
958        &request.final_target_root,
959    )
960    .map_err(LinkedCargoError::ManagedPath)?;
961    Ok(())
962}
963
964fn normalize_linked_managed_path(
965    kind: &'static str,
966    path: &Path,
967) -> Result<PathBuf, LinkedCargoError> {
968    normalize_managed_path_identity(path).map_err(|source| {
969        LinkedCargoError::NormalizeManagedDirectory {
970            kind,
971            path: path.to_path_buf(),
972            source,
973        }
974    })
975}
976
977fn validate_selector(selector: &DescriptorRootSelector) -> Result<(), LinkedCargoError> {
978    if selector.package_id.is_empty() {
979        return Err(LinkedCargoError::EmptyRootSelector("package_id"));
980    }
981    if selector.target_name.is_empty() {
982        return Err(LinkedCargoError::EmptyRootSelector("target_name"));
983    }
984    if selector.target_kinds.is_empty() || selector.target_kinds.iter().any(String::is_empty) {
985        return Err(LinkedCargoError::EmptyRootSelector("target_kinds"));
986    }
987    if !selector.role.is_root() {
988        return Err(LinkedCargoError::NonRootRole(selector.role));
989    }
990    Ok(())
991}
992
993/// End-to-end orchestration failure.
994#[derive(Debug, Error)]
995#[non_exhaustive]
996pub enum LinkedCargoError {
997    /// Descriptor Cargo must receive an explicit subcommand/selection too.
998    #[error("RSJS descriptor Cargo arguments are empty")]
999    MissingDescriptorCargoArguments,
1000    /// Plan storage must be cwd-independent.
1001    #[error("RSJS semantic-plan directory must be absolute: `{0}`")]
1002    RelativePlanDirectory(PathBuf),
1003    /// Final artifacts live in an invocation- and wrapper-policy-scoped
1004    /// absolute namespace.
1005    #[error("RSJS final target root must be absolute: `{0}`")]
1006    RelativeFinalTargetRoot(PathBuf),
1007    /// Final Cargo must receive an explicit subcommand/selection.
1008    #[error("RSJS final Cargo arguments are empty")]
1009    MissingFinalCargoArguments,
1010    /// Descriptor compilation may never execute a selected program.
1011    #[error("descriptor Cargo arguments may not contain a runtime `-- ...` suffix")]
1012    DescriptorRuntimeArguments,
1013    /// Only the lifecycle's known phase pairs preserve one Cargo unit model.
1014    #[error(
1015        "unsupported linked Cargo phase pair: descriptor {descriptor:?}, final {final_phase:?}"
1016    )]
1017    UnsupportedPhaseSubcommands {
1018        /// Descriptor-pass Cargo subcommand.
1019        descriptor: OsString,
1020        /// Final-pass Cargo subcommand.
1021        final_phase: OsString,
1022    },
1023    /// Runtime arguments are meaningful only for final run/test invocations.
1024    #[error("final Cargo subcommand {0:?} may not contain runtime arguments after `--`")]
1025    UnsupportedFinalRuntimeArguments(OsString),
1026    /// Tests compile without execution in the descriptor phase. The final
1027    /// phase may return a harness for a caller to launch with runtime setup.
1028    #[error(
1029        "`--no-run` is required exactly once for the descriptor test pass and is allowed once for a final test pass without harness arguments"
1030    )]
1031    InvalidTestPhaseNoRun,
1032    /// After the controlled phase rewrite, every Cargo selection/config input
1033    /// must be byte-for-byte identical.
1034    #[error(
1035        "descriptor and final Cargo selection/config arguments diverge after phase normalization: descriptor {descriptor:?}, final {final_phase:?}"
1036    )]
1037    PhaseCargoArgumentsMismatch {
1038        /// Normalized descriptor arguments.
1039        descriptor: Vec<OsString>,
1040        /// Normalized final arguments.
1041        final_phase: Vec<OsString>,
1042    },
1043    /// Caller-supplied compilation environment must be frozen across phases.
1044    #[error(
1045        "descriptor and final Cargo environments differ for variable names {names:?}; use one identical environment map for both phases"
1046    )]
1047    PhaseEnvironmentMismatch {
1048        /// Names only; potentially secret values are never included.
1049        names: Vec<OsString>,
1050    },
1051    /// Every generated namespace is a separate identity/deletion boundary.
1052    #[error(
1053        "RSJS managed {first_kind} directory `{first}` overlaps {second_kind} directory `{second}`"
1054    )]
1055    ManagedDirectoryOverlap {
1056        /// First managed namespace role.
1057        first_kind: &'static str,
1058        /// First managed namespace root.
1059        first: PathBuf,
1060        /// Second managed namespace role.
1061        second_kind: &'static str,
1062        /// Second managed namespace root.
1063        second: PathBuf,
1064    },
1065    /// Managed output confinement or plain-entry validation failed.
1066    #[error(transparent)]
1067    ManagedPath(#[from] ManagedPathError),
1068    /// Descriptor path relationships must be validated before any linked
1069    /// namespace is created.
1070    #[error("invalid descriptor managed paths: {0}")]
1071    DescriptorManagedPaths(#[source] DescriptorCargoRunError),
1072    /// Cross-subsystem comparisons use one canonical managed-path identity.
1073    #[error("failed to normalize RSJS managed {kind} directory `{path}`: {source}")]
1074    NormalizeManagedDirectory {
1075        /// Managed namespace role.
1076        kind: &'static str,
1077        /// Caller-supplied path.
1078        path: PathBuf,
1079        /// Canonicalization failure.
1080        #[source]
1081        source: std::io::Error,
1082    },
1083    /// Root selection fields are exact and nonempty.
1084    #[error("RSJS root selector field `{0}` must not be empty")]
1085    EmptyRootSelector(&'static str),
1086    /// A dependency role cannot be selected as a root.
1087    #[error("RSJS root selector uses non-root artifact role {0:?}")]
1088    NonRootRole(ArtifactRole),
1089    /// Descriptor Cargo failed.
1090    #[error("RSJS descriptor compilation failed: {0}")]
1091    DescriptorCargo(#[source] DescriptorCargoRunError),
1092    /// A fully successful uncached run could not remove only its exact,
1093    /// marker-owned invocation staging tree.
1094    #[error("failed to clean successful RSJS descriptor staging: {0}")]
1095    DescriptorStagingCleanup(#[source] DescriptorCargoRunError),
1096    /// Persistent descriptor reuse failed closed.
1097    #[error("RSJS descriptor cache validation failed: {0}")]
1098    DescriptorCache(#[source] DescriptorCacheError),
1099    /// Wrapper sidecars could not be joined to this invocation's Cargo
1100    /// messages.
1101    #[error("failed to join RSJS descriptor units to Cargo artifacts: {0}")]
1102    JoinDescriptorArtifacts(#[source] UnitArtifactJoinError),
1103    /// The exact selected Cargo root did not exist.
1104    #[error(
1105        "descriptor Cargo emitted no exact root for package `{package_id}` target `{target_name}`"
1106    )]
1107    MissingRoot {
1108        /// Exact package ID.
1109        package_id: String,
1110        /// Exact target name.
1111        target_name: String,
1112    },
1113    /// More than one unit matched an exact root selector.
1114    #[error(
1115        "descriptor Cargo emitted {matches} roots for package `{package_id}` target `{target_name}`"
1116    )]
1117    AmbiguousRoot {
1118        /// Exact package ID.
1119        package_id: String,
1120        /// Exact target name.
1121        target_name: String,
1122        /// Candidate count.
1123        matches: usize,
1124    },
1125    /// Final Cargo must emit the exact root selected from descriptor Cargo.
1126    #[error(
1127        "final Cargo emitted no exact root for descriptor package `{package_id}` target `{target_name}`"
1128    )]
1129    MissingFinalRoot {
1130        /// Exact package ID.
1131        package_id: String,
1132        /// Exact target name.
1133        target_name: String,
1134    },
1135    /// One exact root selection must remain unique in the final phase.
1136    #[error(
1137        "final Cargo emitted {matches} exact roots for descriptor package `{package_id}` target `{target_name}`"
1138    )]
1139    AmbiguousFinalRoot {
1140        /// Exact package ID.
1141        package_id: String,
1142        /// Exact target name.
1143        target_name: String,
1144        /// Candidate count.
1145        matches: usize,
1146    },
1147    /// Profile, features, manifest, and target metadata are part of root
1148    /// identity across phases.
1149    #[error(
1150        "final Cargo root coordinate differs from descriptor root for package `{package_id}` target `{target_name}`"
1151    )]
1152    FinalRootCoordinateMismatch {
1153        /// Exact package ID.
1154        package_id: String,
1155        /// Exact target name.
1156        target_name: String,
1157    },
1158    /// Executable roots must remain executable roots in the final phase.
1159    #[error(
1160        "final Cargo root for package `{package_id}` target `{target_name}` has no executable"
1161    )]
1162    MissingFinalRootExecutable {
1163        /// Exact package ID.
1164        package_id: String,
1165        /// Exact target name.
1166        target_name: String,
1167    },
1168    /// A final check root still needs one Cargo-enumerated materialized file.
1169    #[error("selected final RSJS root has no Cargo-enumerated artifact")]
1170    FinalRootHasNoArtifact,
1171    /// Final root output inspection failed.
1172    #[error("failed to inspect selected final root artifact `{path}`: {source}")]
1173    InspectFinalRootArtifact {
1174        /// Cargo-enumerated artifact path.
1175        path: PathBuf,
1176        /// Filesystem failure.
1177        #[source]
1178        source: std::io::Error,
1179    },
1180    /// Cargo-enumerated final root material must be an ordinary file.
1181    #[error("selected final root artifact is not a plain regular file: `{0}`")]
1182    FinalRootArtifactNotFile(PathBuf),
1183    /// Run/test requests require a directly host-executable attested root.
1184    #[error(
1185        "attested final root for package `{package_id}` target `{target_name}` is not directly executable on this host"
1186    )]
1187    FinalRootNotHostExecutable {
1188        /// Exact Cargo package ID.
1189        package_id: String,
1190        /// Exact Cargo target name.
1191        target_name: String,
1192    },
1193    /// Cargo manifest paths must identify the test package directory.
1194    #[error("attested final root manifest has no parent directory: `{0}`")]
1195    FinalRootManifestWithoutParent(PathBuf),
1196    /// The attested executable could not be launched directly.
1197    #[error(
1198        "failed to execute attested final root `{path}` directly on this host: {source}; cargo-proa will not rerun Cargo target selection"
1199    )]
1200    ExecuteFinalRoot {
1201        /// Attested executable or test harness.
1202        path: PathBuf,
1203        /// Host spawn failure.
1204        #[source]
1205        source: std::io::Error,
1206    },
1207    /// User programs and test harnesses propagate a nonzero result.
1208    #[error("attested final root `{path}` exited unsuccessfully with {status}")]
1209    FinalRootExited {
1210        /// Attested executable or test harness.
1211        path: PathBuf,
1212        /// Exact host exit status.
1213        status: ExitStatus,
1214    },
1215    /// Caller-supplied artifact paths must be exact absolute Cargo paths.
1216    #[error("selected RSJS root artifact must be absolute: `{0}`")]
1217    RelativeRootArtifact(PathBuf),
1218    /// Caller-supplied root path was not in the matching Cargo message.
1219    #[error("selected RSJS root artifact was not enumerated by Cargo: `{0}`")]
1220    RootArtifactNotEnumerated(PathBuf),
1221    /// Cargo published no usable root artifact.
1222    #[error("selected RSJS root has no Cargo-enumerated artifact")]
1223    RootHasNoArtifact,
1224    /// Automatic root-filename selection is intentionally fail-closed.
1225    #[error(
1226        "selected RSJS root has {matches} Cargo-enumerated filenames; supply `artifact_path` exactly"
1227    )]
1228    AmbiguousRootArtifact {
1229        /// Candidate count.
1230        matches: usize,
1231    },
1232    /// Exact external root graph assembly failed.
1233    #[error("failed to assemble RSJS link manifest: {0}")]
1234    LinkManifest(#[source] LinkManifestAssemblyError),
1235    /// Object extraction/relocation resolution failed.
1236    #[error("failed to resolve RSJS transport records: {0}")]
1237    TransportLink(#[source] TransportLinkError),
1238    /// Legacy producer data could not become canonical ABI.
1239    #[error("failed to adapt RSJS descriptors: {0}")]
1240    AbiAdapter(#[source] AbiAdapterError),
1241    /// Canonical graph/owner linking failed.
1242    #[error("failed to link canonical RSJS plan: {0}")]
1243    SemanticLink(#[source] SemanticLinkError),
1244    /// Semantic plan persistence failed.
1245    #[error("failed to persist canonical RSJS plan: {0}")]
1246    WriteSemanticPlan(#[source] SemanticPlanWriteError),
1247    /// Plan-sensitive final compilation failed.
1248    #[error("RSJS final compilation failed")]
1249    FinalCargo(#[source] FinalCargoError),
1250}
1251
1252#[cfg(test)]
1253mod tests;