Skip to main content

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