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