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