Skip to main content

proa_cli/rsjs/
build.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Hidden building blocks for the RSJS descriptor compilation.
5//!
6//! This module intentionally does not drive the normal `proa build` command.
7//! It provides the rustc-wrapper half of a future two-compilation pipeline and
8//! a strict collector for the Cargo JSON produced by that pipeline.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::env;
12use std::ffi::{OsStr, OsString};
13use std::fmt::{self, Write as _};
14use std::fs::{self, File, OpenOptions};
15use std::io::{self, BufRead, BufReader, Read, Write};
16use std::path::{Path, PathBuf};
17use std::process::{Command, ExitStatus, Stdio};
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use rayon::prelude::*;
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23use sha2::{Digest, Sha256};
24use thiserror::Error;
25
26use rsjs_ir::abi::{CargoUnitId, InvocationId, PlanId, SemanticHash};
27use rsjs_ir::build::{ArtifactRole, LinkArtifact, LinkUnitDependency, LinkUnitManifest};
28
29/// Enables the hidden descriptor rustc-wrapper dispatch.
30pub const WRAPPER_MODE_ENV: &str = "PROA_RSJS_RUSTC_WRAPPER_MODE";
31/// The only wrapper protocol accepted by this version of the CLI.
32pub const WRAPPER_MODE_DESCRIPTOR_V1: &str = "descriptor-v1";
33/// Final-compilation wrapper protocol that restores descriptor Cargo-unit IDs.
34pub const WRAPPER_MODE_FINAL_V2: &str = "final-v2";
35/// Version of the wrapper-owned final rustc argument/environment policy.
36///
37/// This must change whenever wrapper behavior can affect rustc output without
38/// changing the exact plan or unit-map bytes.
39pub const FINAL_WRAPPER_POLICY_VERSION: u16 = 6;
40/// Filesystem/output policy for persistent descriptor Cargo targets.
41///
42/// This is deliberately independent of sidecar schema: bump it whenever a
43/// previous target may contain wrapper/proc-macro artifacts that must never
44/// participate in current build identity.
45pub const DESCRIPTOR_TARGET_POLICY_VERSION: u16 = 4;
46/// Explicit host-local staging directory for descriptor objects and sidecars.
47pub const DESCRIPTOR_STAGING_DIR_ENV: &str = "PROA_RSJS_DESCRIPTOR_STAGING_DIR";
48/// Exact runner-owned Cargo target directory for descriptor compilation.
49pub const DESCRIPTOR_TARGET_DIR_ENV: &str = "PROA_RSJS_DESCRIPTOR_TARGET_DIR";
50/// Exact generated subtree excluded from package-source closure hashing in
51/// both descriptor and final compilation.
52pub const SOURCE_EXCLUSION_DIR_ENV: &str = "PROA_RSJS_SOURCE_EXCLUSION_DIR";
53/// Exact invocation- and wrapper-policy-scoped final target owned by the
54/// final Cargo runner.
55pub const FINAL_TARGET_DIR_ENV: &str = "PROA_RSJS_FINAL_TARGET_DIR";
56/// Legacy proc-macro filesystem descriptor fallback; not identity-safe.
57pub const COMPONENT_DESCRIPTOR_DIRS_ENV: &str = "RSJS_COMPONENT_DESCRIPTOR_DIRS";
58pub(crate) const DESCRIPTOR_TARGET_MARKER_FILE: &str = ".proa-rsjs-descriptor-target-v1";
59pub(crate) const DESCRIPTOR_TARGET_MARKER_BYTES: &[u8] = b"proa-rsjs-descriptor-target-v1\n";
60pub(crate) const DESCRIPTOR_STAGING_MARKER_FILE: &str = ".proa-rsjs-descriptor-staging-v1";
61pub(crate) const DESCRIPTOR_STAGING_MARKER_BYTES: &[u8] = b"proa-rsjs-descriptor-staging-v1\n";
62const DESCRIPTOR_RECOVERY_ATTEMPTS_DIRECTORY: &str = ".proa-rsjs-recovery-attempts";
63const DESCRIPTOR_RECOVERY_ATTEMPT_PREFIX: &str = "attempt-";
64/// Exact content-addressed descriptor-to-final unit map.
65pub const FINAL_UNIT_MAP_PATH_ENV: &str = "PROA_RSJS_FINAL_UNIT_MAP_PATH";
66/// SHA-256 of the exact final unit-map bytes.
67pub const FINAL_UNIT_MAP_HASH_ENV: &str = "PROA_RSJS_FINAL_UNIT_MAP_HASH";
68/// Stable, lowercase-hex Cargo-unit identity exposed to RSJS proc macros.
69pub const CARGO_UNIT_ID_ENV: &str = "RSJS_CARGO_UNIT_ID";
70/// Explicit final-wrapper result visible to proc macros.
71pub const FINAL_CARGO_UNIT_STATUS_ENV: &str = "RSJS_FINAL_CARGO_UNIT_STATUS";
72/// The final rustc invocation matched exactly one descriptor unit.
73pub const FINAL_CARGO_UNIT_STATUS_MAPPED: &str = "mapped-v1";
74/// No descriptor unit matched; an RSJS macro must fail rather than guess.
75pub const FINAL_CARGO_UNIT_STATUS_UNMAPPED: &str = "unmapped-v1";
76/// Marks rustc as running the descriptor phase rather than final compilation.
77pub const DESCRIPTOR_PHASE_ENV: &str = "RSJS_DESCRIPTOR_PHASE";
78/// Schema version of [`DescriptorUnitSidecar`].
79pub const DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION: u16 = 10;
80/// Schema version of [`FinalUnitMap`].
81pub const FINAL_UNIT_MAP_SCHEMA_VERSION: u16 = 7;
82const FINAL_UNIT_MAP_FORMAT: &str = "proa.rsjs.final_unit_map";
83/// Marks rustc as running the linked final phase.
84pub const FINAL_PHASE_ENV: &str = "RSJS_FINAL_PHASE";
85/// Exact content-addressed link-plan path consumed by final macro expansion.
86pub const FINAL_PLAN_PATH_ENV: &str = "RSJS_LINK_PLAN_PATH";
87/// Lower-case hexadecimal strong plan identity.
88pub const FINAL_PLAN_ID_ENV: &str = "RSJS_PLAN_ID";
89/// Tagged SHA-256 digest of the exact linked-plan bytes.
90pub const FINAL_PLAN_FILE_HASH_ENV: &str = "RSJS_LINK_PLAN_FILE_HASH";
91const UNIT_HASH_DOMAIN: &[u8] = b"proa.rsjs.descriptor-cargo-unit.v3";
92const PROFILE_HASH_DOMAIN: &[u8] = b"proa.rsjs.final-match-profile.v1";
93const FILE_HASH_DOMAIN: &[u8] = b"proa.rsjs.descriptor-input-file.v1";
94const PACKAGE_SOURCE_CLOSURE_HASH_DOMAIN: &[u8] = b"proa.rsjs.package-source-closure.v4";
95const PACKAGE_SOURCE_FILE_HASH_DOMAIN: &[u8] = b"proa.rsjs.package-source-file.v1";
96const OUT_DIR_FILE_HASH_DOMAIN: &[u8] = b"proa.rsjs.out-dir-file.v1";
97const OBSERVED_SOURCE_FILE_HASH_DOMAIN: &[u8] = b"proa.rsjs.observed-source-file.v1";
98const OBSERVED_ENVIRONMENT_VALUE_HASH_DOMAIN: &[u8] = b"proa.rsjs.observed-environment-value.v1";
99const LOGICAL_ENVIRONMENT_HASH_DOMAIN: &[u8] = b"proa.rsjs.logical-environment.v2";
100const REALIZED_ENVIRONMENT_HASH_DOMAIN: &[u8] = b"proa.rsjs.realized-rustc-environment.v1";
101pub(crate) const DESCRIPTOR_OBJECT_HASH_DOMAIN: &[u8] = b"proa.rsjs.descriptor-object.v1";
102const LINK_ARTIFACT_HASH_DOMAIN: &[u8] = b"proa.rsjs.link-artifact.v1";
103const DESCRIPTOR_CODEGEN_POLICY: [&str; 4] = [
104    "codegen-units=1",
105    "incremental=disabled",
106    "link-dead-code=yes",
107    "lto=off",
108];
109const DESCRIPTOR_STRIP_POLICY: &str = "strip=none";
110
111static ATOMIC_WRITE_NONCE: AtomicU64 = AtomicU64::new(0);
112
113/// Return whether the process environment requests hidden wrapper dispatch.
114pub fn rustc_wrapper_dispatch_requested() -> bool {
115    env::var_os(WRAPPER_MODE_ENV).is_some()
116}
117
118/// Run one invocation received through Cargo's `RUSTC_WRAPPER` protocol.
119///
120/// Cargo invokes a wrapper as `wrapper rustc rustc-args...`. Probe invocations
121/// are forwarded byte-for-byte. Compilation invocations additionally emit one
122/// explicit descriptor object and one atomic unit sidecar.
123pub fn run_rustc_wrapper_from_env<I>(args: I) -> Result<ExitStatus, WrapperError>
124where
125    I: IntoIterator<Item = OsString>,
126{
127    let args = args.into_iter().collect::<Vec<_>>();
128    reject_composed_workspace_wrapper(&args)?;
129    let mode = env::var(WRAPPER_MODE_ENV)
130        .map_err(|_| WrapperError::MissingEnvironment(WRAPPER_MODE_ENV))?;
131    match mode.as_str() {
132        WRAPPER_MODE_DESCRIPTOR_V1 => {
133            let staging_dir = env::var_os(DESCRIPTOR_STAGING_DIR_ENV)
134                .map(PathBuf::from)
135                .ok_or(WrapperError::MissingEnvironment(DESCRIPTOR_STAGING_DIR_ENV))?;
136            if !staging_dir.is_absolute() {
137                return Err(WrapperError::RelativeStagingDirectory(staging_dir));
138            }
139            let target_dir = env::var_os(DESCRIPTOR_TARGET_DIR_ENV)
140                .map(PathBuf::from)
141                .ok_or(WrapperError::MissingEnvironment(DESCRIPTOR_TARGET_DIR_ENV))?;
142            if !target_dir.is_absolute() {
143                return Err(WrapperError::RelativeDescriptorTargetDirectory(target_dir));
144            }
145            let source_exclusion = env::var_os(SOURCE_EXCLUSION_DIR_ENV)
146                .map(PathBuf::from)
147                .ok_or(WrapperError::MissingEnvironment(SOURCE_EXCLUSION_DIR_ENV))?;
148            if !source_exclusion.is_absolute() {
149                return Err(WrapperError::RelativeSourceExclusionDirectory(
150                    source_exclusion,
151                ));
152            }
153            run_descriptor_rustc_wrapper(args, &staging_dir, &target_dir, &source_exclusion)
154        }
155        WRAPPER_MODE_FINAL_V2 => run_final_rustc_wrapper(args),
156        _ => Err(WrapperError::UnsupportedWrapperMode(mode)),
157    }
158}
159
160/// Cargo composes `RUSTC_WRAPPER` and `RUSTC_WORKSPACE_WRAPPER` as
161/// `outer-wrapper workspace-wrapper rustc rustc-args...`. Cargo configuration
162/// does not necessarily export the latter as an environment variable, so the
163/// runner's environment checks alone cannot detect this unsupported shape.
164fn reject_composed_workspace_wrapper(args: &[OsString]) -> Result<(), WrapperError> {
165    let Some(candidate_rustc_leader) = args.get(3) else {
166        return Ok(());
167    };
168    let Some(candidate_workspace_wrapper) = args.get(1) else {
169        return Ok(());
170    };
171    let Some(candidate_rustc) = args.get(2) else {
172        return Ok(());
173    };
174
175    if !is_cargo_rustc_argument_leader(candidate_rustc)
176        && is_cargo_rustc_argument_leader(candidate_rustc_leader)
177    {
178        return Err(WrapperError::ComposedWorkspaceWrapper {
179            wrapper: candidate_workspace_wrapper.clone(),
180            rustc: candidate_rustc.clone(),
181        });
182    }
183    Ok(())
184}
185
186fn is_cargo_rustc_argument_leader(argument: &OsStr) -> bool {
187    argument.to_str().is_some_and(|argument| {
188        argument == "-"
189            || matches!(
190                argument,
191                "-vV" | "-V" | "--version" | "--help" | "-h" | "--crate-name"
192            )
193            || argument.starts_with("--crate-name=")
194            || argument == "--print"
195            || argument.starts_with("--print=")
196    })
197}
198
199fn run_descriptor_rustc_wrapper<I>(
200    args: I,
201    staging_dir: &Path,
202    target_dir: &Path,
203    source_exclusion: &Path,
204) -> Result<ExitStatus, WrapperError>
205where
206    I: IntoIterator<Item = OsString>,
207{
208    let args = args.into_iter().collect::<Vec<_>>();
209    let rustc = args
210        .get(1)
211        .ok_or(WrapperError::MissingRustcProgram)?
212        .clone();
213    let rustc_args = args.get(2..).unwrap_or_default();
214
215    if is_rustc_probe(rustc_args) {
216        return wrapped_rustc_command(&rustc)
217            .args(rustc_args)
218            .status()
219            .map_err(|source| WrapperError::SpawnRustc {
220                program: PathBuf::from(rustc),
221                source,
222            });
223    }
224
225    let rustc_identity = query_rustc_identity(&rustc)?;
226    let environment = rustc_visible_environment()?;
227    let cargo_manifest_dir = match env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) {
228        Some(directory) if !directory.is_absolute() => {
229            return Err(WrapperError::RelativeCargoManifestDirectory(directory));
230        }
231        directory => directory,
232    };
233    let out_dir =
234        descriptor_out_dir_coordinate(target_dir, environment.get("OUT_DIR").map(String::as_str))?;
235    let input = normalize_rustc_invocation_with_package_root(
236        rustc_args,
237        &environment,
238        &rustc_identity,
239        cargo_manifest_dir.as_deref(),
240        Some(source_exclusion),
241    )?;
242    let cargo_extra_filename =
243        input
244            .cargo_extra_filename()
245            .map_err(|reason| WrapperError::InvalidCargoExtraFilename {
246                context: "descriptor rustc invocation",
247                value: input
248                    .codegen_options
249                    .get("extra-filename")
250                    .cloned()
251                    .unwrap_or_default(),
252                reason,
253            })?;
254    let cargo_unit_id = input.cargo_unit_id();
255    let cargo_unit_id_hex = cargo_unit_id.to_string();
256    let dep_info_path = rustc_dep_info_path(rustc_args, &input)?;
257
258    let objects_dir = staging_dir.join("objects");
259    let units_dir = staging_dir.join("units");
260    fs::create_dir_all(&objects_dir).map_err(|source| WrapperError::CreateStagingDirectory {
261        path: objects_dir.clone(),
262        source,
263    })?;
264    fs::create_dir_all(&units_dir).map_err(|source| WrapperError::CreateStagingDirectory {
265        path: units_dir.clone(),
266        source,
267    })?;
268
269    let object_file_name = format!("{cargo_unit_id_hex}.o");
270    let object_path = objects_dir.join(&object_file_name);
271    let forwarded_args = descriptor_rustc_args(rustc_args, &object_path)?;
272    validate_dep_info_output_path(target_dir, &dep_info_path)?;
273    prepare_dep_info_output(&dep_info_path)?;
274
275    let status = wrapped_rustc_command(&rustc)
276        .args(&forwarded_args)
277        .env(CARGO_UNIT_ID_ENV, &cargo_unit_id_hex)
278        .env(DESCRIPTOR_PHASE_ENV, "1")
279        .status()
280        .map_err(|source| WrapperError::SpawnRustc {
281            program: PathBuf::from(&rustc),
282            source,
283        })?;
284
285    if !status.success() {
286        return Ok(status);
287    }
288    if !object_path.is_file() {
289        return Err(WrapperError::MissingDescriptorObject(object_path));
290    }
291
292    let dep_info_working_directory =
293        canonical_plain_directory(&env::current_dir().map_err(WrapperError::CurrentDirectory)?)?;
294    let mut descriptor_phase_environment = BTreeMap::new();
295    descriptor_phase_environment.insert(
296        CARGO_UNIT_ID_ENV.to_string(),
297        Some(cargo_unit_id_hex.clone()),
298    );
299    descriptor_phase_environment.insert(DESCRIPTOR_PHASE_ENV.to_string(), Some("1".to_string()));
300    let observed = observe_rustc_inputs(
301        &dep_info_path,
302        &dep_info_working_directory,
303        environment.get("OUT_DIR").map(Path::new),
304        out_dir.as_deref(),
305        &descriptor_phase_environment,
306    )?;
307    let dep_info_coordinate = target_relative_dep_info_path(target_dir, &dep_info_path)?;
308
309    let descriptor_object_hash =
310        hash_file(&object_path, DESCRIPTOR_OBJECT_HASH_DOMAIN).map_err(|source| {
311            WrapperError::HashInput {
312                path: object_path.clone(),
313                source,
314            }
315        })?;
316    let sidecar = DescriptorUnitSidecar {
317        schema_version: DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION,
318        cargo_unit_id: cargo_unit_id_hex.clone(),
319        cargo_manifest_path: cargo_manifest_dir.map(|directory| directory.join("Cargo.toml")),
320        cargo_package_name: env::var("CARGO_PKG_NAME").ok(),
321        cargo_package_version: env::var("CARGO_PKG_VERSION").ok(),
322        cargo_profile: env::var("PROFILE").ok(),
323        cargo_profile_fingerprint: hex_digest(&input.final_match_profile_hash()),
324        cargo_primary_package: env::var_os("CARGO_PRIMARY_PACKAGE").is_some(),
325        cargo_extra_filename,
326        crate_name: input.crate_name.clone(),
327        crate_types: input.crate_types.iter().cloned().collect(),
328        target: input.target.clone(),
329        cfgs: input.cfgs.iter().cloned().collect(),
330        features: input.features.iter().cloned().collect(),
331        source_hash: hex_digest(&input.source_hash),
332        package_source_closure_hash: hex_digest(&input.package_source_closure_hash),
333        dependency_artifacts: input
334            .dependencies
335            .iter()
336            .map(|(name, digest)| {
337                let path = input
338                    .dependency_paths
339                    .get(name)
340                    .expect("every normalized dependency retains its exact input path");
341                (
342                    name.clone(),
343                    DescriptorDependencyArtifact {
344                        path: path.clone(),
345                        content_hash: hex_digest(digest),
346                    },
347                )
348            })
349            .collect(),
350        normalized_rustc_inputs_hash: hex_digest(&input.normalized_inputs_hash()),
351        logical_environment_hash: hex_digest(&input.logical_environment_hash()),
352        dep_info_path: dep_info_coordinate,
353        dep_info_working_directory,
354        out_dir,
355        out_dir_dependencies: observed.out_dir_dependencies,
356        source_dependencies: observed.source_dependencies,
357        environment_dependencies: observed.environment_dependencies,
358        realized_environment_hash: hex_digest(&realized_environment_hash(&environment)),
359        descriptor_codegen: DescriptorCodegenSidecar {
360            codegen_units: 1,
361            incremental: false,
362            link_dead_code: true,
363            lto: "off".to_string(),
364            strip: "none".to_string(),
365        },
366        descriptor_object: format!("objects/{object_file_name}"),
367        descriptor_object_hash: hex_digest(&descriptor_object_hash),
368    };
369    let sidecar_bytes =
370        serde_json::to_vec_pretty(&sidecar).map_err(WrapperError::SerializeUnitSidecar)?;
371    let sidecar_path = units_dir.join(format!("{cargo_unit_id_hex}.json"));
372    atomic_write(&sidecar_path, &sidecar_bytes)?;
373
374    Ok(status)
375}
376
377fn run_final_rustc_wrapper<I>(args: I) -> Result<ExitStatus, WrapperError>
378where
379    I: IntoIterator<Item = OsString>,
380{
381    let args = args.into_iter().collect::<Vec<_>>();
382    let rustc = args
383        .get(1)
384        .ok_or(WrapperError::MissingRustcProgram)?
385        .clone();
386    let rustc_args = args.get(2..).unwrap_or_default();
387
388    if is_rustc_probe(rustc_args) {
389        return wrapped_rustc_command(&rustc)
390            .args(rustc_args)
391            .status()
392            .map_err(|source| WrapperError::SpawnRustc {
393                program: PathBuf::from(rustc),
394                source,
395            });
396    }
397
398    let unit_map = load_final_unit_map_from_env()?;
399    let final_target = env::var_os(FINAL_TARGET_DIR_ENV)
400        .map(PathBuf::from)
401        .ok_or(WrapperError::MissingEnvironment(FINAL_TARGET_DIR_ENV))?;
402    let final_out_dir_raw = env::var_os("OUT_DIR").map(PathBuf::from);
403    let final_out_dir = validate_final_out_dir(&final_target, final_out_dir_raw.as_deref())?;
404    let final_out_dir_coordinate =
405        final_out_dir_coordinate(&final_target, final_out_dir_raw.as_deref())?;
406    // Derive the join coordinate from Cargo's untouched invocation first.
407    // Plan-sensitive RSJS expansions emit built-in `env!` dependencies for
408    // the plan and unit-map fingerprints. Cargo therefore invalidates those
409    // units before this wrapper runs while retaining unrelated artifacts in
410    // the stable final target. Keeping the invariant final cfgs out of Cargo's
411    // RUSTFLAGS preserves Cargo's metadata/extra-filename discriminator across
412    // the descriptor and final phases.
413    let invocation = final_unit_coordinate_from_invocation(rustc_args)?;
414    let final_plan_args = final_plan_rustc_args_from_env()?;
415    let final_child_environment = final_child_environment_from_env()?;
416    let mapped = unit_map.resolve(invocation.as_ref().map(|value| &value.coordinate));
417    let final_visible_environment = rustc_visible_environment()?;
418    let mut final_phase_environment = BTreeMap::<String, Option<String>>::new();
419    for (name, value) in &final_child_environment {
420        let value = value
421            .to_str()
422            .ok_or(WrapperError::NonUtf8PhaseOwnedEnvironment(name))?;
423        final_phase_environment.insert((*name).to_string(), Some(value.to_string()));
424    }
425    if let Some(mapped) = mapped {
426        final_phase_environment.insert(
427            CARGO_UNIT_ID_ENV.to_string(),
428            Some(mapped.cargo_unit_id.to_string()),
429        );
430        final_phase_environment.insert(
431            FINAL_CARGO_UNIT_STATUS_ENV.to_string(),
432            Some(FINAL_CARGO_UNIT_STATUS_MAPPED.to_string()),
433        );
434    } else {
435        final_phase_environment.insert(
436            FINAL_CARGO_UNIT_STATUS_ENV.to_string(),
437            Some(FINAL_CARGO_UNIT_STATUS_UNMAPPED.to_string()),
438        );
439    }
440    let dep_info_path = invocation
441        .as_ref()
442        .map(|value| rustc_dep_info_path(rustc_args, &value.input))
443        .transpose()?;
444    if let Some(mapped) = mapped {
445        validate_current_out_dir_dependencies(
446            final_out_dir.as_deref(),
447            &mapped.out_dir_dependencies,
448        )?;
449        validate_current_source_dependencies(&mapped.source_dependencies)?;
450        validate_current_environment_dependencies(
451            &final_visible_environment,
452            final_out_dir_raw.as_deref(),
453            final_out_dir_coordinate.as_deref(),
454            &mapped.environment_dependencies,
455        )?;
456    }
457    if let Some(dep_info_path) = dep_info_path.as_deref() {
458        validate_dep_info_output_path(&final_target, dep_info_path)?;
459        prepare_dep_info_output(dep_info_path)?;
460    }
461
462    let mut command = wrapped_rustc_command(&rustc);
463    command
464        .args(rustc_args)
465        .args(final_plan_args)
466        .envs(&final_child_environment)
467        .env_remove(DESCRIPTOR_PHASE_ENV)
468        .env_remove(CARGO_UNIT_ID_ENV);
469    if let Some(mapped) = mapped {
470        command
471            .env(CARGO_UNIT_ID_ENV, mapped.cargo_unit_id.to_string())
472            .env(FINAL_CARGO_UNIT_STATUS_ENV, FINAL_CARGO_UNIT_STATUS_MAPPED);
473    } else {
474        command.env(
475            FINAL_CARGO_UNIT_STATUS_ENV,
476            FINAL_CARGO_UNIT_STATUS_UNMAPPED,
477        );
478    }
479    let status = command
480        .status()
481        .map_err(|source| WrapperError::SpawnRustc {
482            program: PathBuf::from(rustc),
483            source,
484        })?;
485    if status.success() {
486        if let (Some(mapped), Some(dep_info_path)) = (mapped, dep_info_path.as_deref()) {
487            let working_directory = canonical_plain_directory(
488                &env::current_dir().map_err(WrapperError::CurrentDirectory)?,
489            )?;
490            let actual = observe_rustc_inputs(
491                dep_info_path,
492                &working_directory,
493                final_out_dir_raw.as_deref(),
494                final_out_dir_coordinate.as_deref(),
495                &final_phase_environment,
496            )?;
497            if actual.out_dir_dependencies != mapped.out_dir_dependencies {
498                return Err(WrapperError::FinalOutDirDependencySetMismatch {
499                    expected: mapped.out_dir_dependencies.clone(),
500                    actual: actual.out_dir_dependencies,
501                });
502            }
503            if actual.source_dependencies != mapped.source_dependencies
504                && !source_dependency_sets_equivalent(
505                    &mapped.source_dependencies,
506                    &actual.source_dependencies,
507                )
508            {
509                return Err(WrapperError::FinalSourceDependencySetMismatch {
510                    expected: mapped.source_dependencies.clone(),
511                    actual: actual.source_dependencies,
512                });
513            }
514            if actual.environment_dependencies != mapped.environment_dependencies {
515                return Err(WrapperError::FinalEnvironmentDependencySetMismatch {
516                    expected: mapped.environment_dependencies.clone(),
517                    actual: actual.environment_dependencies,
518                });
519            }
520        }
521    }
522    Ok(status)
523}
524
525const FINAL_CHILD_ENVIRONMENT: [&str; 5] = [
526    FINAL_PHASE_ENV,
527    FINAL_PLAN_PATH_ENV,
528    FINAL_PLAN_ID_ENV,
529    FINAL_PLAN_FILE_HASH_ENV,
530    FINAL_UNIT_MAP_HASH_ENV,
531];
532
533fn final_child_environment_from_env() -> Result<BTreeMap<&'static str, OsString>, WrapperError> {
534    let mut environment = BTreeMap::new();
535    for name in FINAL_CHILD_ENVIRONMENT {
536        let value = env::var_os(name).ok_or(WrapperError::MissingEnvironment(name))?;
537        environment.insert(name, value);
538    }
539    if environment.get(FINAL_PHASE_ENV).map(OsString::as_os_str) != Some(OsStr::new("1")) {
540        return Err(WrapperError::InvalidFinalPhase);
541    }
542    let plan_path = PathBuf::from(
543        environment
544            .get(FINAL_PLAN_PATH_ENV)
545            .expect("the required final plan path was collected")
546            .as_os_str(),
547    );
548    if !plan_path.is_absolute() {
549        return Err(WrapperError::RelativeFinalPlan(plan_path));
550    }
551    Ok(environment)
552}
553
554fn final_plan_rustc_args_from_env() -> Result<Vec<OsString>, WrapperError> {
555    let plan_id = env::var(FINAL_PLAN_ID_ENV)
556        .map_err(|_| WrapperError::MissingEnvironment(FINAL_PLAN_ID_ENV))?;
557    validate_lower_sha256(&plan_id).map_err(|reason| WrapperError::InvalidSha256 {
558        name: FINAL_PLAN_ID_ENV,
559        value: plan_id.clone(),
560        reason,
561    })?;
562    let plan_file_hash = env::var(FINAL_PLAN_FILE_HASH_ENV)
563        .map_err(|_| WrapperError::MissingEnvironment(FINAL_PLAN_FILE_HASH_ENV))?;
564    validate_tagged_sha256(&plan_file_hash).map_err(|reason| WrapperError::InvalidSha256 {
565        name: FINAL_PLAN_FILE_HASH_ENV,
566        value: plan_file_hash.clone(),
567        reason,
568    })?;
569    let unit_map_hash = env::var(FINAL_UNIT_MAP_HASH_ENV)
570        .map_err(|_| WrapperError::MissingEnvironment(FINAL_UNIT_MAP_HASH_ENV))?;
571    validate_lower_sha256(&unit_map_hash).map_err(|reason| WrapperError::InvalidSha256 {
572        name: FINAL_UNIT_MAP_HASH_ENV,
573        value: unit_map_hash.clone(),
574        reason,
575    })?;
576
577    Ok(final_plan_rustc_args(
578        &plan_id,
579        &plan_file_hash,
580        &unit_map_hash,
581    ))
582}
583
584fn final_plan_rustc_args(
585    _plan_id: &str,
586    _plan_file_hash: &str,
587    _unit_map_hash: &str,
588) -> Vec<OsString> {
589    [
590        "--cfg".to_string(),
591        "rsjs_final".to_string(),
592        "--cfg".to_string(),
593        format!("rsjs_final_wrapper_policy=\"{FINAL_WRAPPER_POLICY_VERSION}\""),
594        "--check-cfg".to_string(),
595        "cfg(rsjs_final)".to_string(),
596        "--check-cfg".to_string(),
597        format!("cfg(rsjs_final_wrapper_policy,values(\"{FINAL_WRAPPER_POLICY_VERSION}\"))"),
598    ]
599    .into_iter()
600    .map(OsString::from)
601    .collect()
602}
603
604fn wrapped_rustc_command(rustc: &OsStr) -> Command {
605    let mut command = Command::new(rustc);
606    scrub_wrapper_control_environment(&mut command);
607    command
608}
609
610fn is_rustc_probe(args: &[OsString]) -> bool {
611    if args.len() == 1 {
612        let argument = args[0].to_string_lossy();
613        if matches!(
614            argument.as_ref(),
615            "-vV" | "-V" | "--version" | "--help" | "-h"
616        ) {
617            return true;
618        }
619    }
620
621    let mut prints = Vec::new();
622    let mut positional = Vec::new();
623    let mut index = 0;
624    while index < args.len() {
625        let argument = args[index].to_string_lossy();
626        if argument == "--emit" || argument.starts_with("--emit=") {
627            return false;
628        }
629        if argument == "--print" {
630            index += 1;
631            let Some(value) = args.get(index).and_then(|value| value.to_str()) else {
632                return false;
633            };
634            prints.push(value.to_string());
635        } else if let Some(value) = argument.strip_prefix("--print=") {
636            prints.push(value.to_string());
637        } else if rustc_probe_option_consumes_next(&argument) {
638            index += 1;
639            if args.get(index).is_none() {
640                return false;
641            }
642        } else if argument == "-" || !argument.starts_with('-') {
643            positional.push(argument.to_string());
644        }
645        index += 1;
646    }
647
648    !prints.is_empty()
649        && prints.iter().all(|value| {
650            matches!(
651                value.split('=').next().unwrap_or_default(),
652                "calling-conventions"
653                    | "all-target-specs-json"
654                    | "cfg"
655                    | "check-cfg"
656                    | "code-models"
657                    | "crate-name"
658                    | "deployment-target"
659                    | "file-names"
660                    | "host-tuple"
661                    | "relocation-models"
662                    | "split-debuginfo"
663                    | "stack-protector-strategies"
664                    | "sysroot"
665                    | "target-cpus"
666                    | "target-features"
667                    | "target-libdir"
668                    | "target-list"
669                    | "target-spec-json"
670                    | "target-spec-json-schema"
671                    | "tls-models"
672            )
673        })
674        && positional.iter().all(|argument| argument == "-")
675}
676
677fn rustc_probe_option_consumes_next(argument: &str) -> bool {
678    matches!(
679        argument,
680        "--cap-lints"
681            | "--cfg"
682            | "--check-cfg"
683            | "--color"
684            | "--crate-attr"
685            | "--crate-name"
686            | "--crate-type"
687            | "--diagnostic-width"
688            | "--edition"
689            | "--error-format"
690            | "--extern"
691            | "--json"
692            | "--out-dir"
693            | "--remap-path-prefix"
694            | "--remap-path-scope"
695            | "--sysroot"
696            | "--target"
697            | "-C"
698            | "-L"
699            | "-Z"
700            | "-l"
701            | "-o"
702    )
703}
704
705fn query_rustc_identity(rustc: &OsStr) -> Result<Vec<u8>, WrapperError> {
706    let output =
707        Command::new(rustc)
708            .arg("-vV")
709            .output()
710            .map_err(|source| WrapperError::SpawnRustc {
711                program: PathBuf::from(rustc),
712                source,
713            })?;
714    if !output.status.success() {
715        return Err(WrapperError::RustcIdentityFailed {
716            program: PathBuf::from(rustc),
717            status: output.status,
718        });
719    }
720    Ok(output.stdout)
721}
722
723fn rustc_visible_environment() -> Result<BTreeMap<String, String>, WrapperError> {
724    let mut environment = BTreeMap::new();
725    for (name, value) in env::vars_os() {
726        let name = name
727            .into_string()
728            .map_err(WrapperError::NonUtf8EnvironmentName)?;
729        if wrapper_control_environment(&name) {
730            continue;
731        }
732        let value = value
733            .into_string()
734            .map_err(|value| WrapperError::NonUtf8EnvironmentValue {
735                name: name.clone(),
736                value,
737            })?;
738        environment.insert(name, value);
739    }
740    Ok(environment)
741}
742
743const WRAPPER_CONTROL_ENVIRONMENT: [&str; 16] = [
744    WRAPPER_MODE_ENV,
745    DESCRIPTOR_STAGING_DIR_ENV,
746    DESCRIPTOR_TARGET_DIR_ENV,
747    SOURCE_EXCLUSION_DIR_ENV,
748    FINAL_TARGET_DIR_ENV,
749    FINAL_UNIT_MAP_PATH_ENV,
750    FINAL_UNIT_MAP_HASH_ENV,
751    CARGO_UNIT_ID_ENV,
752    FINAL_CARGO_UNIT_STATUS_ENV,
753    DESCRIPTOR_PHASE_ENV,
754    FINAL_PHASE_ENV,
755    FINAL_PLAN_PATH_ENV,
756    FINAL_PLAN_ID_ENV,
757    FINAL_PLAN_FILE_HASH_ENV,
758    "RUSTC_WRAPPER",
759    "RUSTC_WORKSPACE_WRAPPER",
760];
761
762pub(crate) fn wrapper_control_environment(name: &str) -> bool {
763    WRAPPER_CONTROL_ENVIRONMENT.contains(&name)
764}
765
766pub(crate) fn scrub_wrapper_control_environment(command: &mut Command) {
767    for name in WRAPPER_CONTROL_ENVIRONMENT {
768        command.env_remove(name);
769    }
770}
771
772/// Cargo/rustc environment with stable compile-time meaning.
773///
774/// This is deliberately an allowlist. Cargo injects target-directory-specific
775/// variables such as `CARGO_TARGET_TMPDIR` and `CARGO_BIN_EXE_*`, while the
776/// surrounding shell contributes arbitrary host/process state. Neither may
777/// make a reusable unit ID depend on which Cargo process happened to run it.
778/// Arbitrarily named build-script `cargo::rustc-env` values are recovered from
779/// Cargo's exact build-script output below and added independently.
780fn cargo_semantic_rustc_environment(name: &str) -> bool {
781    matches!(
782        name,
783        "HOST"
784            | "TARGET"
785            | "PROFILE"
786            | "OPT_LEVEL"
787            | "DEBUG"
788            | "CARGO_CRATE_NAME"
789            | "CARGO_BIN_NAME"
790            | "CARGO_PRIMARY_PACKAGE"
791            | "CARGO_MANIFEST_LINKS"
792    ) || name.starts_with("CARGO_PKG_")
793        || name.starts_with("CARGO_CFG_")
794        || name.starts_with("CARGO_FEATURE_")
795}
796
797fn identity_rustc_environment(
798    environment: &BTreeMap<String, String>,
799) -> io::Result<BTreeMap<String, String>> {
800    let mut identity = environment
801        .iter()
802        .filter(|(name, _)| cargo_semantic_rustc_environment(name))
803        .map(|(name, value)| (name.clone(), value.clone()))
804        .collect::<BTreeMap<_, _>>();
805
806    let Some(out_dir) = environment.get("OUT_DIR") else {
807        return Ok(identity);
808    };
809    for name in build_script_rustc_env_names(Path::new(out_dir))? {
810        let value = environment.get(&name).ok_or_else(|| {
811            io::Error::new(
812                io::ErrorKind::InvalidData,
813                format!(
814                    "Cargo build-script output declared rustc-env `{name}`, but rustc did not receive it"
815                ),
816            )
817        })?;
818        identity.insert(name, value.clone());
819    }
820    Ok(identity)
821}
822
823fn build_script_rustc_env_names(out_dir: &Path) -> io::Result<BTreeSet<String>> {
824    let parent = out_dir.parent().ok_or_else(|| {
825        io::Error::new(
826            io::ErrorKind::InvalidInput,
827            "Cargo OUT_DIR has no build-script output directory",
828        )
829    })?;
830    let output_path = parent.join("output");
831    let output = fs::read_to_string(&output_path)?;
832    let mut names = BTreeSet::new();
833    for line in output.lines() {
834        let directive = line
835            .strip_prefix("cargo::rustc-env=")
836            .or_else(|| line.strip_prefix("cargo:rustc-env="));
837        let Some(directive) = directive else {
838            continue;
839        };
840        let (name, _) = directive.split_once('=').ok_or_else(|| {
841            io::Error::new(
842                io::ErrorKind::InvalidData,
843                format!(
844                    "Cargo build-script output `{}` contains malformed rustc-env directive `{line}`",
845                    output_path.display()
846                ),
847            )
848        })?;
849        if name.is_empty() || name.bytes().any(|byte| byte == 0 || byte == b'=') {
850            return Err(io::Error::new(
851                io::ErrorKind::InvalidData,
852                format!(
853                    "Cargo build-script output `{}` contains invalid rustc-env name `{name}`",
854                    output_path.display()
855                ),
856            ));
857        }
858        names.insert(name.to_string());
859    }
860    Ok(names)
861}
862
863fn realized_environment_hash(environment: &BTreeMap<String, String>) -> [u8; 32] {
864    hash_canonical(REALIZED_ENVIRONMENT_HASH_DOMAIN, |hash| {
865        hash.map("environment", environment);
866    })
867}
868
869/// Stable 32-byte descriptor Cargo-unit identity.
870#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
871pub struct DescriptorCargoUnitId([u8; 32]);
872
873impl DescriptorCargoUnitId {
874    /// Return the raw identifier bytes supplied to transport producers.
875    pub const fn as_bytes(&self) -> &[u8; 32] {
876        &self.0
877    }
878
879    /// Convert the realized wrapper identity into the compiler ABI's strong
880    /// Cargo-unit ID type.
881    pub const fn as_abi_id(&self) -> CargoUnitId {
882        CargoUnitId::from_bytes(self.0)
883    }
884
885    /// Parse the exact lowercase-hex representation written to sidecars.
886    pub fn from_hex(encoded: &str) -> Result<Self, WrapperError> {
887        if encoded.len() != 64 {
888            return Err(WrapperError::InvalidCargoUnitId {
889                value: encoded.to_string(),
890                reason: format!(
891                    "expected 64 lowercase hexadecimal characters, got {}",
892                    encoded.len()
893                ),
894            });
895        }
896        let mut bytes = [0_u8; 32];
897        for (index, output) in bytes.iter_mut().enumerate() {
898            let high_offset = index * 2;
899            let low_offset = high_offset + 1;
900            let high = decode_lower_hex(encoded.as_bytes()[high_offset]).ok_or_else(|| {
901                WrapperError::InvalidCargoUnitId {
902                    value: encoded.to_string(),
903                    reason: format!("invalid byte at offset {high_offset}"),
904                }
905            })?;
906            let low = decode_lower_hex(encoded.as_bytes()[low_offset]).ok_or_else(|| {
907                WrapperError::InvalidCargoUnitId {
908                    value: encoded.to_string(),
909                    reason: format!("invalid byte at offset {low_offset}"),
910                }
911            })?;
912            *output = (high << 4) | low;
913        }
914        Ok(Self(bytes))
915    }
916}
917
918fn decode_lower_hex(byte: u8) -> Option<u8> {
919    match byte {
920        b'0'..=b'9' => Some(byte - b'0'),
921        b'a'..=b'f' => Some(byte - b'a' + 10),
922        _ => None,
923    }
924}
925
926impl fmt::Debug for DescriptorCargoUnitId {
927    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
928        write!(formatter, "DescriptorCargoUnitId({self})")
929    }
930}
931
932impl fmt::Display for DescriptorCargoUnitId {
933    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
934        formatter.write_str(&hex_digest(&self.0))
935    }
936}
937
938/// Path-free semantic inputs plus host-local join coordinates for one
939/// descriptor-phase rustc unit.
940///
941/// Dependency paths never enter [`DescriptorCargoUnitId`]; only their exact
942/// content digests do. The paths are retained solely so the root assembler can
943/// join each rustc input to Cargo's same-invocation artifact enumeration
944/// without scanning or hashing unrelated outputs.
945#[derive(Clone, Debug, PartialEq, Eq)]
946pub struct NormalizedRustcInvocation {
947    crate_name: String,
948    crate_types: BTreeSet<String>,
949    target: Option<String>,
950    edition: Option<String>,
951    cfgs: BTreeSet<String>,
952    features: BTreeSet<String>,
953    emits: BTreeSet<String>,
954    semantic_options: BTreeMap<String, String>,
955    codegen_options: BTreeMap<String, String>,
956    unstable_options: BTreeMap<String, String>,
957    native_libraries: BTreeSet<String>,
958    /// Exact rustc-visible values. These remain process-local and contribute
959    /// only through the unit digest; sidecars never persist the plaintext.
960    environment: BTreeMap<String, String>,
961    rustc_identity_hash: [u8; 32],
962    source_hash: [u8; 32],
963    package_source_closure_hash: [u8; 32],
964    dependencies: BTreeMap<String, [u8; 32]>,
965    dependency_paths: BTreeMap<String, PathBuf>,
966}
967
968impl NormalizedRustcInvocation {
969    fn cargo_extra_filename(&self) -> Result<Option<String>, String> {
970        self.codegen_options
971            .get("extra-filename")
972            .map(|value| {
973                validate_cargo_extra_filename(value)?;
974                Ok(value.clone())
975            })
976            .transpose()
977    }
978
979    /// Derive the stable Cargo-unit ID for this descriptor compilation.
980    pub fn cargo_unit_id(&self) -> DescriptorCargoUnitId {
981        DescriptorCargoUnitId(hash_canonical(UNIT_HASH_DOMAIN, |hash| {
982            hash.field("crate_name", self.crate_name.as_bytes());
983            hash.set("crate_types", self.crate_types.iter().map(String::as_bytes));
984            hash.optional("target", self.target.as_deref().map(str::as_bytes));
985            hash.optional("edition", self.edition.as_deref().map(str::as_bytes));
986            hash.set("cfgs", self.cfgs.iter().map(String::as_bytes));
987            hash.set("features", self.features.iter().map(String::as_bytes));
988            hash.set("emits", self.emits.iter().map(String::as_bytes));
989            hash.map("semantic_options", &self.semantic_options);
990            hash.map("codegen_options", &self.codegen_options);
991            hash.map("unstable_options", &self.unstable_options);
992            hash.set(
993                "native_libraries",
994                self.native_libraries.iter().map(String::as_bytes),
995            );
996            hash.map("environment", &self.environment);
997            hash.field("rustc_identity_hash", &self.rustc_identity_hash);
998            hash.field("source_hash", &self.source_hash);
999            hash.field(
1000                "package_source_closure_hash",
1001                &self.package_source_closure_hash,
1002            );
1003            hash.digest_map("dependencies", &self.dependencies);
1004            hash.set(
1005                "descriptor_codegen",
1006                DESCRIPTOR_CODEGEN_POLICY
1007                    .iter()
1008                    .map(|value| value.as_bytes()),
1009            );
1010            hash.field("descriptor_strip", DESCRIPTOR_STRIP_POLICY.as_bytes());
1011        }))
1012    }
1013
1014    fn normalized_inputs_hash(&self) -> [u8; 32] {
1015        self.cargo_unit_id().0
1016    }
1017
1018    fn logical_environment_hash(&self) -> [u8; 32] {
1019        hash_canonical(LOGICAL_ENVIRONMENT_HASH_DOMAIN, |hash| {
1020            hash.map("environment", &self.environment);
1021        })
1022    }
1023
1024    fn final_match_profile_hash(&self) -> [u8; 32] {
1025        let profile_codegen_options = self
1026            .codegen_options
1027            .iter()
1028            .filter(|(name, _)| !matches!(name.as_str(), "metadata" | "extra-filename"))
1029            .map(|(name, value)| (name.clone(), value.clone()))
1030            .collect::<BTreeMap<_, _>>();
1031        let profile_environment = self
1032            .environment
1033            .iter()
1034            .filter(|(name, _)| matches!(name.as_str(), "PROFILE" | "DEBUG" | "OPT_LEVEL"))
1035            .map(|(name, value)| (name.clone(), value.clone()))
1036            .collect::<BTreeMap<_, _>>();
1037        hash_canonical(PROFILE_HASH_DOMAIN, |hash| {
1038            hash.map("codegen_options", &profile_codegen_options);
1039            hash.map("unstable_options", &self.unstable_options);
1040            hash.map("semantic_options", &self.semantic_options);
1041            hash.map("cargo_profile_environment", &profile_environment);
1042        })
1043    }
1044}
1045
1046/// Normalize one rustc invocation without admitting host-local source,
1047/// dependency, output, sysroot, or linker paths into semantic identity.
1048///
1049/// Exact dependency paths are retained as non-semantic Cargo join coordinates.
1050pub fn normalize_rustc_invocation(
1051    args: &[OsString],
1052    environment: &BTreeMap<String, String>,
1053    rustc_identity: &[u8],
1054) -> Result<NormalizedRustcInvocation, WrapperError> {
1055    normalize_rustc_invocation_with_package_root(args, environment, rustc_identity, None, None)
1056}
1057
1058/// Normalize one rustc invocation and bind it to the complete regular-file
1059/// closure beneath an explicit Cargo package root.
1060///
1061/// Cargo's wrappers call this form with `CARGO_MANIFEST_DIR`. The public
1062/// path-only normalizer above retains a crate-root-only fallback for direct
1063/// rustc fixtures and non-Cargo callers that have no package provenance.
1064fn normalize_rustc_invocation_with_package_root(
1065    args: &[OsString],
1066    environment: &BTreeMap<String, String>,
1067    rustc_identity: &[u8],
1068    package_root: Option<&Path>,
1069    excluded_source_subtree: Option<&Path>,
1070) -> Result<NormalizedRustcInvocation, WrapperError> {
1071    let args = args
1072        .iter()
1073        .map(|arg| {
1074            arg.to_str()
1075                .map(str::to_owned)
1076                .ok_or_else(|| WrapperError::NonUtf8RustcArgument(arg.clone()))
1077        })
1078        .collect::<Result<Vec<_>, _>>()?;
1079
1080    let mut crate_name = None;
1081    let mut crate_types = BTreeSet::new();
1082    let mut target = None;
1083    let mut edition = None;
1084    let mut cfgs = BTreeSet::new();
1085    let mut emits = BTreeSet::new();
1086    let mut semantic_options = BTreeMap::new();
1087    let mut codegen_options = BTreeMap::new();
1088    let mut unstable_options = BTreeMap::new();
1089    let mut native_libraries = BTreeSet::new();
1090    let mut dependencies = BTreeMap::new();
1091    let mut dependency_paths = BTreeMap::new();
1092    let mut source_hash = None;
1093    let mut index = 0;
1094
1095    while index < args.len() {
1096        let argument = &args[index];
1097
1098        if let Some(value) = long_option_value(&args, &mut index, "--crate-name")? {
1099            crate_name = Some(value);
1100        } else if let Some(value) = long_option_value(&args, &mut index, "--crate-type")? {
1101            crate_types.extend(split_comma_values(&value));
1102        } else if let Some(value) = long_option_value(&args, &mut index, "--target")? {
1103            target = Some(value);
1104        } else if let Some(value) = long_option_value(&args, &mut index, "--edition")? {
1105            edition = Some(value);
1106        } else if let Some(value) = long_option_value(&args, &mut index, "--cfg")? {
1107            cfgs.insert(value);
1108        } else if let Some(value) = long_option_value(&args, &mut index, "--emit")? {
1109            for emit in split_comma_values(&value) {
1110                let kind = emit.split_once('=').map_or(emit.as_str(), |(kind, _)| kind);
1111                emits.insert(kind.to_string());
1112            }
1113        } else if let Some(value) = long_option_value(&args, &mut index, "--extern")? {
1114            let (name, path) = parse_extern(&value)?;
1115            match path {
1116                Some(path) => {
1117                    if !path.is_absolute() {
1118                        return Err(WrapperError::RelativeExternArtifact(path));
1119                    }
1120                    let digest = hash_file(&path, FILE_HASH_DOMAIN).map_err(|source| {
1121                        WrapperError::HashInput {
1122                            path: path.clone(),
1123                            source,
1124                        }
1125                    })?;
1126                    if let Some(previous) = dependencies.insert(name.clone(), digest) {
1127                        if previous != digest {
1128                            return Err(WrapperError::ConflictingExtern(name));
1129                        }
1130                    }
1131                    if let Some(previous) = dependency_paths.insert(name.clone(), path.clone()) {
1132                        if previous != path {
1133                            return Err(WrapperError::ConflictingExtern(name));
1134                        }
1135                    }
1136                }
1137                None => {
1138                    // `--extern proc_macro` and similar pathless externs are
1139                    // rustc/sysroot capabilities, not Cargo artifact edges.
1140                    // Keep them in unit identity without inventing an artifact
1141                    // hash that the root linker could never resolve.
1142                    semantic_options.insert(format!("rustc-resolved-extern:{name}"), String::new());
1143                }
1144            }
1145        } else if let Some(value) = short_option_value(&args, &mut index, "-C")? {
1146            let (key, value) = split_key_value(&value);
1147            if !descriptor_codegen_option(key) && !linker_only_codegen_option(key) {
1148                codegen_options.insert(key.to_string(), value.to_string());
1149            }
1150        } else if let Some(value) = short_option_value(&args, &mut index, "-Z")? {
1151            let (key, value) = split_key_value(&value);
1152            if key == "binary-dep-depinfo" {
1153                return Err(WrapperError::UnsupportedBinaryDepDepInfo);
1154            }
1155            if matches!(key, "remap-cwd-prefix" | "remap-path-scope") {
1156                return Err(WrapperError::UnsupportedDepInfoPathRemapping(format!(
1157                    "-Z{key}"
1158                )));
1159            }
1160            if !path_only_unstable_option(key) {
1161                unstable_options.insert(key.to_string(), value.to_string());
1162            }
1163        } else if let Some(value) = short_option_value(&args, &mut index, "-l")? {
1164            native_libraries.insert(value);
1165        } else if let Some(value) = short_option_value(&args, &mut index, "-L")? {
1166            let kind = value
1167                .split_once('=')
1168                .map_or("all", |(kind, _)| kind)
1169                .to_string();
1170            semantic_options.insert(format!("library-search-kind:{kind}"), String::new());
1171        } else if long_option_value(&args, &mut index, "--env-set")?.is_some() {
1172            return Err(WrapperError::UnsupportedLogicalEnvironmentInjection);
1173        } else if long_option_value(&args, &mut index, "--remap-path-prefix")?.is_some() {
1174            return Err(WrapperError::UnsupportedDepInfoPathRemapping(
1175                "--remap-path-prefix".to_string(),
1176            ));
1177        } else if long_option_value(&args, &mut index, "--remap-path-scope")?.is_some() {
1178            return Err(WrapperError::UnsupportedDepInfoPathRemapping(
1179                "--remap-path-scope".to_string(),
1180            ));
1181        } else if consume_path_option(&args, &mut index, argument)? {
1182            // Output, sysroot, and diagnostics paths do not participate in a
1183            // descriptor unit's host-independent semantic identity.
1184        } else if consume_diagnostic_option(&args, &mut index, argument)? {
1185            // Diagnostics do not affect emitted transport records.
1186        } else if boolean_rustc_flag(argument) {
1187            semantic_options.insert(argument.clone(), String::new());
1188        } else if argument.starts_with('-') {
1189            if let Some((key, value)) = argument.split_once('=') {
1190                semantic_options.insert(key.to_string(), value.to_string());
1191            } else {
1192                return Err(WrapperError::UnsupportedRustcOption(argument.clone()));
1193            }
1194        } else {
1195            if source_hash.is_some() {
1196                return Err(WrapperError::MultipleRustcInputs);
1197            }
1198            let path = PathBuf::from(argument);
1199            source_hash = Some(
1200                hash_file(&path, FILE_HASH_DOMAIN)
1201                    .map_err(|source| WrapperError::HashInput { path, source })?,
1202            );
1203        }
1204
1205        index += 1;
1206    }
1207
1208    let crate_name = crate_name.ok_or(WrapperError::MissingCrateName)?;
1209    if crate_types.is_empty() {
1210        // rustc's `--test` mode implies a binary test harness and Cargo
1211        // therefore omits an explicit `--crate-type`. Preserve the exact
1212        // effective crate type while continuing to reject an unexplained
1213        // missing type for every other invocation.
1214        if semantic_options.contains_key("--test") {
1215            crate_types.insert("bin".to_string());
1216        } else {
1217            return Err(WrapperError::MissingCrateType);
1218        }
1219    }
1220    let source_hash = source_hash.ok_or(WrapperError::MissingRustcInput)?;
1221    let package_source_closure_hash = match package_root {
1222        Some(package_root) => hash_package_source_closure(package_root, excluded_source_subtree)
1223            .map_err(|source| WrapperError::HashPackageSourceClosure {
1224                path: package_root.to_path_buf(),
1225                source,
1226            })?,
1227        None => hash_canonical(PACKAGE_SOURCE_CLOSURE_HASH_DOMAIN, |hash| {
1228            hash.field("mode", b"crate-root-only-fallback");
1229            hash.field("crate_root", &source_hash);
1230        }),
1231    };
1232    let features = cfgs
1233        .iter()
1234        .filter_map(|cfg| {
1235            cfg.strip_prefix("feature=\"")
1236                .and_then(|feature| feature.strip_suffix('"'))
1237                .map(str::to_owned)
1238        })
1239        .collect();
1240    let identity_environment = identity_rustc_environment(environment).map_err(|source| {
1241        WrapperError::ReadBuildScriptEnvironment {
1242            out_dir: environment.get("OUT_DIR").map(PathBuf::from),
1243            source,
1244        }
1245    })?;
1246
1247    Ok(NormalizedRustcInvocation {
1248        crate_name,
1249        crate_types,
1250        target,
1251        edition,
1252        cfgs,
1253        features,
1254        emits,
1255        semantic_options,
1256        codegen_options,
1257        unstable_options,
1258        native_libraries,
1259        environment: identity_environment,
1260        rustc_identity_hash: hash_bytes(FILE_HASH_DOMAIN, rustc_identity),
1261        source_hash,
1262        package_source_closure_hash,
1263        dependencies,
1264        dependency_paths,
1265    })
1266}
1267
1268fn long_option_value(
1269    args: &[String],
1270    index: &mut usize,
1271    option: &'static str,
1272) -> Result<Option<String>, WrapperError> {
1273    let argument = &args[*index];
1274    if argument == option {
1275        *index += 1;
1276        return args
1277            .get(*index)
1278            .cloned()
1279            .map(Some)
1280            .ok_or(WrapperError::MissingRustcOptionValue(option));
1281    }
1282    Ok(argument
1283        .strip_prefix(option)
1284        .and_then(|suffix| suffix.strip_prefix('='))
1285        .map(str::to_owned))
1286}
1287
1288fn short_option_value(
1289    args: &[String],
1290    index: &mut usize,
1291    option: &'static str,
1292) -> Result<Option<String>, WrapperError> {
1293    let argument = &args[*index];
1294    if argument == option {
1295        *index += 1;
1296        return args
1297            .get(*index)
1298            .cloned()
1299            .map(Some)
1300            .ok_or(WrapperError::MissingRustcOptionValue(option));
1301    }
1302    Ok(argument
1303        .strip_prefix(option)
1304        .filter(|suffix| !suffix.is_empty())
1305        .map(str::to_owned))
1306}
1307
1308fn consume_path_option(
1309    args: &[String],
1310    index: &mut usize,
1311    argument: &str,
1312) -> Result<bool, WrapperError> {
1313    for option in ["--out-dir", "--sysroot", "-o"] {
1314        if argument == option {
1315            *index += 1;
1316            if args.get(*index).is_none() {
1317                return Err(WrapperError::MissingRustcOptionValue(option));
1318            }
1319            return Ok(true);
1320        }
1321        if argument.starts_with(&format!("{option}=")) {
1322            return Ok(true);
1323        }
1324        if option == "-o" && argument.starts_with("-o") && argument.len() > 2 {
1325            return Ok(true);
1326        }
1327    }
1328    Ok(false)
1329}
1330
1331fn consume_diagnostic_option(
1332    args: &[String],
1333    index: &mut usize,
1334    argument: &str,
1335) -> Result<bool, WrapperError> {
1336    const OPTIONS: [&str; 12] = [
1337        "--allow",
1338        "--cap-lints",
1339        "--check-cfg",
1340        "--color",
1341        "--deny",
1342        "--diagnostic-width",
1343        "--error-format",
1344        "--forbid",
1345        "--force-warn",
1346        "--json",
1347        "--warn",
1348        "--crate-version",
1349    ];
1350    for option in OPTIONS {
1351        if argument == option {
1352            *index += 1;
1353            if args.get(*index).is_none() {
1354                return Err(WrapperError::MissingRustcOptionValue(option));
1355            }
1356            return Ok(true);
1357        }
1358        if argument.starts_with(&format!("{option}=")) {
1359            return Ok(true);
1360        }
1361    }
1362    for option in ["-A", "-D", "-F", "-W"] {
1363        if argument == option {
1364            *index += 1;
1365            if args.get(*index).is_none() {
1366                return Err(WrapperError::MissingRustcOptionValue("lint option"));
1367            }
1368            return Ok(true);
1369        }
1370        if argument.starts_with(option) && argument.len() > option.len() {
1371            return Ok(true);
1372        }
1373    }
1374    Ok(false)
1375}
1376
1377fn boolean_rustc_flag(argument: &str) -> bool {
1378    matches!(
1379        argument,
1380        "--test" | "--bench" | "--no-main" | "--proc-macro" | "--crate-type" | "--verbose" | "-v"
1381    )
1382}
1383
1384fn split_comma_values(value: &str) -> impl Iterator<Item = String> + '_ {
1385    value
1386        .split(',')
1387        .filter(|value| !value.is_empty())
1388        .map(str::to_owned)
1389}
1390
1391fn parse_extern(value: &str) -> Result<(String, Option<PathBuf>), WrapperError> {
1392    let (name, path) = value
1393        .split_once('=')
1394        .map_or((value, None), |(name, path)| (name, Some(path)));
1395    if name.is_empty() {
1396        return Err(WrapperError::MalformedExtern(value.to_string()));
1397    }
1398    Ok((name.to_string(), path.map(PathBuf::from)))
1399}
1400
1401fn split_key_value(value: &str) -> (&str, &str) {
1402    value
1403        .split_once('=')
1404        .map_or((value, ""), |(key, value)| (key, value))
1405}
1406
1407fn descriptor_codegen_option(key: &str) -> bool {
1408    matches!(
1409        key,
1410        "codegen-units" | "incremental" | "link-dead-code" | "linker-plugin-lto" | "lto" | "strip"
1411    )
1412}
1413
1414fn linker_only_codegen_option(key: &str) -> bool {
1415    matches!(
1416        key,
1417        "link-arg"
1418            | "link-args"
1419            | "linker"
1420            | "linker-features"
1421            | "rpath"
1422            | "default-linker-libraries"
1423    )
1424}
1425
1426fn path_only_unstable_option(key: &str) -> bool {
1427    matches!(
1428        key,
1429        "incremental-info"
1430            | "profile"
1431            | "profile-emit"
1432            | "profile-use"
1433            | "self-profile"
1434            | "temps-dir"
1435    )
1436}
1437
1438fn descriptor_rustc_args(
1439    rustc_args: &[OsString],
1440    descriptor_object: &Path,
1441) -> Result<Vec<OsString>, WrapperError> {
1442    let mut result = Vec::with_capacity(rustc_args.len() + 6);
1443    let mut index = 0;
1444    while index < rustc_args.len() {
1445        let argument = rustc_args[index]
1446            .to_str()
1447            .ok_or_else(|| WrapperError::NonUtf8RustcArgument(rustc_args[index].clone()))?;
1448
1449        if argument == "-C" {
1450            let value = rustc_args
1451                .get(index + 1)
1452                .and_then(|value| value.to_str())
1453                .ok_or(WrapperError::MissingRustcOptionValue("-C"))?;
1454            if descriptor_codegen_option(split_key_value(value).0) {
1455                index += 2;
1456                continue;
1457            }
1458        } else if let Some(value) = argument.strip_prefix("-C") {
1459            if !value.is_empty() && descriptor_codegen_option(split_key_value(value).0) {
1460                index += 1;
1461                continue;
1462            }
1463        }
1464
1465        if argument == "--emit" {
1466            let value = rustc_args
1467                .get(index + 1)
1468                .and_then(|value| value.to_str())
1469                .ok_or(WrapperError::MissingRustcOptionValue("--emit"))?;
1470            if let Some(rewritten) = emit_without_object(value) {
1471                result.push(OsString::from("--emit"));
1472                result.push(OsString::from(rewritten));
1473            }
1474            index += 2;
1475            continue;
1476        } else if let Some(value) = argument.strip_prefix("--emit=") {
1477            if let Some(rewritten) = emit_without_object(value) {
1478                result.push(OsString::from(format!("--emit={rewritten}")));
1479            }
1480            index += 1;
1481            continue;
1482        }
1483
1484        result.push(rustc_args[index].clone());
1485        index += 1;
1486    }
1487
1488    result.extend([
1489        OsString::from("-Ccodegen-units=1"),
1490        OsString::from("-Clink-dead-code=yes"),
1491        OsString::from("-Clto=off"),
1492        OsString::from("-Cstrip=none"),
1493        OsString::from(format!("--emit=obj={}", descriptor_object.display())),
1494    ]);
1495    Ok(result)
1496}
1497
1498fn emit_without_object(value: &str) -> Option<String> {
1499    let emits = value
1500        .split(',')
1501        .filter(|emit| emit.split_once('=').map_or(*emit, |(kind, _)| kind) != "obj")
1502        .collect::<Vec<_>>();
1503    (!emits.is_empty()).then(|| emits.join(","))
1504}
1505
1506/// Hash the conservative source closure rooted at one Cargo package.
1507///
1508/// Every regular file participates under its UTF-8, slash-separated path
1509/// relative to `package_root`, so relocating an identical package does not
1510/// change the digest. Exact-name VCS entries (`.git`, `.hg`, `.svn`,
1511/// `.jj`), `node_modules` at any depth, the conventional package-root
1512/// `target` directory, and one caller-proven exact generated subtree are
1513/// excluded. The latter is the runner-owned descriptor target. Nested source
1514/// directories named `target` remain ordinary inputs, and an untrusted
1515/// `.rustc_info.json` file never hides its containing subtree. All other files
1516/// participate, including manifests, build
1517/// scripts, Rust modules, and `include_*` assets; this deliberately accepts
1518/// false invalidations in exchange for never guessing which package-local
1519/// files rustc may observe.
1520///
1521/// Symlinks, special files, and non-UTF-8 relative paths fail closed because
1522/// following or encoding them would make the identity host-dependent. Files
1523/// outside `CARGO_MANIFEST_DIR` are not discoverable from rustc's
1524/// pre-compilation argv. The wrapper separately audits rustc-declared
1525/// `OUT_DIR` source dependencies from the successful compile's exact dep-info;
1526/// other external source classes require an explicit tracking protocol.
1527fn hash_package_source_closure(
1528    package_root: &Path,
1529    excluded_subtree: Option<&Path>,
1530) -> io::Result<[u8; 32]> {
1531    let package_root = fs::canonicalize(package_root)?;
1532    let metadata = fs::symlink_metadata(&package_root)?;
1533    if !metadata.file_type().is_dir() {
1534        return Err(io::Error::new(
1535            io::ErrorKind::InvalidInput,
1536            "Cargo package source root is not a directory",
1537        ));
1538    }
1539
1540    let excluded_subtree = excluded_subtree
1541        .map(fs::canonicalize)
1542        .transpose()?
1543        .filter(|excluded| excluded.starts_with(&package_root));
1544    let mut files = BTreeMap::new();
1545    collect_package_source_files(
1546        &package_root,
1547        &package_root,
1548        excluded_subtree.as_deref(),
1549        &mut files,
1550    )?;
1551    Ok(hash_canonical(PACKAGE_SOURCE_CLOSURE_HASH_DOMAIN, |hash| {
1552        hash.field("mode", b"manifest-tree-v4-root-target");
1553        hash.digest_map("files", &files);
1554    }))
1555}
1556
1557fn collect_package_source_files(
1558    package_root: &Path,
1559    directory: &Path,
1560    excluded_subtree: Option<&Path>,
1561    files: &mut BTreeMap<String, [u8; 32]>,
1562) -> io::Result<()> {
1563    for entry in fs::read_dir(directory)? {
1564        let entry = entry?;
1565        let name = entry.file_name();
1566        if package_source_root_vcs_entry_is_excluded(package_root, directory, &name) {
1567            continue;
1568        }
1569        let file_type = entry.file_type()?;
1570        if file_type.is_dir() {
1571            if excluded_subtree.is_some_and(|excluded| entry.path() == excluded) {
1572                continue;
1573            }
1574            if package_source_generated_directory_is_excluded(package_root, directory, &name) {
1575                continue;
1576            }
1577            collect_package_source_files(package_root, &entry.path(), excluded_subtree, files)?;
1578            continue;
1579        }
1580        if !file_type.is_file() {
1581            return Err(io::Error::new(
1582                io::ErrorKind::InvalidData,
1583                format!(
1584                    "package source closure contains unsupported symlink or special file `{}`",
1585                    entry.path().display()
1586                ),
1587            ));
1588        }
1589
1590        let path = entry.path();
1591        let relative = path.strip_prefix(package_root).map_err(|_| {
1592            io::Error::new(
1593                io::ErrorKind::InvalidData,
1594                format!(
1595                    "package source file `{}` escaped root `{}`",
1596                    path.display(),
1597                    package_root.display()
1598                ),
1599            )
1600        })?;
1601        let relative = portable_package_relative_path(relative)?;
1602        if relative
1603            .rsplit('/')
1604            .next()
1605            .is_some_and(|name| name.ends_with(' '))
1606        {
1607            return Err(io::Error::new(
1608                io::ErrorKind::InvalidData,
1609                format!("package source path is ambiguous in rustc dep-info: `{relative}`"),
1610            ));
1611        }
1612        let digest = hash_file(&path, PACKAGE_SOURCE_FILE_HASH_DOMAIN)?;
1613        if files.insert(relative.clone(), digest).is_some() {
1614            return Err(io::Error::new(
1615                io::ErrorKind::InvalidData,
1616                format!("package source closure repeats relative path `{relative}`"),
1617            ));
1618        }
1619    }
1620    Ok(())
1621}
1622
1623fn package_source_root_vcs_entry_is_excluded(
1624    package_root: &Path,
1625    parent: &Path,
1626    name: &OsStr,
1627) -> bool {
1628    parent == package_root && matches!(name.to_str(), Some(".git" | ".hg" | ".svn" | ".jj"))
1629}
1630
1631fn package_source_generated_directory_is_excluded(
1632    package_root: &Path,
1633    parent: &Path,
1634    name: &OsStr,
1635) -> bool {
1636    matches!(name.to_str(), Some("node_modules"))
1637        || (parent == package_root && name == OsStr::new("target"))
1638}
1639
1640fn rustc_dep_info_path(
1641    rustc_args: &[OsString],
1642    input: &NormalizedRustcInvocation,
1643) -> Result<PathBuf, WrapperError> {
1644    let args = rustc_args
1645        .iter()
1646        .map(|argument| {
1647            argument
1648                .to_str()
1649                .map(str::to_owned)
1650                .ok_or_else(|| WrapperError::NonUtf8RustcArgument(argument.clone()))
1651        })
1652        .collect::<Result<Vec<_>, _>>()?;
1653    let mut dep_info = None;
1654    let mut out_dir = None;
1655    let mut explicit_output = false;
1656    let mut index = 0;
1657    while index < args.len() {
1658        let argument = &args[index];
1659        if let Some(value) = long_option_value(&args, &mut index, "--emit")? {
1660            for emit in value.split(',').filter(|emit| !emit.is_empty()) {
1661                let (kind, path) = emit
1662                    .split_once('=')
1663                    .map_or((emit, None), |(kind, path)| (kind, Some(path)));
1664                if kind == "dep-info" {
1665                    if dep_info.is_some() {
1666                        return Err(WrapperError::DuplicateDepInfoOutput);
1667                    }
1668                    dep_info = Some(path.map(PathBuf::from));
1669                }
1670            }
1671        } else if let Some(value) = long_option_value(&args, &mut index, "--out-dir")? {
1672            out_dir = Some(PathBuf::from(value));
1673        } else if argument == "-o"
1674            || argument.starts_with("-o=")
1675            || (argument.starts_with("-o") && argument.len() > 2)
1676        {
1677            explicit_output = true;
1678            if argument == "-o" {
1679                index += 1;
1680                if args.get(index).is_none() {
1681                    return Err(WrapperError::MissingRustcOptionValue("-o"));
1682                }
1683            }
1684        }
1685        index += 1;
1686    }
1687
1688    let explicit = dep_info.ok_or(WrapperError::MissingDepInfoOutput)?;
1689    let path = match explicit {
1690        Some(path) => path,
1691        None if explicit_output => return Err(WrapperError::UnsupportedDefaultDepInfoWithOutput),
1692        None => {
1693            let out_dir = out_dir.ok_or(WrapperError::MissingRustcOptionValue("--out-dir"))?;
1694            let extra = input.cargo_extra_filename().map_err(|reason| {
1695                WrapperError::InvalidCargoExtraFilename {
1696                    context: "rustc dep-info output",
1697                    value: input
1698                        .codegen_options
1699                        .get("extra-filename")
1700                        .cloned()
1701                        .unwrap_or_default(),
1702                    reason,
1703                }
1704            })?;
1705            out_dir.join(format!(
1706                "{}{}.d",
1707                input.crate_name,
1708                extra.as_deref().unwrap_or_default()
1709            ))
1710        }
1711    };
1712    if path.is_absolute() {
1713        Ok(path)
1714    } else {
1715        env::current_dir()
1716            .map(|directory| directory.join(path))
1717            .map_err(WrapperError::CurrentDirectory)
1718    }
1719}
1720
1721struct ParsedDepInfo {
1722    source_paths: Vec<PathBuf>,
1723    environment: Vec<ParsedEnvironmentDependency>,
1724}
1725
1726struct ParsedEnvironmentDependency {
1727    name: String,
1728    value: Option<String>,
1729}
1730
1731#[derive(Clone, Debug, PartialEq, Eq)]
1732struct ObservedRustcInputs {
1733    out_dir_dependencies: Vec<DescriptorOutDirDependency>,
1734    source_dependencies: Vec<DescriptorSourceDependency>,
1735    environment_dependencies: Vec<DescriptorEnvironmentDependency>,
1736}
1737
1738fn observe_rustc_inputs(
1739    dep_info_path: &Path,
1740    working_directory: &Path,
1741    out_dir: Option<&Path>,
1742    out_dir_coordinate: Option<&str>,
1743    phase_environment: &BTreeMap<String, Option<String>>,
1744) -> Result<ObservedRustcInputs, WrapperError> {
1745    let metadata =
1746        fs::symlink_metadata(dep_info_path).map_err(|source| WrapperError::ReadDepInfo {
1747            path: dep_info_path.to_path_buf(),
1748            source,
1749        })?;
1750    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
1751        return Err(WrapperError::UnsafeDepInfoOutput(
1752            dep_info_path.to_path_buf(),
1753        ));
1754    }
1755    let bytes = fs::read(dep_info_path).map_err(|source| WrapperError::ReadDepInfo {
1756        path: dep_info_path.to_path_buf(),
1757        source,
1758    })?;
1759    let parsed = parse_rustc_dep_info(&bytes).map_err(|reason| WrapperError::MalformedDepInfo {
1760        path: dep_info_path.to_path_buf(),
1761        reason,
1762    })?;
1763
1764    let working_directory = canonical_plain_directory(working_directory)?;
1765    let original_out_dir = out_dir;
1766    let canonical_out_dir = out_dir.map(canonical_plain_out_dir).transpose()?;
1767    match (canonical_out_dir.as_ref(), out_dir_coordinate) {
1768        (Some(_), Some(coordinate)) => validate_portable_relative_path(coordinate)
1769            .map_err(WrapperError::InvalidObservedOutDirCoordinate)?,
1770        (None, None) => {}
1771        _ => return Err(WrapperError::InconsistentObservedOutDir),
1772    }
1773
1774    let mut out_dir_dependencies = BTreeMap::<String, String>::new();
1775    let mut source_dependencies = BTreeMap::<PathBuf, String>::new();
1776    for source_path in parsed.source_paths {
1777        let source_path = if source_path.is_absolute() {
1778            source_path
1779        } else {
1780            working_directory.join(source_path)
1781        };
1782        let lexical_out_dir_relative =
1783            original_out_dir.and_then(|out_dir| source_path.strip_prefix(out_dir).ok());
1784        if let Some(relative) = lexical_out_dir_relative {
1785            portable_package_relative_path(relative).map_err(|source| {
1786                WrapperError::ReadOutDirDependency {
1787                    path: source_path.clone(),
1788                    source,
1789                }
1790            })?;
1791            validate_no_symlink_path(
1792                original_out_dir.expect("a lexical OUT_DIR relative path has an OUT_DIR"),
1793                relative,
1794            )?;
1795        }
1796
1797        let original_metadata = fs::symlink_metadata(&source_path).map_err(|source| {
1798            WrapperError::ReadObservedSource {
1799                path: source_path.clone(),
1800                source,
1801            }
1802        })?;
1803        if original_metadata.file_type().is_symlink() || !original_metadata.file_type().is_file() {
1804            return Err(WrapperError::UnsafeObservedSource(source_path));
1805        }
1806        let canonical =
1807            fs::canonicalize(&source_path).map_err(|source| WrapperError::ReadObservedSource {
1808                path: source_path.clone(),
1809                source,
1810            })?;
1811        let canonical_metadata = fs::symlink_metadata(&canonical).map_err(|source| {
1812            WrapperError::ReadObservedSource {
1813                path: canonical.clone(),
1814                source,
1815            }
1816        })?;
1817        if canonical_metadata.file_type().is_symlink() || !canonical_metadata.file_type().is_file()
1818        {
1819            return Err(WrapperError::UnsafeObservedSource(canonical));
1820        }
1821
1822        if let Some(canonical_out_dir) = canonical_out_dir.as_ref() {
1823            match canonical.strip_prefix(canonical_out_dir) {
1824                Ok(relative) if relative.as_os_str().is_empty() => {
1825                    return Err(WrapperError::UnsafeOutDirDependency(canonical));
1826                }
1827                Ok(relative) => {
1828                    if lexical_out_dir_relative.is_none() {
1829                        // An external lexical path that reaches OUT_DIR only
1830                        // through a symlink is not a portable generated-input
1831                        // coordinate.
1832                        return Err(WrapperError::UnsafeOutDirDependency(source_path));
1833                    }
1834                    validate_no_symlink_path(canonical_out_dir, relative)?;
1835                    let relative_path =
1836                        portable_package_relative_path(relative).map_err(|source| {
1837                            WrapperError::ReadOutDirDependency {
1838                                path: canonical.clone(),
1839                                source,
1840                            }
1841                        })?;
1842                    let content_hash =
1843                        hash_file(&canonical, OUT_DIR_FILE_HASH_DOMAIN).map_err(|source| {
1844                            WrapperError::ReadOutDirDependency {
1845                                path: canonical,
1846                                source,
1847                            }
1848                        })?;
1849                    if out_dir_dependencies
1850                        .insert(relative_path.clone(), hex_digest(&content_hash))
1851                        .is_some()
1852                    {
1853                        return Err(WrapperError::ConflictingOutDirDependency(relative_path));
1854                    }
1855                    continue;
1856                }
1857                Err(_) if lexical_out_dir_relative.is_some() => {
1858                    return Err(WrapperError::UnsafeOutDirDependency(source_path));
1859                }
1860                Err(_) => {}
1861            }
1862        }
1863
1864        let content_hash =
1865            hash_file(&canonical, OBSERVED_SOURCE_FILE_HASH_DOMAIN).map_err(|source| {
1866                WrapperError::ReadObservedSource {
1867                    path: canonical.clone(),
1868                    source,
1869                }
1870            })?;
1871        record_observed_source_dependency(
1872            &mut source_dependencies,
1873            canonical,
1874            hex_digest(&content_hash),
1875        )?;
1876    }
1877
1878    let environment_dependencies = normalize_environment_dependencies(
1879        parsed.environment,
1880        original_out_dir,
1881        out_dir_coordinate,
1882        phase_environment,
1883    )?;
1884
1885    Ok(ObservedRustcInputs {
1886        out_dir_dependencies: out_dir_dependencies
1887            .into_iter()
1888            .map(|(relative_path, content_hash)| DescriptorOutDirDependency {
1889                relative_path,
1890                content_hash,
1891            })
1892            .collect(),
1893        source_dependencies: source_dependencies
1894            .into_iter()
1895            .map(|(absolute_path, content_hash)| DescriptorSourceDependency {
1896                absolute_path,
1897                content_hash,
1898            })
1899            .collect(),
1900        environment_dependencies,
1901    })
1902}
1903
1904fn record_observed_source_dependency(
1905    source_dependencies: &mut BTreeMap<PathBuf, String>,
1906    canonical: PathBuf,
1907    content_hash: String,
1908) -> Result<(), WrapperError> {
1909    match source_dependencies.entry(canonical.clone()) {
1910        std::collections::btree_map::Entry::Vacant(entry) => {
1911            entry.insert(content_hash);
1912        }
1913        std::collections::btree_map::Entry::Occupied(entry) if entry.get() == &content_hash => {
1914            // rustc can name the same included source through multiple lexical
1915            // paths (for example `docs/file.md` and
1916            // `handler/../docs/file.md`). The canonical input and bytes are
1917            // identical, so this is one dependency record.
1918        }
1919        std::collections::btree_map::Entry::Occupied(_) => {
1920            return Err(WrapperError::ConflictingObservedSource(canonical));
1921        }
1922    }
1923    Ok(())
1924}
1925
1926fn canonical_plain_directory(path: &Path) -> Result<PathBuf, WrapperError> {
1927    if !path.is_absolute() {
1928        return Err(WrapperError::RelativeDepInfoWorkingDirectory(
1929            path.to_path_buf(),
1930        ));
1931    }
1932    let canonical = fs::canonicalize(path).map_err(|source| WrapperError::ReadObservedSource {
1933        path: path.to_path_buf(),
1934        source,
1935    })?;
1936    let metadata =
1937        fs::symlink_metadata(&canonical).map_err(|source| WrapperError::ReadObservedSource {
1938            path: canonical.clone(),
1939            source,
1940        })?;
1941    if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
1942        return Err(WrapperError::UnsafeObservedSource(canonical));
1943    }
1944    Ok(canonical)
1945}
1946
1947fn canonical_plain_out_dir(path: &Path) -> Result<PathBuf, WrapperError> {
1948    if !path.is_absolute() {
1949        return Err(WrapperError::RelativeOutDir(path.to_path_buf()));
1950    }
1951    let canonical =
1952        fs::canonicalize(path).map_err(|source| WrapperError::ReadOutDirDependency {
1953            path: path.to_path_buf(),
1954            source,
1955        })?;
1956    let metadata =
1957        fs::symlink_metadata(&canonical).map_err(|source| WrapperError::ReadOutDirDependency {
1958            path: canonical.clone(),
1959            source,
1960        })?;
1961    if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
1962        return Err(WrapperError::UnsafeOutDirDependency(canonical));
1963    }
1964    Ok(canonical)
1965}
1966
1967fn normalize_environment_dependencies(
1968    dependencies: Vec<ParsedEnvironmentDependency>,
1969    out_dir: Option<&Path>,
1970    out_dir_coordinate: Option<&str>,
1971    phase_environment: &BTreeMap<String, Option<String>>,
1972) -> Result<Vec<DescriptorEnvironmentDependency>, WrapperError> {
1973    let mut normalized = BTreeMap::<String, Option<String>>::new();
1974    for dependency in dependencies {
1975        if wrapper_control_environment(&dependency.name) {
1976            let expected = phase_environment
1977                .get(&dependency.name)
1978                .cloned()
1979                .unwrap_or(None);
1980            if dependency.value != expected {
1981                return Err(WrapperError::PhaseOwnedEnvironmentMismatch {
1982                    name: dependency.name,
1983                });
1984            }
1985            continue;
1986        }
1987
1988        let value_hash = match dependency.value {
1989            None => None,
1990            Some(value) if dependency.name == "OUT_DIR" => {
1991                let expected = out_dir.ok_or(WrapperError::InconsistentObservedOutDir)?;
1992                if Path::new(&value) != expected {
1993                    return Err(WrapperError::ObservedEnvironmentMismatch {
1994                        name: dependency.name,
1995                    });
1996                }
1997                let coordinate =
1998                    out_dir_coordinate.ok_or(WrapperError::InconsistentObservedOutDir)?;
1999                Some(observed_environment_value_hash(
2000                    &dependency.name,
2001                    b"out-dir-coordinate",
2002                    coordinate.as_bytes(),
2003                ))
2004            }
2005            Some(value) => Some(observed_environment_value_hash(
2006                &dependency.name,
2007                b"exact-value",
2008                value.as_bytes(),
2009            )),
2010        };
2011        if normalized
2012            .insert(dependency.name.clone(), value_hash)
2013            .is_some()
2014        {
2015            return Err(WrapperError::DuplicateEnvironmentDependency {
2016                name: dependency.name,
2017            });
2018        }
2019    }
2020    Ok(normalized
2021        .into_iter()
2022        .map(|(name, value_hash)| DescriptorEnvironmentDependency { name, value_hash })
2023        .collect())
2024}
2025
2026fn observed_environment_value_hash(name: &str, mode: &[u8], value: &[u8]) -> String {
2027    hex_digest(&hash_canonical(
2028        OBSERVED_ENVIRONMENT_VALUE_HASH_DOMAIN,
2029        |hash| {
2030            hash.field("name", name.as_bytes());
2031            hash.field("mode", mode);
2032            hash.field("value", value);
2033        },
2034    ))
2035}
2036
2037fn prepare_dep_info_output(path: &Path) -> Result<(), WrapperError> {
2038    match fs::symlink_metadata(path) {
2039        Ok(metadata) if metadata.file_type().is_file() => {
2040            fs::remove_file(path).map_err(|source| WrapperError::WriteDepInfo {
2041                path: path.to_path_buf(),
2042                source,
2043            })
2044        }
2045        Ok(_) => Err(WrapperError::UnsafeDepInfoOutput(path.to_path_buf())),
2046        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(()),
2047        Err(source) => Err(WrapperError::ReadDepInfo {
2048            path: path.to_path_buf(),
2049            source,
2050        }),
2051    }
2052}
2053
2054fn validate_dep_info_output_path(target: &Path, path: &Path) -> Result<(), WrapperError> {
2055    if !target.is_absolute() || !path.is_absolute() {
2056        return Err(WrapperError::DepInfoOutsideTarget {
2057            path: path.to_path_buf(),
2058            target: target.to_path_buf(),
2059        });
2060    }
2061    validate_dep_info_path_spelling(target, false)?;
2062    validate_dep_info_path_spelling(path, true)?;
2063    let relative = path
2064        .strip_prefix(target)
2065        .map_err(|_| WrapperError::DepInfoOutsideTarget {
2066            path: path.to_path_buf(),
2067            target: target.to_path_buf(),
2068        })?;
2069    let mut components = relative.components().peekable();
2070    if components.peek().is_none() {
2071        return Err(WrapperError::DepInfoOutsideTarget {
2072            path: path.to_path_buf(),
2073            target: target.to_path_buf(),
2074        });
2075    }
2076    let target_metadata =
2077        fs::symlink_metadata(target).map_err(|source| WrapperError::ReadDepInfo {
2078            path: target.to_path_buf(),
2079            source,
2080        })?;
2081    if target_metadata.file_type().is_symlink() || !target_metadata.file_type().is_dir() {
2082        return Err(WrapperError::UnsafeDepInfoOutput(target.to_path_buf()));
2083    }
2084    let mut current = target.to_path_buf();
2085    while let Some(component) = components.next() {
2086        let std::path::Component::Normal(component) = component else {
2087            return Err(WrapperError::DepInfoOutsideTarget {
2088                path: path.to_path_buf(),
2089                target: target.to_path_buf(),
2090            });
2091        };
2092        current.push(component);
2093        if components.peek().is_none() {
2094            break;
2095        }
2096        let metadata =
2097            fs::symlink_metadata(&current).map_err(|source| WrapperError::ReadDepInfo {
2098                path: current.clone(),
2099                source,
2100            })?;
2101        if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
2102            return Err(WrapperError::UnsafeDepInfoOutput(current));
2103        }
2104    }
2105    Ok(())
2106}
2107
2108fn target_relative_dep_info_path(target: &Path, path: &Path) -> Result<String, WrapperError> {
2109    validate_dep_info_output_path(target, path)?;
2110    let relative = path
2111        .strip_prefix(target)
2112        .map_err(|_| WrapperError::DepInfoOutsideTarget {
2113            path: path.to_path_buf(),
2114            target: target.to_path_buf(),
2115        })?;
2116    portable_package_relative_path(relative).map_err(|source| WrapperError::ReadDepInfo {
2117        path: path.to_path_buf(),
2118        source,
2119    })
2120}
2121
2122fn validate_no_symlink_path(base: &Path, relative: &Path) -> Result<(), WrapperError> {
2123    let mut path = base.to_path_buf();
2124    let mut components = relative.components().peekable();
2125    while let Some(component) = components.next() {
2126        let std::path::Component::Normal(component) = component else {
2127            return Err(WrapperError::UnsafeOutDirDependency(base.join(relative)));
2128        };
2129        path.push(component);
2130        let metadata =
2131            fs::symlink_metadata(&path).map_err(|source| WrapperError::ReadOutDirDependency {
2132                path: path.clone(),
2133                source,
2134            })?;
2135        let expected_type = if components.peek().is_some() {
2136            metadata.file_type().is_dir()
2137        } else {
2138            metadata.file_type().is_file()
2139        };
2140        if metadata.file_type().is_symlink() || !expected_type {
2141            return Err(WrapperError::UnsafeOutDirDependency(path));
2142        }
2143    }
2144    Ok(())
2145}
2146
2147fn validate_dep_info_path_spelling(
2148    path: &Path,
2149    terminal_is_file: bool,
2150) -> Result<(), WrapperError> {
2151    let mut last = None;
2152    for component in path.components() {
2153        let std::path::Component::Normal(component) = component else {
2154            continue;
2155        };
2156        let component = component
2157            .to_str()
2158            .ok_or_else(|| WrapperError::UnrepresentableDepInfoPath(path.to_path_buf()))?;
2159        if component.contains('\\')
2160            || component
2161                .chars()
2162                .any(|character| character.is_whitespace() && character != ' ')
2163        {
2164            return Err(WrapperError::UnrepresentableDepInfoPath(path.to_path_buf()));
2165        }
2166        last = Some(component);
2167    }
2168    if terminal_is_file && last.is_some_and(|component| component.ends_with(' ')) {
2169        return Err(WrapperError::UnrepresentableDepInfoPath(path.to_path_buf()));
2170    }
2171    Ok(())
2172}
2173
2174fn descriptor_out_dir_coordinate(
2175    target_dir: &Path,
2176    out_dir: Option<&str>,
2177) -> Result<Option<String>, WrapperError> {
2178    let Some(out_dir) = out_dir else {
2179        return Ok(None);
2180    };
2181    let out_dir = Path::new(out_dir);
2182    if !out_dir.is_absolute() {
2183        return Err(WrapperError::RelativeOutDir(out_dir.to_path_buf()));
2184    }
2185    validate_dep_info_path_spelling(target_dir, false)?;
2186    validate_dep_info_path_spelling(out_dir, false)?;
2187    let target_metadata =
2188        fs::symlink_metadata(target_dir).map_err(|source| WrapperError::ReadOutDirDependency {
2189            path: target_dir.to_path_buf(),
2190            source,
2191        })?;
2192    if target_metadata.file_type().is_symlink() || !target_metadata.file_type().is_dir() {
2193        return Err(WrapperError::UnsafeOutDirDependency(
2194            target_dir.to_path_buf(),
2195        ));
2196    }
2197    let relative = out_dir.strip_prefix(target_dir).map_err(|_| {
2198        WrapperError::OutDirOutsideDescriptorTarget {
2199            out_dir: out_dir.to_path_buf(),
2200            target: target_dir.to_path_buf(),
2201        }
2202    })?;
2203    if relative.as_os_str().is_empty() {
2204        return Err(WrapperError::OutDirOutsideDescriptorTarget {
2205            out_dir: out_dir.to_path_buf(),
2206            target: target_dir.to_path_buf(),
2207        });
2208    }
2209    let portable = portable_package_relative_path(relative).map_err(|source| {
2210        WrapperError::ReadOutDirDependency {
2211            path: out_dir.to_path_buf(),
2212            source,
2213        }
2214    })?;
2215    let mut current = target_dir.to_path_buf();
2216    for component in relative.components() {
2217        let std::path::Component::Normal(component) = component else {
2218            return Err(WrapperError::UnsafeOutDirDependency(out_dir.to_path_buf()));
2219        };
2220        current.push(component);
2221        let metadata = fs::symlink_metadata(&current).map_err(|source| {
2222            WrapperError::ReadOutDirDependency {
2223                path: current.clone(),
2224                source,
2225            }
2226        })?;
2227        if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
2228            return Err(WrapperError::UnsafeOutDirDependency(current));
2229        }
2230    }
2231    let canonical_target =
2232        fs::canonicalize(target_dir).map_err(|source| WrapperError::ReadOutDirDependency {
2233            path: target_dir.to_path_buf(),
2234            source,
2235        })?;
2236    let canonical_out_dir =
2237        fs::canonicalize(out_dir).map_err(|source| WrapperError::ReadOutDirDependency {
2238            path: out_dir.to_path_buf(),
2239            source,
2240        })?;
2241    if canonical_out_dir == canonical_target || !canonical_out_dir.starts_with(&canonical_target) {
2242        return Err(WrapperError::OutDirOutsideDescriptorTarget {
2243            out_dir: out_dir.to_path_buf(),
2244            target: target_dir.to_path_buf(),
2245        });
2246    }
2247    Ok(Some(portable))
2248}
2249
2250fn validate_out_dir_dependency_records(
2251    dependencies: &[DescriptorOutDirDependency],
2252) -> Result<(), WrapperError> {
2253    let mut previous = None;
2254    for dependency in dependencies {
2255        validate_portable_relative_path(&dependency.relative_path).map_err(|reason| {
2256            WrapperError::InvalidOutDirDependencyPath {
2257                path: dependency.relative_path.clone(),
2258                reason,
2259            }
2260        })?;
2261        validate_lower_sha256(&dependency.content_hash).map_err(|reason| {
2262            WrapperError::InvalidSha256 {
2263                name: "OUT_DIR dependency content hash",
2264                value: dependency.content_hash.clone(),
2265                reason,
2266            }
2267        })?;
2268        if previous
2269            .as_ref()
2270            .is_some_and(|value: &String| value.as_str() >= dependency.relative_path.as_str())
2271        {
2272            return Err(WrapperError::NonCanonicalOutDirDependencies);
2273        }
2274        previous = Some(dependency.relative_path.clone());
2275    }
2276    Ok(())
2277}
2278
2279fn validate_source_dependency_records(
2280    dependencies: &[DescriptorSourceDependency],
2281) -> Result<(), WrapperError> {
2282    let mut previous = None::<&Path>;
2283    for dependency in dependencies {
2284        if !dependency.absolute_path.is_absolute() {
2285            return Err(WrapperError::RelativeObservedSource(
2286                dependency.absolute_path.clone(),
2287            ));
2288        }
2289        validate_lower_sha256(&dependency.content_hash).map_err(|reason| {
2290            WrapperError::InvalidSha256 {
2291                name: "observed source dependency content hash",
2292                value: dependency.content_hash.clone(),
2293                reason,
2294            }
2295        })?;
2296        if previous.is_some_and(|value| value >= dependency.absolute_path.as_path()) {
2297            return Err(WrapperError::NonCanonicalSourceDependencies);
2298        }
2299        previous = Some(&dependency.absolute_path);
2300    }
2301    Ok(())
2302}
2303
2304fn validate_environment_dependency_records(
2305    dependencies: &[DescriptorEnvironmentDependency],
2306) -> Result<(), WrapperError> {
2307    let mut previous = None::<&str>;
2308    for dependency in dependencies {
2309        if dependency.name.is_empty()
2310            || dependency.name.bytes().any(|byte| byte == 0)
2311            || wrapper_control_environment(&dependency.name)
2312        {
2313            return Err(WrapperError::InvalidEnvironmentDependencyName {
2314                name: dependency.name.clone(),
2315            });
2316        }
2317        if let Some(value_hash) = &dependency.value_hash {
2318            validate_lower_sha256(value_hash).map_err(|reason| WrapperError::InvalidSha256 {
2319                name: "observed environment dependency value hash",
2320                value: value_hash.clone(),
2321                reason,
2322            })?;
2323        }
2324        if previous.is_some_and(|value| value >= dependency.name.as_str()) {
2325            return Err(WrapperError::NonCanonicalEnvironmentDependencies);
2326        }
2327        previous = Some(&dependency.name);
2328    }
2329    Ok(())
2330}
2331
2332fn validate_current_out_dir_dependencies(
2333    out_dir: Option<&Path>,
2334    expected: &[DescriptorOutDirDependency],
2335) -> Result<(), WrapperError> {
2336    validate_out_dir_dependency_records(expected)?;
2337    let Some(out_dir) = out_dir else {
2338        return if expected.is_empty() {
2339            Ok(())
2340        } else {
2341            Err(WrapperError::MissingOutDirForDependencies)
2342        };
2343    };
2344    if !out_dir.is_absolute() {
2345        return Err(WrapperError::RelativeOutDir(out_dir.to_path_buf()));
2346    }
2347    let out_dir =
2348        fs::canonicalize(out_dir).map_err(|source| WrapperError::ReadOutDirDependency {
2349            path: out_dir.to_path_buf(),
2350            source,
2351        })?;
2352    if expected.is_empty() {
2353        return Ok(());
2354    }
2355    for dependency in expected {
2356        let mut path = out_dir.clone();
2357        for component in dependency.relative_path.split('/') {
2358            path.push(component);
2359            let metadata = fs::symlink_metadata(&path).map_err(|source| {
2360                WrapperError::ReadOutDirDependency {
2361                    path: path.clone(),
2362                    source,
2363                }
2364            })?;
2365            if metadata.file_type().is_symlink() {
2366                return Err(WrapperError::UnsafeOutDirDependency(path));
2367            }
2368        }
2369        let metadata =
2370            fs::symlink_metadata(&path).map_err(|source| WrapperError::ReadOutDirDependency {
2371                path: path.clone(),
2372                source,
2373            })?;
2374        if !metadata.file_type().is_file() {
2375            return Err(WrapperError::UnsafeOutDirDependency(path));
2376        }
2377        let actual = hash_file(&path, OUT_DIR_FILE_HASH_DOMAIN).map_err(|source| {
2378            WrapperError::ReadOutDirDependency {
2379                path: path.clone(),
2380                source,
2381            }
2382        })?;
2383        let actual = hex_digest(&actual);
2384        if actual != dependency.content_hash {
2385            return Err(WrapperError::OutDirDependencyHashMismatch {
2386                path,
2387                expected: dependency.content_hash.clone(),
2388                actual,
2389            });
2390        }
2391    }
2392    Ok(())
2393}
2394
2395/// Whether two rustc source-dependency sets describe the same consumed bytes.
2396///
2397/// The descriptor and final compilations run in separate tool-owned target
2398/// trees, so build-script outputs (sailfish's per-target template cache, for
2399/// example) keep identical bytes but get different generated file names in
2400/// each pass. Entries under the tool-owned `target/proa-rsjs` tree therefore
2401/// compare as a sorted multiset of content hashes; every path outside that
2402/// tree must still match exactly. `content_hash` is a domain-separated digest
2403/// of the exact bytes rustc read, so byte-for-byte identity of everything the
2404/// final compilation consumed is preserved. The relaxation deliberately does
2405/// not attempt to pair generated files across passes: their names share no
2406/// stable component, and hash-multiset equality is the strongest available
2407/// pairing (a content swap between two generated files with unchanged
2408/// multiset is accepted; both layouts were produced by the same trusted
2409/// build-script execution).
2410fn source_dependency_sets_equivalent(
2411    expected: &[DescriptorSourceDependency],
2412    actual: &[DescriptorSourceDependency],
2413) -> bool {
2414    fn under_tool_target(dependency: &DescriptorSourceDependency) -> bool {
2415        let components: Vec<_> = dependency.absolute_path.components().collect();
2416        components
2417            .windows(2)
2418            .any(|pair| pair[0].as_os_str() == "target" && pair[1].as_os_str() == "proa-rsjs")
2419    }
2420    fn split(
2421        dependencies: &[DescriptorSourceDependency],
2422    ) -> (Vec<&str>, Vec<&DescriptorSourceDependency>) {
2423        let mut generated_hashes = Vec::new();
2424        let mut exact = Vec::new();
2425        for dependency in dependencies {
2426            if under_tool_target(dependency) {
2427                generated_hashes.push(dependency.content_hash.as_str());
2428            } else {
2429                exact.push(dependency);
2430            }
2431        }
2432        generated_hashes.sort_unstable();
2433        exact.sort_unstable();
2434        (generated_hashes, exact)
2435    }
2436    let (expected_generated, expected_exact) = split(expected);
2437    let (actual_generated, actual_exact) = split(actual);
2438    expected_exact == actual_exact && expected_generated == actual_generated
2439}
2440
2441fn validate_current_source_dependencies(
2442    expected: &[DescriptorSourceDependency],
2443) -> Result<(), WrapperError> {
2444    validate_source_dependency_records(expected)?;
2445    for dependency in expected {
2446        let metadata = fs::symlink_metadata(&dependency.absolute_path).map_err(|source| {
2447            WrapperError::ReadObservedSource {
2448                path: dependency.absolute_path.clone(),
2449                source,
2450            }
2451        })?;
2452        if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
2453            return Err(WrapperError::UnsafeObservedSource(
2454                dependency.absolute_path.clone(),
2455            ));
2456        }
2457        let canonical = fs::canonicalize(&dependency.absolute_path).map_err(|source| {
2458            WrapperError::ReadObservedSource {
2459                path: dependency.absolute_path.clone(),
2460                source,
2461            }
2462        })?;
2463        if canonical != dependency.absolute_path {
2464            return Err(WrapperError::UnsafeObservedSource(
2465                dependency.absolute_path.clone(),
2466            ));
2467        }
2468        let actual = hash_file(&canonical, OBSERVED_SOURCE_FILE_HASH_DOMAIN).map_err(|source| {
2469            WrapperError::ReadObservedSource {
2470                path: canonical.clone(),
2471                source,
2472            }
2473        })?;
2474        let actual = hex_digest(&actual);
2475        if actual != dependency.content_hash {
2476            return Err(WrapperError::ObservedSourceHashMismatch {
2477                path: canonical,
2478                expected: dependency.content_hash.clone(),
2479                actual,
2480            });
2481        }
2482    }
2483    Ok(())
2484}
2485
2486fn validate_current_environment_dependencies(
2487    environment: &BTreeMap<String, String>,
2488    out_dir: Option<&Path>,
2489    out_dir_coordinate: Option<&str>,
2490    expected: &[DescriptorEnvironmentDependency],
2491) -> Result<(), WrapperError> {
2492    validate_environment_dependency_records(expected)?;
2493    for dependency in expected {
2494        let actual_hash = match environment.get(&dependency.name) {
2495            None => None,
2496            Some(value) if dependency.name == "OUT_DIR" => {
2497                let expected_out_dir = out_dir.ok_or(WrapperError::InconsistentObservedOutDir)?;
2498                if Path::new(value) != expected_out_dir {
2499                    return Err(WrapperError::ObservedEnvironmentMismatch {
2500                        name: dependency.name.clone(),
2501                    });
2502                }
2503                let coordinate =
2504                    out_dir_coordinate.ok_or(WrapperError::InconsistentObservedOutDir)?;
2505                Some(observed_environment_value_hash(
2506                    &dependency.name,
2507                    b"out-dir-coordinate",
2508                    coordinate.as_bytes(),
2509                ))
2510            }
2511            Some(value) => Some(observed_environment_value_hash(
2512                &dependency.name,
2513                b"exact-value",
2514                value.as_bytes(),
2515            )),
2516        };
2517        if actual_hash != dependency.value_hash {
2518            return Err(WrapperError::ObservedEnvironmentMismatch {
2519                name: dependency.name.clone(),
2520            });
2521        }
2522    }
2523    Ok(())
2524}
2525
2526fn validate_final_out_dir(
2527    final_target: &Path,
2528    out_dir: Option<&Path>,
2529) -> Result<Option<PathBuf>, WrapperError> {
2530    if !final_target.is_absolute() {
2531        return Err(WrapperError::RelativeFinalTarget(
2532            final_target.to_path_buf(),
2533        ));
2534    }
2535    validate_dep_info_path_spelling(final_target, false)?;
2536    let target_metadata = fs::symlink_metadata(final_target).map_err(|source| {
2537        WrapperError::ReadOutDirDependency {
2538            path: final_target.to_path_buf(),
2539            source,
2540        }
2541    })?;
2542    if !target_metadata.file_type().is_dir() || target_metadata.file_type().is_symlink() {
2543        return Err(WrapperError::UnsafeFinalTarget(final_target.to_path_buf()));
2544    }
2545    let Some(out_dir) = out_dir else {
2546        return Ok(None);
2547    };
2548    if !out_dir.is_absolute() {
2549        return Err(WrapperError::RelativeOutDir(out_dir.to_path_buf()));
2550    }
2551    validate_dep_info_path_spelling(out_dir, false)?;
2552    let relative =
2553        out_dir
2554            .strip_prefix(final_target)
2555            .map_err(|_| WrapperError::OutDirOutsideFinalTarget {
2556                out_dir: out_dir.to_path_buf(),
2557                target: final_target.to_path_buf(),
2558            })?;
2559    if relative.as_os_str().is_empty() {
2560        return Err(WrapperError::OutDirOutsideFinalTarget {
2561            out_dir: out_dir.to_path_buf(),
2562            target: final_target.to_path_buf(),
2563        });
2564    }
2565    portable_package_relative_path(relative).map_err(|source| {
2566        WrapperError::ReadOutDirDependency {
2567            path: out_dir.to_path_buf(),
2568            source,
2569        }
2570    })?;
2571    let mut path = final_target.to_path_buf();
2572    for component in relative.components() {
2573        let std::path::Component::Normal(component) = component else {
2574            return Err(WrapperError::UnsafeOutDirDependency(out_dir.to_path_buf()));
2575        };
2576        path.push(component);
2577        let metadata =
2578            fs::symlink_metadata(&path).map_err(|source| WrapperError::ReadOutDirDependency {
2579                path: path.clone(),
2580                source,
2581            })?;
2582        if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
2583            return Err(WrapperError::UnsafeOutDirDependency(path));
2584        }
2585    }
2586    let canonical_target =
2587        fs::canonicalize(final_target).map_err(|source| WrapperError::ReadOutDirDependency {
2588            path: final_target.to_path_buf(),
2589            source,
2590        })?;
2591    let canonical_out_dir =
2592        fs::canonicalize(out_dir).map_err(|source| WrapperError::ReadOutDirDependency {
2593            path: out_dir.to_path_buf(),
2594            source,
2595        })?;
2596    if canonical_out_dir == canonical_target || !canonical_out_dir.starts_with(&canonical_target) {
2597        return Err(WrapperError::OutDirOutsideFinalTarget {
2598            out_dir: out_dir.to_path_buf(),
2599            target: final_target.to_path_buf(),
2600        });
2601    }
2602    Ok(Some(canonical_out_dir))
2603}
2604
2605fn final_out_dir_coordinate(
2606    final_target: &Path,
2607    out_dir: Option<&Path>,
2608) -> Result<Option<String>, WrapperError> {
2609    let Some(out_dir) = out_dir else {
2610        return Ok(None);
2611    };
2612    let relative =
2613        out_dir
2614            .strip_prefix(final_target)
2615            .map_err(|_| WrapperError::OutDirOutsideFinalTarget {
2616                out_dir: out_dir.to_path_buf(),
2617                target: final_target.to_path_buf(),
2618            })?;
2619    if relative.as_os_str().is_empty() {
2620        return Err(WrapperError::OutDirOutsideFinalTarget {
2621            out_dir: out_dir.to_path_buf(),
2622            target: final_target.to_path_buf(),
2623        });
2624    }
2625    portable_package_relative_path(relative)
2626        .map(Some)
2627        .map_err(|source| WrapperError::ReadOutDirDependency {
2628            path: out_dir.to_path_buf(),
2629            source,
2630        })
2631}
2632
2633pub(crate) fn validate_descriptor_observed_inputs(
2634    descriptor_target: &Path,
2635    sidecar: &DescriptorUnitSidecar,
2636) -> Result<(), WrapperError> {
2637    let unit = DescriptorCargoUnitId::from_hex(&sidecar.cargo_unit_id)?;
2638    validate_sidecar_out_dir_dependencies(unit, sidecar)
2639        .map_err(|error| WrapperError::InvalidCachedOutDirDependencies(error.to_string()))?;
2640    let target_metadata = fs::symlink_metadata(descriptor_target).map_err(|source| {
2641        WrapperError::ReadOutDirDependency {
2642            path: descriptor_target.to_path_buf(),
2643            source,
2644        }
2645    })?;
2646    if target_metadata.file_type().is_symlink() || !target_metadata.file_type().is_dir() {
2647        return Err(WrapperError::UnsafeOutDirDependency(
2648            descriptor_target.to_path_buf(),
2649        ));
2650    }
2651    let out_dir = if let Some(relative) = sidecar.out_dir.as_deref() {
2652        let mut path = descriptor_target.to_path_buf();
2653        for component in relative.split('/') {
2654            path.push(component);
2655            let metadata = fs::symlink_metadata(&path).map_err(|source| {
2656                WrapperError::ReadOutDirDependency {
2657                    path: path.clone(),
2658                    source,
2659                }
2660            })?;
2661            if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
2662                return Err(WrapperError::UnsafeOutDirDependency(path));
2663            }
2664        }
2665        Some(path)
2666    } else {
2667        None
2668    };
2669    let working_directory = canonical_plain_directory(&sidecar.dep_info_working_directory)?;
2670    if working_directory != sidecar.dep_info_working_directory {
2671        return Err(WrapperError::UnsafeObservedSource(
2672            sidecar.dep_info_working_directory.clone(),
2673        ));
2674    }
2675    let mut dep_info_path = descriptor_target.to_path_buf();
2676    for component in sidecar.dep_info_path.split('/') {
2677        dep_info_path.push(component);
2678    }
2679    validate_dep_info_output_path(descriptor_target, &dep_info_path)?;
2680    let mut descriptor_phase_environment = BTreeMap::new();
2681    descriptor_phase_environment.insert(CARGO_UNIT_ID_ENV.to_string(), Some(unit.to_string()));
2682    descriptor_phase_environment.insert(DESCRIPTOR_PHASE_ENV.to_string(), Some("1".to_string()));
2683    let observed = observe_rustc_inputs(
2684        &dep_info_path,
2685        &working_directory,
2686        out_dir.as_deref(),
2687        sidecar.out_dir.as_deref(),
2688        &descriptor_phase_environment,
2689    )?;
2690    if observed.out_dir_dependencies != sidecar.out_dir_dependencies
2691        || observed.source_dependencies != sidecar.source_dependencies
2692        || observed.environment_dependencies != sidecar.environment_dependencies
2693    {
2694        return Err(WrapperError::CachedObservedInputsMismatch { unit });
2695    }
2696    Ok(())
2697}
2698
2699fn validate_portable_relative_path(path: &str) -> Result<(), String> {
2700    if path.is_empty() {
2701        return Err("path is empty".to_string());
2702    }
2703    for component in path.split('/') {
2704        if component.is_empty() || matches!(component, "." | "..") {
2705            return Err(format!("invalid path component `{component}`"));
2706        }
2707        if component.contains('\\')
2708            || component.bytes().any(|byte| byte == 0)
2709            || component
2710                .chars()
2711                .any(|character| character.is_whitespace() && character != ' ')
2712        {
2713            return Err(format!("non-portable path component `{component}`"));
2714        }
2715    }
2716    Ok(())
2717}
2718
2719fn parse_rustc_dep_info(bytes: &[u8]) -> Result<ParsedDepInfo, String> {
2720    let text =
2721        std::str::from_utf8(bytes).map_err(|_| "dep-info contains a non-UTF-8 path".to_string())?;
2722    let mut main_dependencies = None::<String>;
2723    let mut phony_dependencies = Vec::<String>::new();
2724    let mut environment = BTreeMap::<String, Option<String>>::new();
2725    let mut saw_phony = false;
2726    let mut saw_metadata = false;
2727
2728    for (index, line) in text.lines().enumerate() {
2729        let line_number = index + 1;
2730        if line.is_empty() {
2731            continue;
2732        }
2733        if let Some(raw) = line.strip_prefix("# env-dep:") {
2734            saw_metadata = true;
2735            let (name, value) = raw
2736                .split_once('=')
2737                .map_or((raw, None), |(name, value)| (name, Some(value)));
2738            let name = decode_rustc_dep_info_environment(name).map_err(|reason| {
2739                format!("invalid environment dependency name at line {line_number}: {reason}")
2740            })?;
2741            if name.is_empty() || name.bytes().any(|byte| byte == 0) {
2742                return Err(format!(
2743                    "invalid environment dependency name at line {line_number}"
2744                ));
2745            }
2746            let value = value
2747                .map(decode_rustc_dep_info_environment)
2748                .transpose()
2749                .map_err(|reason| {
2750                    format!("invalid environment dependency value at line {line_number}: {reason}")
2751                })?;
2752            if environment.insert(name.clone(), value).is_some() {
2753                return Err(format!(
2754                    "dep-info repeats environment dependency `{name}` at line {line_number}"
2755                ));
2756            }
2757            continue;
2758        }
2759        if line.starts_with("# checksum:") {
2760            saw_metadata = true;
2761            continue;
2762        }
2763        if saw_metadata {
2764            return Err(format!(
2765                "dep-info rule appears after metadata at line {line_number}"
2766            ));
2767        }
2768        if let Some((target, dependencies)) = line.rsplit_once(": ") {
2769            if saw_phony {
2770                return Err(format!(
2771                    "dep-info main rule appears after phony targets at line {line_number}"
2772                ));
2773            }
2774            if target.is_empty() || dependencies.is_empty() {
2775                return Err(format!(
2776                    "dep-info main rule has an empty target or dependency set at line {line_number}"
2777                ));
2778            }
2779            if let Some(expected) = &main_dependencies {
2780                if expected != dependencies {
2781                    return Err(format!(
2782                        "dep-info main rules disagree at line {line_number}"
2783                    ));
2784                }
2785            } else {
2786                main_dependencies = Some(dependencies.to_string());
2787            }
2788            continue;
2789        }
2790        if let Some(target) = line.strip_suffix(':') {
2791            saw_phony = true;
2792            if target.is_empty() {
2793                return Err(format!(
2794                    "dep-info has an empty phony target at line {line_number}"
2795                ));
2796            }
2797            phony_dependencies.push(target.to_string());
2798            continue;
2799        }
2800        return Err(format!("unrecognized dep-info line {line_number}"));
2801    }
2802
2803    let main_dependencies =
2804        main_dependencies.ok_or_else(|| "dep-info contains no main rule".to_string())?;
2805    if phony_dependencies.is_empty() {
2806        return Err("dep-info contains no phony dependency targets".to_string());
2807    }
2808    if phony_dependencies.join(" ") != main_dependencies {
2809        return Err("dep-info main dependencies and phony targets disagree".to_string());
2810    }
2811    let decoded = phony_dependencies
2812        .into_iter()
2813        .map(|dependency| decode_rustc_dep_info_path(&dependency))
2814        .collect::<Result<Vec<_>, _>>()?;
2815    let canonical = decoded.iter().collect::<BTreeSet<_>>();
2816    if canonical.len() != decoded.len() {
2817        return Err("dep-info repeats a dependency target".to_string());
2818    }
2819    Ok(ParsedDepInfo {
2820        source_paths: decoded.into_iter().map(PathBuf::from).collect(),
2821        environment: environment
2822            .into_iter()
2823            .map(|(name, value)| ParsedEnvironmentDependency { name, value })
2824            .collect(),
2825    })
2826}
2827
2828fn decode_rustc_dep_info_path(value: &str) -> Result<String, String> {
2829    let mut decoded = String::with_capacity(value.len());
2830    let mut characters = value.chars().peekable();
2831    while let Some(character) = characters.next() {
2832        if character == '\\' && characters.peek() == Some(&' ') {
2833            characters.next();
2834            decoded.push(' ');
2835        } else {
2836            if character == ' ' {
2837                return Err("dep-info path contains an unescaped space".to_string());
2838            }
2839            if character.is_whitespace() && character != ' ' {
2840                return Err("dep-info path contains unrepresentable whitespace".to_string());
2841            }
2842            decoded.push(character);
2843        }
2844    }
2845    Ok(decoded)
2846}
2847
2848fn decode_rustc_dep_info_environment(value: &str) -> Result<String, String> {
2849    let mut decoded = String::with_capacity(value.len());
2850    let mut characters = value.chars();
2851    while let Some(character) = characters.next() {
2852        if character != '\\' {
2853            decoded.push(character);
2854            continue;
2855        }
2856        match characters.next() {
2857            Some('\\') => decoded.push('\\'),
2858            Some('n') => decoded.push('\n'),
2859            Some('r') => decoded.push('\r'),
2860            Some(_) => return Err("unsupported escaped character".to_string()),
2861            None => return Err("trailing escape".to_string()),
2862        }
2863    }
2864    Ok(decoded)
2865}
2866
2867fn portable_package_relative_path(path: &Path) -> io::Result<String> {
2868    let mut output = String::new();
2869    for component in path.components() {
2870        let std::path::Component::Normal(component) = component else {
2871            return Err(io::Error::new(
2872                io::ErrorKind::InvalidData,
2873                format!(
2874                    "package-relative path is not normalized: `{}`",
2875                    path.display()
2876                ),
2877            ));
2878        };
2879        let component = component.to_str().ok_or_else(|| {
2880            io::Error::new(
2881                io::ErrorKind::InvalidData,
2882                "package source closure contains a non-UTF-8 relative path",
2883            )
2884        })?;
2885        if component.contains('\\')
2886            || component
2887                .chars()
2888                .any(|character| character.is_whitespace() && character != ' ')
2889        {
2890            return Err(io::Error::new(
2891                io::ErrorKind::InvalidData,
2892                format!("path component is ambiguous in rustc dep-info: `{component}`"),
2893            ));
2894        }
2895        if !output.is_empty() {
2896            output.push('/');
2897        }
2898        output.push_str(component);
2899    }
2900    if output.is_empty() {
2901        return Err(io::Error::new(
2902            io::ErrorKind::InvalidData,
2903            "package source closure contains an empty relative path",
2904        ));
2905    }
2906    Ok(output)
2907}
2908
2909fn hash_file(path: &Path, domain: &[u8]) -> io::Result<[u8; 32]> {
2910    let mut file = File::open(path)?;
2911    let mut hasher = Sha256::new();
2912    hasher.update(domain);
2913    let mut buffer = [0_u8; 64 * 1024];
2914    loop {
2915        let read = file.read(&mut buffer)?;
2916        if read == 0 {
2917            break;
2918        }
2919        hasher.update(&buffer[..read]);
2920    }
2921    Ok(hasher.finalize().into())
2922}
2923
2924fn hash_file_two_domains(
2925    path: &Path,
2926    first_domain: &[u8],
2927    second_domain: &[u8],
2928) -> io::Result<([u8; 32], [u8; 32])> {
2929    let mut file = File::open(path)?;
2930    let mut first = Sha256::new();
2931    first.update(first_domain);
2932    let mut second = Sha256::new();
2933    second.update(second_domain);
2934    let mut buffer = [0_u8; 64 * 1024];
2935    loop {
2936        let read = file.read(&mut buffer)?;
2937        if read == 0 {
2938            break;
2939        }
2940        first.update(&buffer[..read]);
2941        second.update(&buffer[..read]);
2942    }
2943    Ok((first.finalize().into(), second.finalize().into()))
2944}
2945
2946pub(crate) fn descriptor_input_content_hash(path: &Path) -> io::Result<String> {
2947    hash_file(path, FILE_HASH_DOMAIN).map(|digest| hex_digest(&digest))
2948}
2949
2950#[cfg(test)]
2951pub(crate) fn descriptor_out_dir_dependency_content_hash(path: &Path) -> io::Result<String> {
2952    hash_file(path, OUT_DIR_FILE_HASH_DOMAIN).map(|digest| hex_digest(&digest))
2953}
2954
2955#[cfg(test)]
2956pub(crate) fn descriptor_source_dependency_content_hash(path: &Path) -> io::Result<String> {
2957    hash_file(path, OBSERVED_SOURCE_FILE_HASH_DOMAIN).map(|digest| hex_digest(&digest))
2958}
2959
2960#[cfg(test)]
2961pub(crate) fn descriptor_environment_dependency_value_hash(name: &str, value: &str) -> String {
2962    observed_environment_value_hash(name, b"exact-value", value.as_bytes())
2963}
2964
2965pub(crate) fn descriptor_package_source_closure_hash(
2966    package_root: &Path,
2967    excluded_subtree: &Path,
2968) -> io::Result<String> {
2969    hash_package_source_closure(package_root, Some(excluded_subtree))
2970        .map(|digest| hex_digest(&digest))
2971}
2972
2973#[cfg(test)]
2974pub(crate) fn descriptor_object_content_hash(path: &Path) -> io::Result<String> {
2975    hash_file(path, DESCRIPTOR_OBJECT_HASH_DOMAIN).map(|digest| hex_digest(&digest))
2976}
2977
2978/// Hash one exact Cargo-enumerated artifact using the link-manifest domain.
2979///
2980/// The linker uses this same operation before extraction so a host-local path
2981/// cannot be swapped after the root manifest was assembled.
2982pub fn link_artifact_content_hash(path: &Path) -> io::Result<SemanticHash> {
2983    hash_file(path, LINK_ARTIFACT_HASH_DOMAIN).map(SemanticHash::from_bytes)
2984}
2985
2986fn hash_bytes(domain: &[u8], bytes: &[u8]) -> [u8; 32] {
2987    let mut hasher = Sha256::new();
2988    hasher.update(domain);
2989    hasher.update((bytes.len() as u64).to_be_bytes());
2990    hasher.update(bytes);
2991    hasher.finalize().into()
2992}
2993
2994fn exact_sha256_hex(bytes: &[u8]) -> String {
2995    let digest: [u8; 32] = Sha256::digest(bytes).into();
2996    hex_digest(&digest)
2997}
2998
2999fn hash_canonical(domain: &[u8], f: impl FnOnce(&mut CanonicalHasher)) -> [u8; 32] {
3000    let mut hash = CanonicalHasher::new(domain);
3001    f(&mut hash);
3002    hash.finish()
3003}
3004
3005struct CanonicalHasher(Sha256);
3006
3007impl CanonicalHasher {
3008    fn new(domain: &[u8]) -> Self {
3009        let mut hash = Sha256::new();
3010        hash.update((domain.len() as u64).to_be_bytes());
3011        hash.update(domain);
3012        Self(hash)
3013    }
3014
3015    fn field(&mut self, name: &str, value: &[u8]) {
3016        self.0.update((name.len() as u64).to_be_bytes());
3017        self.0.update(name.as_bytes());
3018        self.0.update((value.len() as u64).to_be_bytes());
3019        self.0.update(value);
3020    }
3021
3022    fn optional(&mut self, name: &str, value: Option<&[u8]>) {
3023        match value {
3024            Some(value) => {
3025                self.field(&format!("{name}:some"), value);
3026            }
3027            None => self.field(&format!("{name}:none"), &[]),
3028        }
3029    }
3030
3031    fn set<'a>(&mut self, name: &str, values: impl IntoIterator<Item = &'a [u8]>) {
3032        let values = values.into_iter().collect::<Vec<_>>();
3033        self.field(&format!("{name}:len"), &(values.len() as u64).to_be_bytes());
3034        for value in values {
3035            self.field(name, value);
3036        }
3037    }
3038
3039    fn map(&mut self, name: &str, values: &BTreeMap<String, String>) {
3040        self.field(&format!("{name}:len"), &(values.len() as u64).to_be_bytes());
3041        for (key, value) in values {
3042            self.field(&format!("{name}:key"), key.as_bytes());
3043            self.field(&format!("{name}:value"), value.as_bytes());
3044        }
3045    }
3046
3047    fn digest_map(&mut self, name: &str, values: &BTreeMap<String, [u8; 32]>) {
3048        self.field(&format!("{name}:len"), &(values.len() as u64).to_be_bytes());
3049        for (key, value) in values {
3050            self.field(&format!("{name}:key"), key.as_bytes());
3051            self.field(&format!("{name}:value"), value);
3052        }
3053    }
3054
3055    fn finish(self) -> [u8; 32] {
3056        self.0.finalize().into()
3057    }
3058}
3059
3060fn hex_digest(digest: &[u8; 32]) -> String {
3061    use fmt::Write as _;
3062
3063    let mut output = String::with_capacity(64);
3064    for byte in digest {
3065        let _ = write!(output, "{byte:02x}");
3066    }
3067    output
3068}
3069
3070fn atomic_write_exact(path: &Path, bytes: &[u8]) -> Result<(), FinalUnitMapError> {
3071    let parent = path
3072        .parent()
3073        .ok_or_else(|| FinalUnitMapError::PathWithoutParent(path.to_path_buf()))?;
3074    fs::create_dir_all(parent).map_err(|source| FinalUnitMapError::CreateDirectory {
3075        path: parent.to_path_buf(),
3076        source,
3077    })?;
3078
3079    let nonce = ATOMIC_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
3080    let file_name = path
3081        .file_name()
3082        .and_then(OsStr::to_str)
3083        .ok_or_else(|| FinalUnitMapError::InvalidFilename(path.to_path_buf()))?;
3084    let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
3085    let mut file = OpenOptions::new()
3086        .create_new(true)
3087        .write(true)
3088        .open(&temporary)
3089        .map_err(|source| FinalUnitMapError::Write {
3090            path: temporary.clone(),
3091            source,
3092        })?;
3093    file.write_all(bytes)
3094        .and_then(|()| file.sync_all())
3095        .map_err(|source| FinalUnitMapError::Write {
3096            path: temporary.clone(),
3097            source,
3098        })?;
3099    drop(file);
3100
3101    match fs::hard_link(&temporary, path) {
3102        Ok(()) => {
3103            fs::remove_file(&temporary).map_err(|source| FinalUnitMapError::Write {
3104                path: temporary,
3105                source,
3106            })?;
3107            Ok(())
3108        }
3109        Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
3110            let existing = fs::read(path).map_err(|source| FinalUnitMapError::Write {
3111                path: path.to_path_buf(),
3112                source,
3113            })?;
3114            let _ = fs::remove_file(&temporary);
3115            if existing == bytes {
3116                Ok(())
3117            } else {
3118                Err(FinalUnitMapError::ConflictingContent(path.to_path_buf()))
3119            }
3120        }
3121        Err(source) => Err(FinalUnitMapError::Write {
3122            path: path.to_path_buf(),
3123            source,
3124        }),
3125    }
3126}
3127
3128fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), WrapperError> {
3129    let parent = path
3130        .parent()
3131        .ok_or_else(|| WrapperError::SidecarWithoutParent(path.to_path_buf()))?;
3132    fs::create_dir_all(parent).map_err(|source| WrapperError::CreateStagingDirectory {
3133        path: parent.to_path_buf(),
3134        source,
3135    })?;
3136
3137    let nonce = ATOMIC_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
3138    let file_name = path
3139        .file_name()
3140        .and_then(OsStr::to_str)
3141        .ok_or_else(|| WrapperError::InvalidSidecarFileName(path.to_path_buf()))?;
3142    let temporary = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), nonce));
3143    let mut file = OpenOptions::new()
3144        .create_new(true)
3145        .write(true)
3146        .open(&temporary)
3147        .map_err(|source| WrapperError::WriteSidecar {
3148            path: temporary.clone(),
3149            source,
3150        })?;
3151    file.write_all(bytes)
3152        .and_then(|()| file.write_all(b"\n"))
3153        .and_then(|()| file.sync_all())
3154        .map_err(|source| WrapperError::WriteSidecar {
3155            path: temporary.clone(),
3156            source,
3157        })?;
3158    drop(file);
3159
3160    match fs::hard_link(&temporary, path) {
3161        Ok(()) => {
3162            fs::remove_file(&temporary).map_err(|source| WrapperError::WriteSidecar {
3163                path: temporary,
3164                source,
3165            })?;
3166            Ok(())
3167        }
3168        Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
3169            let existing = fs::read(path).map_err(|source| WrapperError::WriteSidecar {
3170                path: path.to_path_buf(),
3171                source,
3172            })?;
3173            let mut expected = bytes.to_vec();
3174            expected.push(b'\n');
3175            let _ = fs::remove_file(&temporary);
3176            if existing == expected {
3177                Ok(())
3178            } else {
3179                Err(WrapperError::ConflictingUnitSidecar(path.to_path_buf()))
3180            }
3181        }
3182        Err(source) => Err(WrapperError::WriteSidecar {
3183            path: path.to_path_buf(),
3184            source,
3185        }),
3186    }
3187}
3188
3189#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
3190pub struct DescriptorUnitSidecar {
3191    /// Sidecar schema version.
3192    pub schema_version: u16,
3193    /// Lowercase-hex descriptor Cargo-unit ID.
3194    pub cargo_unit_id: String,
3195    /// Host-local Cargo manifest used only to join this sidecar to the exact
3196    /// compiler-artifact message from the same invocation.
3197    pub cargo_manifest_path: Option<PathBuf>,
3198    /// Cargo package name exposed to this rustc unit.
3199    pub cargo_package_name: Option<String>,
3200    /// Cargo package version exposed to this rustc unit.
3201    pub cargo_package_version: Option<String>,
3202    /// Cargo profile exposed to this rustc unit.
3203    pub cargo_profile: Option<String>,
3204    /// Phase-invariant hash of Cargo/rustc profile-affecting inputs.
3205    pub cargo_profile_fingerprint: String,
3206    /// Whether Cargo marked this unit as belonging to a selected root package.
3207    pub cargo_primary_package: bool,
3208    /// Cargo's exact `-C extra-filename` discriminator for this rustc unit.
3209    #[serde(default)]
3210    pub cargo_extra_filename: Option<String>,
3211    /// Rust crate name.
3212    pub crate_name: String,
3213    /// Normalized crate types.
3214    pub crate_types: Vec<String>,
3215    /// Effective target triple when rustc received one explicitly.
3216    pub target: Option<String>,
3217    /// Normalized rustc cfgs.
3218    pub cfgs: Vec<String>,
3219    /// Cargo/rustc feature cfgs.
3220    pub features: Vec<String>,
3221    /// Content hash of the exact primary source input.
3222    pub source_hash: String,
3223    /// Host-independent digest of the conservative package-local source
3224    /// closure used to derive this unit's immutable identity.
3225    pub package_source_closure_hash: String,
3226    /// Exact `--extern` inputs, keyed by extern name. Paths are host-local join
3227    /// coordinates; only their content hashes participate in semantic unit
3228    /// identity.
3229    pub dependency_artifacts: BTreeMap<String, DescriptorDependencyArtifact>,
3230    /// Hash of every normalized descriptor-phase rustc input.
3231    pub normalized_rustc_inputs_hash: String,
3232    /// Phase-invariant identity of the semantic Cargo/build-script environment.
3233    pub logical_environment_hash: String,
3234    /// Descriptor-target-relative dep-info path produced by this exact rustc
3235    /// invocation. The cache reopens this Cargo-authoritative file when Cargo
3236    /// reports the unit fresh.
3237    pub dep_info_path: String,
3238    /// Exact canonical directory against which rustc spelled relative dep-info
3239    /// source paths during descriptor compilation.
3240    pub dep_info_working_directory: PathBuf,
3241    /// Cargo-target-relative build-script output directory. This is a
3242    /// host-local cache coordinate and never enters the semantic unit key.
3243    pub out_dir: Option<String>,
3244    /// Exact rustc-declared source dependencies consumed beneath `OUT_DIR` by
3245    /// the successful descriptor compilation.
3246    pub out_dir_dependencies: Vec<DescriptorOutDirDependency>,
3247    /// Every other exact rustc-declared source dependency, retained under its
3248    /// canonical host-local absolute path.
3249    pub source_dependencies: Vec<DescriptorSourceDependency>,
3250    /// Every non-wrapper-owned environment dependency rustc declared. Values
3251    /// are domain-separated hashes; plaintext values never leave dep-info.
3252    pub environment_dependencies: Vec<DescriptorEnvironmentDependency>,
3253    /// Private generation fingerprint of the complete effective rustc
3254    /// environment, excluding only cargo-proa wrapper-control variables.
3255    /// Plaintext environment values are never persisted.
3256    pub realized_environment_hash: String,
3257    /// Descriptor-only codegen policy.
3258    pub descriptor_codegen: DescriptorCodegenSidecar,
3259    /// Staging-directory-relative exact object path.
3260    pub descriptor_object: String,
3261    /// Content hash of the exact descriptor object.
3262    pub descriptor_object_hash: String,
3263}
3264
3265/// One exact rustc `--extern` input retained for Cargo-artifact joining.
3266#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
3267#[serde(deny_unknown_fields)]
3268pub struct DescriptorDependencyArtifact {
3269    /// Exact host-local path passed to rustc by Cargo.
3270    pub path: PathBuf,
3271    /// Descriptor-domain content hash captured before descriptor compilation.
3272    pub content_hash: String,
3273}
3274
3275/// One rustc-declared source dependency beneath a build script's `OUT_DIR`.
3276#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
3277#[serde(deny_unknown_fields)]
3278pub struct DescriptorOutDirDependency {
3279    /// Slash-separated path relative to the unit's exact `OUT_DIR`.
3280    pub relative_path: String,
3281    /// Domain-separated hash of the bytes read by rustc.
3282    pub content_hash: String,
3283}
3284
3285/// One rustc-declared source dependency outside the unit's exact `OUT_DIR`.
3286#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
3287#[serde(deny_unknown_fields)]
3288pub struct DescriptorSourceDependency {
3289    /// Canonical host-local absolute source path.
3290    pub absolute_path: PathBuf,
3291    /// Domain-separated hash of the exact bytes read after rustc completed.
3292    pub content_hash: String,
3293}
3294
3295/// One environment variable tracked by rustc's dep-info protocol.
3296#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
3297#[serde(deny_unknown_fields)]
3298pub struct DescriptorEnvironmentDependency {
3299    /// Exact decoded environment-variable name.
3300    pub name: String,
3301    /// `None` means rustc observed the variable absent. `Some` is the
3302    /// domain-separated hash of its decoded value; an empty value is distinct
3303    /// from absence.
3304    pub value_hash: Option<String>,
3305}
3306
3307/// Descriptor-only rustc policy recorded beside each exact unit object.
3308#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
3309pub struct DescriptorCodegenSidecar {
3310    /// Descriptor pass always emits one object from one codegen unit.
3311    pub codegen_units: u32,
3312    /// Incremental object production is disabled.
3313    pub incremental: bool,
3314    /// Retain otherwise-dead transport statics.
3315    pub link_dead_code: bool,
3316    /// Descriptor-pass LTO policy.
3317    pub lto: String,
3318    /// Descriptor-pass strip policy.
3319    pub strip: String,
3320}
3321
3322/// One validated wrapper sidecar and its exact descriptor object.
3323#[derive(Clone, Debug, PartialEq, Eq)]
3324pub struct ValidatedDescriptorUnit {
3325    /// Strong realized Cargo-unit identity.
3326    pub unit: DescriptorCargoUnitId,
3327    /// Parsed, version-checked sidecar.
3328    pub sidecar: DescriptorUnitSidecar,
3329    /// Exact sidecar path in invocation staging or an immutable cache slot.
3330    pub sidecar_path: PathBuf,
3331    /// Exact descriptor object whose content hash was validated.
3332    pub descriptor_object: PathBuf,
3333}
3334
3335/// Phase-invariant identity used to join a final rustc invocation to one
3336/// descriptor Cargo unit.
3337///
3338/// This deliberately excludes target-directory paths, output paths,
3339/// dependency artifact paths, and the final plan's injected cfgs.
3340#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
3341#[serde(deny_unknown_fields)]
3342pub struct FinalUnitCoordinate {
3343    /// Exact Cargo manifest shared by descriptor and final compilation.
3344    pub cargo_manifest_path: PathBuf,
3345    /// Cargo package name.
3346    pub cargo_package_name: String,
3347    /// Cargo package version.
3348    pub cargo_package_version: String,
3349    /// Cargo profile name when Cargo exposed one directly to rustc.
3350    pub cargo_profile: Option<String>,
3351    /// Stable profile-affecting rustc/environment fingerprint.
3352    pub cargo_profile_fingerprint: String,
3353    /// Whether Cargo marked this unit as belonging to a selected root package.
3354    pub cargo_primary_package: bool,
3355    /// Cargo's exact phase-invariant rustc output discriminator. Selected
3356    /// primary bins and libraries may intentionally use an unhashed output.
3357    pub cargo_extra_filename: Option<String>,
3358    /// Rust crate name.
3359    pub crate_name: String,
3360    /// Normalized crate types.
3361    pub crate_types: Vec<String>,
3362    /// Effective explicit target triple.
3363    pub target: Option<String>,
3364    /// Cargo feature cfg values.
3365    pub features: Vec<String>,
3366    /// Descriptor-domain content hash of the exact primary source.
3367    pub source_hash: String,
3368    /// Semantic Cargo/build-script environment.
3369    pub logical_environment_hash: String,
3370    /// Normalized cfgs supplied by Cargo before wrapper-owned final-plan cfgs.
3371    pub cfgs: Vec<String>,
3372}
3373
3374/// One exact descriptor-to-final Cargo-unit mapping.
3375#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
3376#[serde(deny_unknown_fields)]
3377pub struct FinalUnitMapEntry {
3378    /// Phase-invariant semantic coordinate.
3379    pub coordinate: FinalUnitCoordinate,
3380    /// Original descriptor Cargo-unit ID exposed to proc macros.
3381    pub cargo_unit_id: String,
3382    /// Exact generated-source inputs that must be present before final
3383    /// compilation and must be re-observed by final rustc dep-info.
3384    pub out_dir_dependencies: Vec<DescriptorOutDirDependency>,
3385    /// Exact non-`OUT_DIR` sources that must remain byte-identical and must be
3386    /// re-observed by final rustc dep-info.
3387    pub source_dependencies: Vec<DescriptorSourceDependency>,
3388    /// Redacted user/Cargo environment observations that must remain exact
3389    /// across descriptor and final compilation.
3390    pub environment_dependencies: Vec<DescriptorEnvironmentDependency>,
3391}
3392
3393/// Content-addressed descriptor-to-final unit map consumed by `final-v2`.
3394#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
3395#[serde(deny_unknown_fields)]
3396pub struct FinalUnitMap {
3397    /// External file discriminator.
3398    pub format: String,
3399    /// Exact schema version.
3400    pub schema_version: u16,
3401    /// Plan this mapping authorizes.
3402    pub plan_id: String,
3403    /// Tagged `sha256:<hex>` digest of the exact linked-plan bytes.
3404    pub plan_file_hash: String,
3405    /// Canonically sorted, unambiguous mappings.
3406    pub entries: Vec<FinalUnitMapEntry>,
3407}
3408
3409/// Exact file written for a final Cargo invocation.
3410#[derive(Clone, Debug, PartialEq, Eq)]
3411pub struct WrittenFinalUnitMap {
3412    /// Absolute content-addressed path.
3413    pub path: PathBuf,
3414    /// SHA-256 of the exact bytes at `path`.
3415    pub content_hash: String,
3416}
3417
3418/// Build and atomically publish a final unit map from validated descriptor
3419/// sidecars.
3420pub fn write_content_addressed_final_unit_map(
3421    directory: &Path,
3422    plan_id: PlanId,
3423    plan_file_hash: &str,
3424    units: &[ValidatedDescriptorUnit],
3425) -> Result<WrittenFinalUnitMap, FinalUnitMapError> {
3426    if !directory.is_absolute() {
3427        return Err(FinalUnitMapError::RelativeDirectory(
3428            directory.to_path_buf(),
3429        ));
3430    }
3431    validate_tagged_sha256(plan_file_hash).map_err(|reason| {
3432        FinalUnitMapError::InvalidPlanFileHash {
3433            value: plan_file_hash.to_string(),
3434            reason,
3435        }
3436    })?;
3437
3438    let mut entries = units
3439        .iter()
3440        .map(final_unit_map_entry)
3441        .collect::<Result<Vec<_>, _>>()?;
3442    entries.sort_by(|left, right| {
3443        left.coordinate
3444            .cmp(&right.coordinate)
3445            .then_with(|| left.cargo_unit_id.cmp(&right.cargo_unit_id))
3446    });
3447    for pair in entries.windows(2) {
3448        if pair[0].coordinate == pair[1].coordinate {
3449            return Err(FinalUnitMapError::AmbiguousCoordinate {
3450                coordinate: pair[0].coordinate.clone(),
3451                first: pair[0].cargo_unit_id.clone(),
3452                second: pair[1].cargo_unit_id.clone(),
3453            });
3454        }
3455    }
3456
3457    let unit_map = FinalUnitMap {
3458        format: FINAL_UNIT_MAP_FORMAT.to_string(),
3459        schema_version: FINAL_UNIT_MAP_SCHEMA_VERSION,
3460        plan_id: plan_id.to_string(),
3461        plan_file_hash: plan_file_hash.to_string(),
3462        entries,
3463    };
3464    let mut bytes = serde_json::to_vec_pretty(&unit_map).map_err(FinalUnitMapError::Serialize)?;
3465    bytes.push(b'\n');
3466    let content_hash = exact_sha256_hex(&bytes);
3467    let path = directory.join(format!("{content_hash}.final-unit-map.json"));
3468    atomic_write_exact(&path, &bytes)?;
3469    Ok(WrittenFinalUnitMap { path, content_hash })
3470}
3471
3472fn final_unit_map_entry(
3473    unit: &ValidatedDescriptorUnit,
3474) -> Result<FinalUnitMapEntry, FinalUnitMapError> {
3475    let sidecar = &unit.sidecar;
3476    if sidecar.cargo_unit_id != unit.unit.to_string() {
3477        return Err(FinalUnitMapError::UnitIdMismatch {
3478            validated: unit.unit.to_string(),
3479            sidecar: sidecar.cargo_unit_id.clone(),
3480        });
3481    }
3482    let cargo_manifest_path = sidecar.cargo_manifest_path.clone().ok_or_else(|| {
3483        FinalUnitMapError::MissingCoordinateField {
3484            unit: unit.unit.to_string(),
3485            field: "cargo_manifest_path",
3486        }
3487    })?;
3488    if !cargo_manifest_path.is_absolute() {
3489        return Err(FinalUnitMapError::RelativeManifestPath {
3490            unit: unit.unit.to_string(),
3491            path: cargo_manifest_path,
3492        });
3493    }
3494    let cargo_package_name =
3495        required_sidecar_field(unit, "cargo_package_name", &sidecar.cargo_package_name)?;
3496    let cargo_package_version = required_sidecar_field(
3497        unit,
3498        "cargo_package_version",
3499        &sidecar.cargo_package_version,
3500    )?;
3501    validate_lower_sha256(&sidecar.cargo_profile_fingerprint).map_err(|reason| {
3502        FinalUnitMapError::InvalidProfileFingerprint {
3503            unit: unit.unit.to_string(),
3504            value: sidecar.cargo_profile_fingerprint.clone(),
3505            reason,
3506        }
3507    })?;
3508    let cargo_extra_filename = sidecar.cargo_extra_filename.clone();
3509    if let Some(value) = &cargo_extra_filename {
3510        validate_cargo_extra_filename(value).map_err(|reason| {
3511            FinalUnitMapError::InvalidCargoExtraFilename {
3512                unit: unit.unit.to_string(),
3513                value: value.clone(),
3514                reason,
3515            }
3516        })?;
3517    }
3518    let crate_types = canonical_sidecar_values(unit, "crate_types", &sidecar.crate_types)?;
3519    let cfgs = canonical_sidecar_values(unit, "cfgs", &sidecar.cfgs)?;
3520    if cfgs.iter().any(|cfg| is_final_plan_cfg(cfg)) {
3521        return Err(FinalUnitMapError::ReservedDescriptorCfg {
3522            unit: unit.unit.to_string(),
3523        });
3524    }
3525    let features = canonical_sidecar_values(unit, "features", &sidecar.features)?;
3526    let derived_features = cfg_features(cfgs.iter().map(String::as_str));
3527    if features != derived_features {
3528        return Err(FinalUnitMapError::FeatureCfgMismatch {
3529            unit: unit.unit.to_string(),
3530            features,
3531            derived: derived_features,
3532        });
3533    }
3534    validate_lower_sha256(&sidecar.source_hash).map_err(|reason| {
3535        FinalUnitMapError::InvalidSourceHash {
3536            unit: unit.unit.to_string(),
3537            value: sidecar.source_hash.clone(),
3538            reason,
3539        }
3540    })?;
3541    validate_lower_sha256(&sidecar.package_source_closure_hash).map_err(|reason| {
3542        FinalUnitMapError::InvalidPackageSourceClosureHash {
3543            unit: unit.unit.to_string(),
3544            value: sidecar.package_source_closure_hash.clone(),
3545            reason,
3546        }
3547    })?;
3548    validate_lower_sha256(&sidecar.logical_environment_hash).map_err(|reason| {
3549        FinalUnitMapError::InvalidLogicalEnvironmentHash {
3550            unit: unit.unit.to_string(),
3551            value: sidecar.logical_environment_hash.clone(),
3552            reason,
3553        }
3554    })?;
3555
3556    Ok(FinalUnitMapEntry {
3557        coordinate: FinalUnitCoordinate {
3558            cargo_manifest_path,
3559            cargo_package_name,
3560            cargo_package_version,
3561            cargo_profile: sidecar.cargo_profile.clone(),
3562            cargo_profile_fingerprint: sidecar.cargo_profile_fingerprint.clone(),
3563            cargo_primary_package: sidecar.cargo_primary_package,
3564            cargo_extra_filename,
3565            crate_name: sidecar.crate_name.clone(),
3566            crate_types,
3567            target: sidecar.target.clone(),
3568            features,
3569            source_hash: sidecar.source_hash.clone(),
3570            logical_environment_hash: sidecar.logical_environment_hash.clone(),
3571            cfgs,
3572        },
3573        cargo_unit_id: unit.unit.to_string(),
3574        out_dir_dependencies: sidecar.out_dir_dependencies.clone(),
3575        source_dependencies: sidecar.source_dependencies.clone(),
3576        environment_dependencies: sidecar.environment_dependencies.clone(),
3577    })
3578}
3579
3580fn required_sidecar_field(
3581    unit: &ValidatedDescriptorUnit,
3582    field: &'static str,
3583    value: &Option<String>,
3584) -> Result<String, FinalUnitMapError> {
3585    value
3586        .as_ref()
3587        .filter(|value| !value.is_empty())
3588        .cloned()
3589        .ok_or_else(|| FinalUnitMapError::MissingCoordinateField {
3590            unit: unit.unit.to_string(),
3591            field,
3592        })
3593}
3594
3595fn canonical_sidecar_values(
3596    unit: &ValidatedDescriptorUnit,
3597    field: &'static str,
3598    values: &[String],
3599) -> Result<Vec<String>, FinalUnitMapError> {
3600    let canonical = values.iter().cloned().collect::<BTreeSet<_>>();
3601    if canonical.len() != values.len() || canonical.iter().any(String::is_empty) {
3602        return Err(FinalUnitMapError::NonCanonicalCoordinateValues {
3603            unit: unit.unit.to_string(),
3604            field,
3605        });
3606    }
3607    Ok(canonical.into_iter().collect())
3608}
3609
3610#[derive(Debug)]
3611struct LoadedFinalUnitMap {
3612    entries: BTreeMap<FinalUnitCoordinate, LoadedFinalUnit>,
3613}
3614
3615impl LoadedFinalUnitMap {
3616    fn resolve(&self, coordinate: Option<&FinalUnitCoordinate>) -> Option<&LoadedFinalUnit> {
3617        coordinate.and_then(|coordinate| self.entries.get(coordinate))
3618    }
3619}
3620
3621#[derive(Debug)]
3622struct LoadedFinalUnit {
3623    cargo_unit_id: DescriptorCargoUnitId,
3624    out_dir_dependencies: Vec<DescriptorOutDirDependency>,
3625    source_dependencies: Vec<DescriptorSourceDependency>,
3626    environment_dependencies: Vec<DescriptorEnvironmentDependency>,
3627}
3628
3629fn load_final_unit_map_from_env() -> Result<LoadedFinalUnitMap, WrapperError> {
3630    if env::var(FINAL_PHASE_ENV).as_deref() != Ok("1") {
3631        return Err(WrapperError::InvalidFinalPhase);
3632    }
3633    let expected_plan_id = env::var(FINAL_PLAN_ID_ENV)
3634        .map_err(|_| WrapperError::MissingEnvironment(FINAL_PLAN_ID_ENV))?;
3635    let expected_plan_file_hash = env::var(FINAL_PLAN_FILE_HASH_ENV)
3636        .map_err(|_| WrapperError::MissingEnvironment(FINAL_PLAN_FILE_HASH_ENV))?;
3637    validate_tagged_sha256(&expected_plan_file_hash).map_err(|reason| {
3638        WrapperError::InvalidSha256 {
3639            name: FINAL_PLAN_FILE_HASH_ENV,
3640            value: expected_plan_file_hash.clone(),
3641            reason,
3642        }
3643    })?;
3644    let path = env::var_os(FINAL_UNIT_MAP_PATH_ENV)
3645        .map(PathBuf::from)
3646        .ok_or(WrapperError::MissingEnvironment(FINAL_UNIT_MAP_PATH_ENV))?;
3647    if !path.is_absolute() {
3648        return Err(WrapperError::RelativeFinalUnitMap(path));
3649    }
3650    let expected_hash = env::var(FINAL_UNIT_MAP_HASH_ENV)
3651        .map_err(|_| WrapperError::MissingEnvironment(FINAL_UNIT_MAP_HASH_ENV))?;
3652    validate_lower_sha256(&expected_hash).map_err(|reason| WrapperError::InvalidSha256 {
3653        name: FINAL_UNIT_MAP_HASH_ENV,
3654        value: expected_hash.clone(),
3655        reason,
3656    })?;
3657    let expected_filename = format!("{expected_hash}.final-unit-map.json");
3658    if path.file_name() != Some(OsStr::new(&expected_filename)) {
3659        return Err(WrapperError::FinalUnitMapFilename {
3660            path,
3661            expected: expected_filename,
3662        });
3663    }
3664    let bytes = fs::read(&path).map_err(|source| WrapperError::ReadFinalUnitMap {
3665        path: path.clone(),
3666        source,
3667    })?;
3668    let actual_hash = exact_sha256_hex(&bytes);
3669    if actual_hash != expected_hash {
3670        return Err(WrapperError::FinalUnitMapHashMismatch {
3671            path,
3672            expected: expected_hash,
3673            actual: actual_hash,
3674        });
3675    }
3676    let unit_map: FinalUnitMap =
3677        serde_json::from_slice(&bytes).map_err(|source| WrapperError::ParseFinalUnitMap {
3678            path: path.clone(),
3679            source,
3680        })?;
3681    if unit_map.format != FINAL_UNIT_MAP_FORMAT {
3682        return Err(WrapperError::FinalUnitMapFormat(unit_map.format));
3683    }
3684    if unit_map.schema_version != FINAL_UNIT_MAP_SCHEMA_VERSION {
3685        return Err(WrapperError::FinalUnitMapSchema {
3686            actual: unit_map.schema_version,
3687            expected: FINAL_UNIT_MAP_SCHEMA_VERSION,
3688        });
3689    }
3690    if unit_map.plan_id != expected_plan_id {
3691        return Err(WrapperError::FinalUnitMapPlanId {
3692            expected: expected_plan_id,
3693            actual: unit_map.plan_id,
3694        });
3695    }
3696    if unit_map.plan_file_hash != expected_plan_file_hash {
3697        return Err(WrapperError::FinalUnitMapPlanFileHash {
3698            expected: expected_plan_file_hash,
3699            actual: unit_map.plan_file_hash,
3700        });
3701    }
3702
3703    let mut entries = BTreeMap::new();
3704    let mut previous = None;
3705    for entry in unit_map.entries {
3706        validate_final_coordinate(&entry.coordinate)?;
3707        if previous
3708            .as_ref()
3709            .is_some_and(|coordinate| coordinate > &entry.coordinate)
3710        {
3711            return Err(WrapperError::NonCanonicalFinalUnitMap);
3712        }
3713        previous = Some(entry.coordinate.clone());
3714        validate_out_dir_dependency_records(&entry.out_dir_dependencies)?;
3715        validate_source_dependency_records(&entry.source_dependencies)?;
3716        validate_environment_dependency_records(&entry.environment_dependencies)?;
3717        let cargo_unit_id = DescriptorCargoUnitId::from_hex(&entry.cargo_unit_id)?;
3718        let loaded = LoadedFinalUnit {
3719            cargo_unit_id,
3720            out_dir_dependencies: entry.out_dir_dependencies,
3721            source_dependencies: entry.source_dependencies,
3722            environment_dependencies: entry.environment_dependencies,
3723        };
3724        if let Some(first) = entries.insert(entry.coordinate.clone(), loaded) {
3725            return Err(WrapperError::AmbiguousFinalUnitCoordinate {
3726                coordinate: entry.coordinate,
3727                first: first.cargo_unit_id.to_string(),
3728                second: cargo_unit_id.to_string(),
3729            });
3730        }
3731    }
3732    Ok(LoadedFinalUnitMap { entries })
3733}
3734
3735fn validate_final_coordinate(coordinate: &FinalUnitCoordinate) -> Result<(), WrapperError> {
3736    if !coordinate.cargo_manifest_path.is_absolute() {
3737        return Err(WrapperError::RelativeMappedManifest(
3738            coordinate.cargo_manifest_path.clone(),
3739        ));
3740    }
3741    for (field, values) in [
3742        ("crate_types", &coordinate.crate_types),
3743        ("features", &coordinate.features),
3744        ("cfgs", &coordinate.cfgs),
3745    ] {
3746        let canonical = values.iter().cloned().collect::<BTreeSet<_>>();
3747        if canonical.len() != values.len()
3748            || canonical.iter().any(String::is_empty)
3749            || canonical.into_iter().collect::<Vec<_>>() != *values
3750        {
3751            return Err(WrapperError::NonCanonicalFinalCoordinate(field));
3752        }
3753    }
3754    if coordinate.cfgs.iter().any(|cfg| is_final_plan_cfg(cfg)) {
3755        return Err(WrapperError::FinalCoordinateContainsPlanCfg);
3756    }
3757    if coordinate
3758        .cargo_profile
3759        .as_ref()
3760        .is_some_and(String::is_empty)
3761    {
3762        return Err(WrapperError::EmptyFinalProfile);
3763    }
3764    if let Some(value) = &coordinate.cargo_extra_filename {
3765        validate_cargo_extra_filename(value).map_err(|reason| {
3766            WrapperError::InvalidCargoExtraFilename {
3767                context: "final unit-map coordinate",
3768                value: value.clone(),
3769                reason,
3770            }
3771        })?;
3772    }
3773    validate_lower_sha256(&coordinate.cargo_profile_fingerprint).map_err(|reason| {
3774        WrapperError::InvalidSha256 {
3775            name: "final unit cargo_profile_fingerprint",
3776            value: coordinate.cargo_profile_fingerprint.clone(),
3777            reason,
3778        }
3779    })?;
3780    let derived_features = cfg_features(coordinate.cfgs.iter().map(String::as_str));
3781    if derived_features != coordinate.features {
3782        return Err(WrapperError::FinalCoordinateFeatureMismatch);
3783    }
3784    validate_lower_sha256(&coordinate.source_hash).map_err(|reason| {
3785        WrapperError::InvalidSha256 {
3786            name: "final unit source_hash",
3787            value: coordinate.source_hash.clone(),
3788            reason,
3789        }
3790    })?;
3791    validate_lower_sha256(&coordinate.logical_environment_hash).map_err(|reason| {
3792        WrapperError::InvalidSha256 {
3793            name: "final unit logical_environment_hash",
3794            value: coordinate.logical_environment_hash.clone(),
3795            reason,
3796        }
3797    })
3798}
3799
3800struct FinalInvocationCoordinate {
3801    coordinate: FinalUnitCoordinate,
3802    input: NormalizedRustcInvocation,
3803}
3804
3805fn final_unit_coordinate_from_invocation(
3806    rustc_args: &[OsString],
3807) -> Result<Option<FinalInvocationCoordinate>, WrapperError> {
3808    let cargo_manifest_dir = match env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) {
3809        Some(directory) if directory.is_absolute() => directory,
3810        _ => return Ok(None),
3811    };
3812    let source_exclusion = env::var_os(SOURCE_EXCLUSION_DIR_ENV)
3813        .map(PathBuf::from)
3814        .ok_or(WrapperError::MissingEnvironment(SOURCE_EXCLUSION_DIR_ENV))?;
3815    if !source_exclusion.is_absolute() {
3816        return Err(WrapperError::RelativeSourceExclusionDirectory(
3817            source_exclusion,
3818        ));
3819    }
3820    let environment = rustc_visible_environment()?;
3821    let input = match normalize_rustc_invocation_with_package_root(
3822        rustc_args,
3823        &environment,
3824        b"final-coordinate-does-not-use-rustc-identity",
3825        Some(&cargo_manifest_dir),
3826        Some(&source_exclusion),
3827    ) {
3828        Ok(input) => input,
3829        Err(_) => return Ok(None),
3830    };
3831    let cargo_manifest_path = cargo_manifest_dir.join("Cargo.toml");
3832    let Some(cargo_package_name) = nonempty_env("CARGO_PKG_NAME") else {
3833        return Ok(None);
3834    };
3835    let Some(cargo_package_version) = nonempty_env("CARGO_PKG_VERSION") else {
3836        return Ok(None);
3837    };
3838    let cargo_profile_fingerprint = hex_digest(&input.final_match_profile_hash());
3839    let cargo_extra_filename =
3840        input
3841            .cargo_extra_filename()
3842            .map_err(|reason| WrapperError::InvalidCargoExtraFilename {
3843                context: "final rustc invocation",
3844                value: input
3845                    .codegen_options
3846                    .get("extra-filename")
3847                    .cloned()
3848                    .unwrap_or_default(),
3849                reason,
3850            })?;
3851    let logical_environment_hash = hex_digest(&input.logical_environment_hash());
3852    let cfgs = validate_cargo_owned_final_coordinate_cfgs(input.cfgs.clone())?;
3853    let features = cfg_features(cfgs.iter().map(String::as_str));
3854
3855    let coordinate = FinalUnitCoordinate {
3856        cargo_manifest_path,
3857        cargo_package_name,
3858        cargo_package_version,
3859        cargo_profile: nonempty_env("PROFILE"),
3860        cargo_profile_fingerprint,
3861        cargo_primary_package: env::var_os("CARGO_PRIMARY_PACKAGE").is_some(),
3862        cargo_extra_filename,
3863        crate_name: input.crate_name.clone(),
3864        crate_types: input.crate_types.iter().cloned().collect(),
3865        target: input.target.clone(),
3866        features,
3867        source_hash: hex_digest(&input.source_hash),
3868        logical_environment_hash,
3869        cfgs: cfgs.into_iter().collect(),
3870    };
3871    Ok(Some(FinalInvocationCoordinate { coordinate, input }))
3872}
3873
3874fn nonempty_env(name: &str) -> Option<String> {
3875    env::var(name).ok().filter(|value| !value.is_empty())
3876}
3877
3878fn validate_cargo_owned_final_coordinate_cfgs(
3879    cfgs: BTreeSet<String>,
3880) -> Result<BTreeSet<String>, WrapperError> {
3881    if let Some(cfg) = cfgs.iter().find(|cfg| is_final_plan_cfg(cfg)) {
3882        return Err(WrapperError::UnexpectedFinalPlanCfg(cfg.clone()));
3883    }
3884    Ok(cfgs)
3885}
3886
3887fn is_final_plan_cfg(cfg: &str) -> bool {
3888    cfg == "rsjs_final"
3889        || cfg.starts_with("rsjs_final_wrapper_policy")
3890        || cfg.starts_with("rsjs_plan_id")
3891        || cfg.starts_with("rsjs_plan_file_hash")
3892        || cfg.starts_with("rsjs_final_unit_map_hash")
3893}
3894
3895fn cfg_features<'a>(cfgs: impl IntoIterator<Item = &'a str>) -> Vec<String> {
3896    cfgs.into_iter()
3897        .filter_map(|cfg| {
3898            cfg.strip_prefix("feature=\"")
3899                .and_then(|feature| feature.strip_suffix('"'))
3900                .map(str::to_owned)
3901        })
3902        .collect::<BTreeSet<_>>()
3903        .into_iter()
3904        .collect()
3905}
3906
3907fn validate_lower_sha256(value: &str) -> Result<(), String> {
3908    if value.len() != 64 {
3909        return Err(format!(
3910            "expected 64 lowercase hexadecimal characters, got {}",
3911            value.len()
3912        ));
3913    }
3914    if let Some((offset, byte)) = value
3915        .bytes()
3916        .enumerate()
3917        .find(|(_, byte)| !matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
3918    {
3919        return Err(format!(
3920            "invalid byte `{}` at offset {offset}",
3921            char::from(byte)
3922        ));
3923    }
3924    Ok(())
3925}
3926
3927fn validate_tagged_sha256(value: &str) -> Result<(), String> {
3928    let digest = value
3929        .strip_prefix("sha256:")
3930        .ok_or_else(|| "expected `sha256:` prefix".to_string())?;
3931    validate_lower_sha256(digest)
3932}
3933
3934fn validate_cargo_extra_filename(value: &str) -> Result<(), String> {
3935    if value.is_empty() {
3936        return Err("the discriminator is empty".to_string());
3937    }
3938    if value.contains(['/', '\\']) {
3939        return Err("path separators are not allowed".to_string());
3940    }
3941    if let Some((offset, character)) = value
3942        .char_indices()
3943        .find(|(_, character)| character.is_control())
3944    {
3945        return Err(format!(
3946            "control character U+{:04X} at byte offset {offset} is not allowed",
3947            u32::from(character)
3948        ));
3949    }
3950    Ok(())
3951}
3952
3953/// Load only freshly enumerated wrapper outputs from one explicit staging
3954/// directory.
3955///
3956/// This is not target-directory discovery. The orchestrator creates a unique
3957/// directory for one descriptor invocation and supplies that exact path to
3958/// both the wrapper and this loader.
3959pub fn load_descriptor_unit_sidecars(
3960    staging_dir: &Path,
3961) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorSidecarError> {
3962    load_descriptor_unit_sidecars_with_object_validation(
3963        staging_dir,
3964        DescriptorObjectValidation::HashBytes,
3965        false,
3966    )
3967}
3968
3969pub(crate) fn load_descriptor_unit_sidecars_for_recovery(
3970    staging_dir: &Path,
3971) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorSidecarError> {
3972    load_descriptor_unit_sidecars_with_object_validation(
3973        staging_dir,
3974        DescriptorObjectValidation::HashBytes,
3975        true,
3976    )
3977}
3978
3979enum DescriptorObjectValidation {
3980    HashBytes,
3981    TrustAtomicWrapperSidecar,
3982}
3983
3984fn validate_sidecar_out_dir_dependencies(
3985    unit: DescriptorCargoUnitId,
3986    sidecar: &DescriptorUnitSidecar,
3987) -> Result<(), DescriptorSidecarError> {
3988    validate_portable_relative_path(&sidecar.dep_info_path).map_err(|reason| {
3989        DescriptorSidecarError::InvalidObservedInputs {
3990            unit,
3991            reason: format!("invalid target-relative dep-info path: {reason}"),
3992        }
3993    })?;
3994    if !sidecar.dep_info_working_directory.is_absolute() {
3995        return Err(DescriptorSidecarError::InvalidObservedInputs {
3996            unit,
3997            reason: "dep-info working directory is relative".to_string(),
3998        });
3999    }
4000    match &sidecar.out_dir {
4001        Some(path) => validate_portable_relative_path(path).map_err(|reason| {
4002            DescriptorSidecarError::InvalidOutDirPath {
4003                unit,
4004                path: path.clone(),
4005                reason,
4006            }
4007        })?,
4008        None if !sidecar.out_dir_dependencies.is_empty() => {
4009            return Err(DescriptorSidecarError::OutDirDependenciesWithoutOutDir(
4010                unit,
4011            ));
4012        }
4013        None => {}
4014    }
4015    let mut previous = None;
4016    for dependency in &sidecar.out_dir_dependencies {
4017        validate_portable_relative_path(&dependency.relative_path).map_err(|reason| {
4018            DescriptorSidecarError::InvalidOutDirDependencyPath {
4019                unit,
4020                path: dependency.relative_path.clone(),
4021                reason,
4022            }
4023        })?;
4024        validate_lower_sha256(&dependency.content_hash).map_err(|reason| {
4025            DescriptorSidecarError::InvalidOutDirDependencyHash {
4026                unit,
4027                path: dependency.relative_path.clone(),
4028                value: dependency.content_hash.clone(),
4029                reason,
4030            }
4031        })?;
4032        if previous
4033            .as_ref()
4034            .is_some_and(|value: &String| value.as_str() >= dependency.relative_path.as_str())
4035        {
4036            return Err(DescriptorSidecarError::NonCanonicalOutDirDependencies(unit));
4037        }
4038        previous = Some(dependency.relative_path.clone());
4039    }
4040    validate_source_dependency_records(&sidecar.source_dependencies).map_err(|error| {
4041        DescriptorSidecarError::InvalidObservedInputs {
4042            unit,
4043            reason: error.to_string(),
4044        }
4045    })?;
4046    validate_environment_dependency_records(&sidecar.environment_dependencies).map_err(
4047        |error| DescriptorSidecarError::InvalidObservedInputs {
4048            unit,
4049            reason: error.to_string(),
4050        },
4051    )?;
4052    if sidecar.out_dir.is_none()
4053        && sidecar
4054            .environment_dependencies
4055            .iter()
4056            .any(|dependency| dependency.name == "OUT_DIR" && dependency.value_hash.is_some())
4057    {
4058        return Err(DescriptorSidecarError::InvalidObservedInputs {
4059            unit,
4060            reason: "present OUT_DIR environment dependency has no OUT_DIR coordinate".to_string(),
4061        });
4062    }
4063    Ok(())
4064}
4065
4066fn load_descriptor_unit_sidecars_trusting_wrapper_hashes(
4067    staging_dir: &Path,
4068) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorSidecarError> {
4069    load_descriptor_unit_sidecars_with_object_validation(
4070        staging_dir,
4071        DescriptorObjectValidation::TrustAtomicWrapperSidecar,
4072        false,
4073    )
4074}
4075
4076fn load_descriptor_unit_sidecars_with_object_validation(
4077    staging_dir: &Path,
4078    object_validation: DescriptorObjectValidation,
4079    allow_interrupted_temporaries: bool,
4080) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorSidecarError> {
4081    if !staging_dir.is_absolute() {
4082        return Err(DescriptorSidecarError::RelativeStagingDirectory(
4083            staging_dir.to_path_buf(),
4084        ));
4085    }
4086    let units_dir = staging_dir.join("units");
4087    let entries =
4088        fs::read_dir(&units_dir).map_err(|source| DescriptorSidecarError::ReadUnitsDirectory {
4089            path: units_dir.clone(),
4090            source,
4091        })?;
4092    let mut sidecar_paths = Vec::new();
4093    for entry in entries {
4094        let entry = entry.map_err(|source| DescriptorSidecarError::ReadUnitsDirectory {
4095            path: units_dir.clone(),
4096            source,
4097        })?;
4098        let path = entry.path();
4099        if allow_interrupted_temporaries
4100            && interrupted_sidecar_temporary(entry.file_name().as_os_str())
4101        {
4102            let file_type =
4103                entry
4104                    .file_type()
4105                    .map_err(|source| DescriptorSidecarError::ReadUnitsDirectory {
4106                        path: units_dir.clone(),
4107                        source,
4108                    })?;
4109            if !file_type.is_file() {
4110                return Err(DescriptorSidecarError::UnexpectedUnitsEntry(path));
4111            }
4112            continue;
4113        }
4114        sidecar_paths.push(path);
4115    }
4116    sidecar_paths.sort();
4117    if sidecar_paths.is_empty() {
4118        return Err(DescriptorSidecarError::NoUnitSidecars(units_dir));
4119    }
4120
4121    let expected_codegen = DescriptorCodegenSidecar {
4122        codegen_units: 1,
4123        incremental: false,
4124        link_dead_code: true,
4125        lto: "off".to_string(),
4126        strip: "none".to_string(),
4127    };
4128    let mut seen = BTreeSet::new();
4129    let mut units = Vec::with_capacity(sidecar_paths.len());
4130    for sidecar_path in sidecar_paths {
4131        if sidecar_path.extension() != Some(OsStr::new("json")) {
4132            return Err(DescriptorSidecarError::UnexpectedUnitsEntry(sidecar_path));
4133        }
4134        let bytes =
4135            fs::read(&sidecar_path).map_err(|source| DescriptorSidecarError::ReadSidecar {
4136                path: sidecar_path.clone(),
4137                source,
4138            })?;
4139        let sidecar: DescriptorUnitSidecar = serde_json::from_slice(&bytes).map_err(|source| {
4140            DescriptorSidecarError::ParseSidecar {
4141                path: sidecar_path.clone(),
4142                source,
4143            }
4144        })?;
4145        if sidecar.schema_version != DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION {
4146            return Err(DescriptorSidecarError::UnsupportedSchema {
4147                path: sidecar_path,
4148                actual: sidecar.schema_version,
4149                expected: DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION,
4150            });
4151        }
4152        let unit = DescriptorCargoUnitId::from_hex(&sidecar.cargo_unit_id).map_err(|source| {
4153            DescriptorSidecarError::InvalidUnitId {
4154                path: sidecar_path.clone(),
4155                source,
4156            }
4157        })?;
4158        if !seen.insert(unit) {
4159            return Err(DescriptorSidecarError::DuplicateUnit(unit));
4160        }
4161
4162        let expected_filename = format!("{unit}.json");
4163        if sidecar_path.file_name() != Some(OsStr::new(&expected_filename)) {
4164            return Err(DescriptorSidecarError::SidecarFilenameMismatch {
4165                path: sidecar_path,
4166                expected: expected_filename,
4167            });
4168        }
4169        if sidecar.normalized_rustc_inputs_hash != unit.to_string() {
4170            return Err(DescriptorSidecarError::NormalizedHashMismatch {
4171                unit,
4172                actual: sidecar.normalized_rustc_inputs_hash.clone(),
4173            });
4174        }
4175        validate_lower_sha256(&sidecar.logical_environment_hash).map_err(|reason| {
4176            DescriptorSidecarError::InvalidLogicalEnvironmentHash {
4177                unit,
4178                value: sidecar.logical_environment_hash.clone(),
4179                reason,
4180            }
4181        })?;
4182        validate_sidecar_out_dir_dependencies(unit, &sidecar)?;
4183        validate_lower_sha256(&sidecar.realized_environment_hash).map_err(|reason| {
4184            DescriptorSidecarError::InvalidRealizedEnvironmentHash {
4185                unit,
4186                value: sidecar.realized_environment_hash.clone(),
4187                reason,
4188            }
4189        })?;
4190        validate_lower_sha256(&sidecar.package_source_closure_hash).map_err(|reason| {
4191            DescriptorSidecarError::InvalidPackageSourceClosureHash {
4192                unit,
4193                value: sidecar.package_source_closure_hash.clone(),
4194                reason,
4195            }
4196        })?;
4197        for (extern_name, artifact) in &sidecar.dependency_artifacts {
4198            if extern_name.is_empty() {
4199                return Err(DescriptorSidecarError::EmptyDependencyName(unit));
4200            }
4201            if !artifact.path.is_absolute() {
4202                return Err(DescriptorSidecarError::RelativeDependencyArtifact {
4203                    unit,
4204                    extern_name: extern_name.clone(),
4205                    path: artifact.path.clone(),
4206                });
4207            }
4208            validate_lower_sha256(&artifact.content_hash).map_err(|reason| {
4209                DescriptorSidecarError::InvalidDependencyArtifactHash {
4210                    unit,
4211                    extern_name: extern_name.clone(),
4212                    value: artifact.content_hash.clone(),
4213                    reason,
4214                }
4215            })?;
4216        }
4217        if let Some(value) = &sidecar.cargo_extra_filename {
4218            validate_cargo_extra_filename(value).map_err(|reason| {
4219                DescriptorSidecarError::InvalidCargoExtraFilename {
4220                    unit,
4221                    value: value.clone(),
4222                    reason,
4223                }
4224            })?;
4225        }
4226        let expected_object = format!("objects/{unit}.o");
4227        if sidecar.descriptor_object != expected_object {
4228            return Err(DescriptorSidecarError::ObjectPathMismatch {
4229                unit,
4230                actual: sidecar.descriptor_object.clone(),
4231                expected: expected_object,
4232            });
4233        }
4234        if sidecar.descriptor_codegen != expected_codegen {
4235            return Err(DescriptorSidecarError::CodegenPolicyMismatch(unit));
4236        }
4237        validate_lower_sha256(&sidecar.descriptor_object_hash).map_err(|reason| {
4238            DescriptorSidecarError::InvalidDescriptorObjectHash {
4239                unit,
4240                value: sidecar.descriptor_object_hash.clone(),
4241                reason,
4242            }
4243        })?;
4244        let descriptor_object = staging_dir.join(&sidecar.descriptor_object);
4245        match &object_validation {
4246            DescriptorObjectValidation::HashBytes => {
4247                let actual_hash = hash_file(&descriptor_object, DESCRIPTOR_OBJECT_HASH_DOMAIN)
4248                    .map_err(|source| DescriptorSidecarError::ReadObject {
4249                        path: descriptor_object.clone(),
4250                        source,
4251                    })?;
4252                let actual_hash = hex_digest(&actual_hash);
4253                if actual_hash != sidecar.descriptor_object_hash {
4254                    return Err(DescriptorSidecarError::ObjectHashMismatch {
4255                        unit,
4256                        expected: sidecar.descriptor_object_hash.clone(),
4257                        actual: actual_hash,
4258                    });
4259                }
4260            }
4261            DescriptorObjectValidation::TrustAtomicWrapperSidecar => {
4262                require_regular_descriptor_object(&descriptor_object)?;
4263            }
4264        }
4265
4266        units.push(ValidatedDescriptorUnit {
4267            unit,
4268            sidecar,
4269            sidecar_path,
4270            descriptor_object,
4271        });
4272    }
4273    Ok(units)
4274}
4275
4276fn interrupted_sidecar_temporary(name: &OsStr) -> bool {
4277    let Some(name) = name.to_str() else {
4278        return false;
4279    };
4280    let Some(name) = name
4281        .strip_prefix('.')
4282        .and_then(|name| name.strip_suffix(".tmp"))
4283    else {
4284        return false;
4285    };
4286    let Some((name, nonce)) = name.rsplit_once('.') else {
4287        return false;
4288    };
4289    let Some((sidecar, process)) = name.rsplit_once('.') else {
4290        return false;
4291    };
4292    let Some(unit) = sidecar.strip_suffix(".json") else {
4293        return false;
4294    };
4295    !process.is_empty()
4296        && process.bytes().all(|byte| byte.is_ascii_digit())
4297        && !nonce.is_empty()
4298        && nonce.bytes().all(|byte| byte.is_ascii_digit())
4299        && DescriptorCargoUnitId::from_hex(unit).is_ok()
4300}
4301
4302fn require_regular_descriptor_object(path: &Path) -> Result<(), DescriptorSidecarError> {
4303    let metadata = fs::metadata(path).map_err(|source| DescriptorSidecarError::ReadObject {
4304        path: path.to_path_buf(),
4305        source,
4306    })?;
4307    if !metadata.is_file() {
4308        return Err(DescriptorSidecarError::ObjectNotRegularFile(
4309            path.to_path_buf(),
4310        ));
4311    }
4312    Ok(())
4313}
4314
4315/// Validation failure for one explicit descriptor staging directory.
4316#[derive(Debug, Error)]
4317pub enum DescriptorSidecarError {
4318    /// The orchestrator must resolve staging before launching Cargo.
4319    #[error("descriptor staging directory must be absolute: `{0}`")]
4320    RelativeStagingDirectory(PathBuf),
4321    /// Unit enumeration failed.
4322    #[error("failed to enumerate descriptor unit sidecars in `{path}`: {source}")]
4323    ReadUnitsDirectory {
4324        /// Exact units directory.
4325        path: PathBuf,
4326        /// I/O failure.
4327        #[source]
4328        source: io::Error,
4329    },
4330    /// A successful descriptor invocation emitted no units.
4331    #[error("descriptor staging directory `{0}` contains no unit sidecars")]
4332    NoUnitSidecars(PathBuf),
4333    /// Fresh staging may contain only completed JSON sidecars.
4334    #[error("unexpected entry in descriptor units directory: `{0}`")]
4335    UnexpectedUnitsEntry(PathBuf),
4336    /// Sidecar bytes could not be read.
4337    #[error("failed to read descriptor sidecar `{path}`: {source}")]
4338    ReadSidecar {
4339        /// Exact sidecar path.
4340        path: PathBuf,
4341        /// I/O failure.
4342        #[source]
4343        source: io::Error,
4344    },
4345    /// Sidecar JSON could not be decoded.
4346    #[error("failed to parse descriptor sidecar `{path}`: {source}")]
4347    ParseSidecar {
4348        /// Exact sidecar path.
4349        path: PathBuf,
4350        /// JSON failure.
4351        #[source]
4352        source: serde_json::Error,
4353    },
4354    /// Sidecar schema is stale or from a future wrapper.
4355    #[error(
4356        "descriptor sidecar `{path}` uses schema {actual}; this tool requires schema {expected}"
4357    )]
4358    UnsupportedSchema {
4359        /// Exact sidecar path.
4360        path: PathBuf,
4361        /// Actual schema.
4362        actual: u16,
4363        /// Supported schema.
4364        expected: u16,
4365    },
4366    /// Unit ID text is malformed.
4367    #[error("descriptor sidecar `{path}` has an invalid Cargo-unit ID: {source}")]
4368    InvalidUnitId {
4369        /// Exact sidecar path.
4370        path: PathBuf,
4371        /// ID validation failure.
4372        #[source]
4373        source: WrapperError,
4374    },
4375    /// Two sidecars claimed one unit.
4376    #[error("descriptor staging contains duplicate Cargo unit {0}")]
4377    DuplicateUnit(DescriptorCargoUnitId),
4378    /// Filename and payload identity diverged.
4379    #[error("descriptor sidecar `{path}` must be named `{expected}`")]
4380    SidecarFilenameMismatch {
4381        /// Actual path.
4382        path: PathBuf,
4383        /// Required filename.
4384        expected: String,
4385    },
4386    /// The normalized-input checksum must equal the assigned unit ID.
4387    #[error(
4388        "descriptor unit {unit} reports normalized input hash `{actual}` instead of its unit ID"
4389    )]
4390    NormalizedHashMismatch {
4391        /// Assigned unit.
4392        unit: DescriptorCargoUnitId,
4393        /// Sidecar hash.
4394        actual: String,
4395    },
4396    /// Realized generation identity must use canonical lowercase SHA-256.
4397    #[error("descriptor unit {unit} has invalid realized environment hash `{value}`: {reason}")]
4398    InvalidRealizedEnvironmentHash {
4399        /// Assigned unit.
4400        unit: DescriptorCargoUnitId,
4401        /// Rejected hash.
4402        value: String,
4403        /// Validation detail.
4404        reason: String,
4405    },
4406    /// Cross-phase logical environment identity must be canonical SHA-256.
4407    #[error("descriptor unit {unit} has invalid logical environment hash `{value}`: {reason}")]
4408    InvalidLogicalEnvironmentHash {
4409        /// Assigned unit.
4410        unit: DescriptorCargoUnitId,
4411        /// Rejected hash.
4412        value: String,
4413        /// Validation detail.
4414        reason: String,
4415    },
4416    /// OUT_DIR is stored relative to the orchestrator-owned target.
4417    #[error("descriptor unit {unit} has invalid target-relative OUT_DIR `{path}`: {reason}")]
4418    InvalidOutDirPath {
4419        /// Assigned unit.
4420        unit: DescriptorCargoUnitId,
4421        /// Rejected path.
4422        path: String,
4423        /// Validation detail.
4424        reason: String,
4425    },
4426    /// Generated dependencies require one matching OUT_DIR coordinate.
4427    #[error("descriptor unit {0} has OUT_DIR dependencies but no OUT_DIR coordinate")]
4428    OutDirDependenciesWithoutOutDir(DescriptorCargoUnitId),
4429    /// Generated-source paths are strict portable relative paths.
4430    #[error("descriptor unit {unit} has invalid OUT_DIR dependency path `{path}`: {reason}")]
4431    InvalidOutDirDependencyPath {
4432        /// Assigned unit.
4433        unit: DescriptorCargoUnitId,
4434        /// Rejected path.
4435        path: String,
4436        /// Validation detail.
4437        reason: String,
4438    },
4439    /// Generated-source hashes use canonical lowercase SHA-256.
4440    #[error(
4441        "descriptor unit {unit} OUT_DIR dependency `{path}` has invalid hash `{value}`: {reason}"
4442    )]
4443    InvalidOutDirDependencyHash {
4444        /// Assigned unit.
4445        unit: DescriptorCargoUnitId,
4446        /// Generated-source path.
4447        path: String,
4448        /// Rejected hash.
4449        value: String,
4450        /// Validation detail.
4451        reason: String,
4452    },
4453    /// Generated-source records are strictly sorted and unique.
4454    #[error("descriptor unit {0} has non-canonical OUT_DIR dependencies")]
4455    NonCanonicalOutDirDependencies(DescriptorCargoUnitId),
4456    /// Exact dep-info/source/environment records failed closed validation.
4457    #[error("descriptor unit {unit} has invalid observed inputs: {reason}")]
4458    InvalidObservedInputs {
4459        /// Assigned unit.
4460        unit: DescriptorCargoUnitId,
4461        /// Value-redacted validation detail.
4462        reason: String,
4463    },
4464    /// Package closure identity must use the exact lowercase representation.
4465    #[error("descriptor unit {unit} has invalid package source-closure hash `{value}`: {reason}")]
4466    InvalidPackageSourceClosureHash {
4467        /// Assigned unit.
4468        unit: DescriptorCargoUnitId,
4469        /// Rejected hash.
4470        value: String,
4471        /// Validation detail.
4472        reason: String,
4473    },
4474    /// Rust extern names are required map keys.
4475    #[error("descriptor unit {0} contains an empty dependency name")]
4476    EmptyDependencyName(DescriptorCargoUnitId),
4477    /// Cargo passes absolute artifact paths to rustc; relative coordinates
4478    /// cannot be joined safely to its JSON enumeration.
4479    #[error("descriptor unit {unit} extern `{extern_name}` has relative artifact path `{path}`")]
4480    RelativeDependencyArtifact {
4481        /// Descriptor unit.
4482        unit: DescriptorCargoUnitId,
4483        /// Rust extern name.
4484        extern_name: String,
4485        /// Invalid path.
4486        path: PathBuf,
4487    },
4488    /// Wrapper-time dependency hashes must be canonical lowercase SHA-256.
4489    #[error(
4490        "descriptor unit {unit} extern `{extern_name}` has invalid artifact hash `{value}`: {reason}"
4491    )]
4492    InvalidDependencyArtifactHash {
4493        /// Descriptor unit.
4494        unit: DescriptorCargoUnitId,
4495        /// Rust extern name.
4496        extern_name: String,
4497        /// Invalid hash.
4498        value: String,
4499        /// Validation detail.
4500        reason: String,
4501    },
4502    /// Cargo output discriminators must remain a single safe filename fragment.
4503    #[error("descriptor unit {unit} has invalid Cargo extra-filename `{value}`: {reason}")]
4504    InvalidCargoExtraFilename {
4505        /// Assigned unit.
4506        unit: DescriptorCargoUnitId,
4507        /// Rejected discriminator.
4508        value: String,
4509        /// Validation detail.
4510        reason: String,
4511    },
4512    /// Descriptor object path is not the content-addressed wrapper path.
4513    #[error("descriptor unit {unit} reports object `{actual}`; expected exact path `{expected}`")]
4514    ObjectPathMismatch {
4515        /// Assigned unit.
4516        unit: DescriptorCargoUnitId,
4517        /// Reported relative path.
4518        actual: String,
4519        /// Required relative path.
4520        expected: String,
4521    },
4522    /// Retention policy differs from the wrapper protocol.
4523    #[error("descriptor unit {0} has an incompatible retention/codegen policy")]
4524    CodegenPolicyMismatch(DescriptorCargoUnitId),
4525    /// Wrapper/cache object hashes must use canonical lowercase SHA-256.
4526    #[error("descriptor unit {unit} has invalid descriptor object hash `{value}`: {reason}")]
4527    InvalidDescriptorObjectHash {
4528        /// Assigned unit.
4529        unit: DescriptorCargoUnitId,
4530        /// Rejected hash.
4531        value: String,
4532        /// Validation detail.
4533        reason: String,
4534    },
4535    /// Exact object could not be read.
4536    #[error("failed to read descriptor object `{path}`: {source}")]
4537    ReadObject {
4538        /// Exact object path.
4539        path: PathBuf,
4540        /// I/O failure.
4541        #[source]
4542        source: io::Error,
4543    },
4544    /// Object content differs from the atomic sidecar.
4545    #[error(
4546        "descriptor object for unit {unit} has hash `{actual}`; sidecar requires `{expected}`"
4547    )]
4548    ObjectHashMismatch {
4549        /// Assigned unit.
4550        unit: DescriptorCargoUnitId,
4551        /// Sidecar hash.
4552        expected: String,
4553        /// Recomputed hash.
4554        actual: String,
4555    },
4556    /// Skipping a byte rehash still requires a regular object file.
4557    #[error("descriptor object is not a regular file: `{0}`")]
4558    ObjectNotRegularFile(PathBuf),
4559}
4560
4561/// Failure to build a phase-invariant final unit map.
4562#[derive(Debug, Error)]
4563pub enum FinalUnitMapError {
4564    /// Output location must not depend on the process cwd.
4565    #[error("final unit-map directory must be absolute: `{0}`")]
4566    RelativeDirectory(PathBuf),
4567    /// The exact tagged linked-plan hash was malformed.
4568    #[error("invalid linked-plan SHA-256 `{value}`: {reason}")]
4569    InvalidPlanFileHash {
4570        /// Rejected hash.
4571        value: String,
4572        /// Validation detail.
4573        reason: String,
4574    },
4575    /// A validated wrapper identity and its sidecar diverged.
4576    #[error("validated descriptor unit `{validated}` has sidecar Cargo-unit ID `{sidecar}`")]
4577    UnitIdMismatch {
4578        /// Validated ID.
4579        validated: String,
4580        /// Sidecar ID.
4581        sidecar: String,
4582    },
4583    /// A required Cargo coordinate was not recorded.
4584    #[error("descriptor unit {unit} has no nonempty `{field}` coordinate")]
4585    MissingCoordinateField {
4586        /// Descriptor unit.
4587        unit: String,
4588        /// Missing field.
4589        field: &'static str,
4590    },
4591    /// Profile matching requires one exact phase-invariant fingerprint.
4592    #[error("descriptor unit {unit} has invalid profile fingerprint `{value}`: {reason}")]
4593    InvalidProfileFingerprint {
4594        /// Descriptor unit.
4595        unit: String,
4596        /// Rejected fingerprint.
4597        value: String,
4598        /// Validation detail.
4599        reason: String,
4600    },
4601    /// The Cargo rustc output discriminator was malformed.
4602    #[error("descriptor unit {unit} has invalid Cargo extra-filename `{value}`: {reason}")]
4603    InvalidCargoExtraFilename {
4604        /// Descriptor unit.
4605        unit: String,
4606        /// Rejected discriminator.
4607        value: String,
4608        /// Validation detail.
4609        reason: String,
4610    },
4611    /// Manifest paths are exact host-local join coordinates.
4612    #[error("descriptor unit {unit} has relative manifest path `{path}`")]
4613    RelativeManifestPath {
4614        /// Descriptor unit.
4615        unit: String,
4616        /// Rejected path.
4617        path: PathBuf,
4618    },
4619    /// Set-valued sidecar coordinates must already be canonical.
4620    #[error("descriptor unit {unit} has non-canonical `{field}` values")]
4621    NonCanonicalCoordinateValues {
4622        /// Descriptor unit.
4623        unit: String,
4624        /// Field name.
4625        field: &'static str,
4626    },
4627    /// Descriptor inputs may not claim final-only cfgs.
4628    #[error("descriptor unit {unit} contains a reserved final-plan cfg")]
4629    ReservedDescriptorCfg {
4630        /// Descriptor unit.
4631        unit: String,
4632    },
4633    /// Feature and cfg views must describe the same Cargo unit.
4634    #[error("descriptor unit {unit} has features {features:?}, but its cfgs derive {derived:?}")]
4635    FeatureCfgMismatch {
4636        /// Descriptor unit.
4637        unit: String,
4638        /// Recorded features.
4639        features: Vec<String>,
4640        /// Features derived from cfgs.
4641        derived: Vec<String>,
4642    },
4643    /// Source content identity must use the exact lowercase representation.
4644    #[error("descriptor unit {unit} has invalid source hash `{value}`: {reason}")]
4645    InvalidSourceHash {
4646        /// Descriptor unit.
4647        unit: String,
4648        /// Rejected hash.
4649        value: String,
4650        /// Validation detail.
4651        reason: String,
4652    },
4653    /// Package closure identity must use the exact lowercase representation.
4654    #[error("descriptor unit {unit} has invalid package source-closure hash `{value}`: {reason}")]
4655    InvalidPackageSourceClosureHash {
4656        /// Descriptor unit.
4657        unit: String,
4658        /// Rejected hash.
4659        value: String,
4660        /// Validation detail.
4661        reason: String,
4662    },
4663    /// Cross-phase logical environment identity must be lowercase SHA-256.
4664    #[error("descriptor unit {unit} has invalid logical environment hash `{value}`: {reason}")]
4665    InvalidLogicalEnvironmentHash {
4666        /// Descriptor unit.
4667        unit: String,
4668        /// Rejected hash.
4669        value: String,
4670        /// Validation detail.
4671        reason: String,
4672    },
4673    /// Two descriptor units cannot be selected by one final coordinate.
4674    #[error(
4675        "final unit coordinate {coordinate:?} ambiguously identifies descriptor units {first} and {second}"
4676    )]
4677    AmbiguousCoordinate {
4678        /// Ambiguous semantic coordinate.
4679        coordinate: FinalUnitCoordinate,
4680        /// First unit.
4681        first: String,
4682        /// Second unit.
4683        second: String,
4684    },
4685    /// JSON serialization failed.
4686    #[error("failed to serialize final unit map: {0}")]
4687    Serialize(serde_json::Error),
4688    /// A content-addressed path must have a parent.
4689    #[error("final unit-map path has no parent: `{0}`")]
4690    PathWithoutParent(PathBuf),
4691    /// Content-addressed directory creation failed.
4692    #[error("failed to create final unit-map directory `{path}`: {source}")]
4693    CreateDirectory {
4694        /// Directory.
4695        path: PathBuf,
4696        /// I/O failure.
4697        #[source]
4698        source: io::Error,
4699    },
4700    /// Content-addressed file name must be valid UTF-8.
4701    #[error("invalid final unit-map filename: `{0}`")]
4702    InvalidFilename(PathBuf),
4703    /// Atomic write failed.
4704    #[error("failed to write final unit map `{path}`: {source}")]
4705    Write {
4706        /// Exact path.
4707        path: PathBuf,
4708        /// I/O failure.
4709        #[source]
4710        source: io::Error,
4711    },
4712    /// A same-hash path contained other bytes.
4713    #[error("content-addressed final unit map conflicts with `{0}`")]
4714    ConflictingContent(PathBuf),
4715}
4716
4717/// One strictly parsed Cargo `compiler-artifact` message.
4718#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
4719pub struct CargoCompilerArtifact {
4720    /// Cargo package ID, exactly as Cargo emitted it.
4721    pub package_id: String,
4722    /// Manifest path reported by Cargo.
4723    pub manifest_path: PathBuf,
4724    /// Target identity reported by Cargo.
4725    pub target: CargoArtifactTarget,
4726    /// Profile object reported by Cargo.
4727    pub profile: Value,
4728    /// Enabled features, normalized for exact matching.
4729    pub features: BTreeSet<String>,
4730    /// Exact artifact paths reported by Cargo.
4731    pub filenames: BTreeSet<PathBuf>,
4732    /// Executable path, when this target has one.
4733    pub executable: Option<PathBuf>,
4734    /// Whether Cargo reused the artifact.
4735    pub fresh: bool,
4736}
4737
4738/// Target portion of a Cargo `compiler-artifact` message.
4739#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
4740pub struct CargoArtifactTarget {
4741    /// Rust target name.
4742    pub name: String,
4743    /// Cargo target kinds.
4744    pub kind: BTreeSet<String>,
4745    /// Rust crate types.
4746    pub crate_types: BTreeSet<String>,
4747    /// Target source path.
4748    pub src_path: PathBuf,
4749    /// Rust edition.
4750    pub edition: String,
4751}
4752
4753#[derive(Debug, Deserialize)]
4754struct RawCargoArtifact {
4755    package_id: String,
4756    manifest_path: PathBuf,
4757    target: RawCargoTarget,
4758    profile: Value,
4759    features: Vec<String>,
4760    filenames: Vec<PathBuf>,
4761    executable: Option<PathBuf>,
4762    fresh: bool,
4763}
4764
4765#[derive(Debug, Deserialize)]
4766struct RawCargoTarget {
4767    name: String,
4768    kind: Vec<String>,
4769    crate_types: Vec<String>,
4770    src_path: PathBuf,
4771    edition: String,
4772}
4773
4774/// Strict Cargo JSON collector. It never searches a target directory.
4775#[derive(Debug, Default)]
4776pub struct CargoArtifactCollector {
4777    artifacts: Vec<CargoCompilerArtifact>,
4778    seen_artifacts: BTreeSet<Vec<u8>>,
4779    build_finished: Option<bool>,
4780    line: usize,
4781}
4782
4783impl CargoArtifactCollector {
4784    /// Consume one complete line from `cargo --message-format=json...`.
4785    pub fn ingest_line(&mut self, line: &str) -> Result<(), CargoMessageError> {
4786        self.line += 1;
4787        if line.trim().is_empty() {
4788            return Err(CargoMessageError::EmptyLine { line: self.line });
4789        }
4790        if self.build_finished.is_some() {
4791            return Err(CargoMessageError::MessageAfterBuildFinished { line: self.line });
4792        }
4793
4794        let value: Value =
4795            serde_json::from_str(line).map_err(|source| CargoMessageError::MalformedJson {
4796                line: self.line,
4797                source,
4798            })?;
4799        let reason = value
4800            .get("reason")
4801            .and_then(Value::as_str)
4802            .ok_or(CargoMessageError::MissingReason { line: self.line })?;
4803
4804        match reason {
4805            "compiler-artifact" => {
4806                let raw: RawCargoArtifact = serde_json::from_value(value).map_err(|source| {
4807                    CargoMessageError::MalformedCompilerArtifact {
4808                        line: self.line,
4809                        source,
4810                    }
4811                })?;
4812                let unique_kinds = raw.target.kind.iter().collect::<BTreeSet<_>>();
4813                let unique_crate_types = raw.target.crate_types.iter().collect::<BTreeSet<_>>();
4814                let unique_features = raw.features.iter().collect::<BTreeSet<_>>();
4815                let unique_filenames = raw.filenames.iter().collect::<BTreeSet<_>>();
4816                if raw.package_id.is_empty()
4817                    || !raw.manifest_path.is_absolute()
4818                    || raw.target.name.is_empty()
4819                    || raw.target.kind.is_empty()
4820                    || raw.target.crate_types.is_empty()
4821                    || !raw.target.src_path.is_absolute()
4822                    || raw.target.edition.is_empty()
4823                    || !raw.profile.is_object()
4824                    || raw.filenames.is_empty()
4825                    || raw.filenames.iter().any(|path| !path.is_absolute())
4826                    || unique_kinds.len() != raw.target.kind.len()
4827                    || unique_crate_types.len() != raw.target.crate_types.len()
4828                    || unique_features.len() != raw.features.len()
4829                    || unique_filenames.len() != raw.filenames.len()
4830                {
4831                    return Err(CargoMessageError::IncompleteCompilerArtifact { line: self.line });
4832                }
4833                let artifact = CargoCompilerArtifact {
4834                    package_id: raw.package_id,
4835                    manifest_path: raw.manifest_path,
4836                    target: CargoArtifactTarget {
4837                        name: raw.target.name,
4838                        kind: raw.target.kind.into_iter().collect(),
4839                        crate_types: raw.target.crate_types.into_iter().collect(),
4840                        src_path: raw.target.src_path,
4841                        edition: raw.target.edition,
4842                    },
4843                    profile: raw.profile,
4844                    features: raw.features.into_iter().collect(),
4845                    filenames: raw.filenames.into_iter().collect(),
4846                    executable: raw.executable,
4847                    fresh: raw.fresh,
4848                };
4849                let identity = serde_json::to_vec(&artifact)
4850                    .expect("serializing an in-memory Cargo artifact cannot fail");
4851                if !self.seen_artifacts.insert(identity) {
4852                    return Err(CargoMessageError::DuplicateCompilerArtifact {
4853                        line: self.line,
4854                        package_id: artifact.package_id,
4855                        target: artifact.target.name,
4856                    });
4857                }
4858                self.artifacts.push(artifact);
4859            }
4860            "build-finished" => {
4861                let success = value
4862                    .get("success")
4863                    .and_then(Value::as_bool)
4864                    .ok_or(CargoMessageError::MalformedBuildFinished { line: self.line })?;
4865                self.build_finished = Some(success);
4866            }
4867            "compiler-message" => {
4868                validate_auxiliary_message(
4869                    &value,
4870                    self.line,
4871                    reason,
4872                    &[
4873                        ("package_id", JsonFieldKind::NonemptyString),
4874                        ("target", JsonFieldKind::Object),
4875                        ("message", JsonFieldKind::Object),
4876                    ],
4877                )?;
4878            }
4879            "build-script-executed" => {
4880                validate_auxiliary_message(
4881                    &value,
4882                    self.line,
4883                    reason,
4884                    &[
4885                        ("package_id", JsonFieldKind::NonemptyString),
4886                        ("linked_libs", JsonFieldKind::Array),
4887                        ("linked_paths", JsonFieldKind::Array),
4888                        ("cfgs", JsonFieldKind::Array),
4889                        ("env", JsonFieldKind::Array),
4890                        ("out_dir", JsonFieldKind::NonemptyString),
4891                    ],
4892                )?;
4893            }
4894            "future-incompat-report" => {
4895                validate_auxiliary_message(
4896                    &value,
4897                    self.line,
4898                    reason,
4899                    &[("future_incompat_report", JsonFieldKind::Object)],
4900                )?;
4901            }
4902            other => {
4903                return Err(CargoMessageError::UnknownReason {
4904                    line: self.line,
4905                    reason: other.to_string(),
4906                });
4907            }
4908        }
4909        Ok(())
4910    }
4911
4912    /// Consume a complete Cargo JSON stream.
4913    pub fn ingest_reader(&mut self, reader: impl BufRead) -> Result<(), CargoMessageError> {
4914        for line in reader.lines() {
4915            let line = line.map_err(|source| CargoMessageError::Read {
4916                line: self.line + 1,
4917                source,
4918            })?;
4919            self.ingest_line(&line)?;
4920        }
4921        Ok(())
4922    }
4923
4924    /// Require a successful terminal message and return collected artifacts.
4925    pub fn finish(self) -> Result<Vec<CargoCompilerArtifact>, CargoMessageError> {
4926        match self.build_finished {
4927            Some(true) => Ok(self.artifacts),
4928            Some(false) => Err(CargoMessageError::CargoBuildFailed),
4929            None => Err(CargoMessageError::MissingBuildFinished),
4930        }
4931    }
4932}
4933
4934/// One exact descriptor-phase Cargo invocation.
4935#[derive(Clone, Debug)]
4936pub struct DescriptorCargoRequest {
4937    /// Cargo executable.
4938    pub cargo: OsString,
4939    /// Absolute `cargo-proa`/`proa` executable used as `RUSTC_WRAPPER`.
4940    pub wrapper: PathBuf,
4941    /// Absolute Cargo working directory.
4942    pub working_directory: PathBuf,
4943    /// Fresh absolute staging directory reserved for this invocation. A
4944    /// cached recovery may substitute the exact marker-owned root named by an
4945    /// interrupted target journal and write through a fresh child attempt. It
4946    /// must be a strict descendant of `source_exclusion_directory` so wrapper
4947    /// outputs cannot enter package source identity.
4948    pub staging_directory: PathBuf,
4949    /// Exact absolute Cargo target directory reserved for descriptor builds.
4950    ///
4951    /// The runner owns `--target-dir`; callers must not repeat it in
4952    /// `cargo_args`. Recovery may remove this directory only after validating
4953    /// the runner-owned marker written here.
4954    pub target_directory: PathBuf,
4955    /// Exact generated subtree excluded from package source closure hashing.
4956    /// The descriptor target must be contained by this path. Linked final
4957    /// compilation receives the same boundary so the coordinate is phase
4958    /// invariant even for custom in-tree Cargo target directories.
4959    pub source_exclusion_directory: PathBuf,
4960    /// Cargo arguments, including the subcommand and exact target selection.
4961    ///
4962    /// The runner owns `--message-format` and rejects an author-supplied one.
4963    pub cargo_args: Vec<OsString>,
4964    /// Additional exact environment for both Cargo and build scripts.
4965    pub environment: BTreeMap<OsString, OsString>,
4966}
4967
4968/// Successful descriptor Cargo output, before root-specific manifest linking.
4969///
4970/// This remains crate-private because its Cargo artifact paths point into a
4971/// mutable shared target. Public callers receive an opaque lease and must
4972/// consume it through the safe linking/reporting boundary below.
4973#[derive(Debug)]
4974pub(crate) struct DescriptorCargoOutput {
4975    /// Strictly parsed artifacts from Cargo's JSON protocol.
4976    pub(crate) cargo_artifacts: Vec<CargoCompilerArtifact>,
4977    /// Validated wrapper units and exact descriptor objects.
4978    pub(crate) units: Vec<ValidatedDescriptorUnit>,
4979}
4980
4981/// Path-free summary of one descriptor Cargo artifact.
4982#[derive(Clone, Debug, PartialEq, Eq)]
4983pub struct DescriptorCargoArtifactReport {
4984    /// Cargo package ID, exactly as Cargo emitted it.
4985    pub package_id: String,
4986    /// Cargo target name.
4987    pub target_name: String,
4988    /// Cargo target-kind set.
4989    pub target_kinds: BTreeSet<String>,
4990    /// Whether Cargo reused this artifact.
4991    pub fresh: bool,
4992}
4993
4994/// Path-free summary of one validated descriptor unit.
4995#[derive(Clone, Debug, PartialEq, Eq)]
4996pub struct DescriptorCargoUnitReport {
4997    /// Strong descriptor Cargo-unit identity.
4998    pub unit: DescriptorCargoUnitId,
4999    /// Cargo package name recorded by the wrapper, when available.
5000    pub cargo_package_name: Option<String>,
5001    /// Rust crate name of the compiled unit. Distinguishes a package's lib
5002    /// unit from its `build_script_build` unit, which share one package name.
5003    pub crate_name: String,
5004    /// Exact descriptor object content hash.
5005    pub descriptor_object_hash: String,
5006}
5007
5008/// Safe descriptor-run diagnostics that remain valid after its leases drop.
5009#[derive(Clone, Debug, PartialEq, Eq)]
5010pub struct DescriptorCargoReport {
5011    /// Path-free Cargo artifact summaries.
5012    pub cargo_artifacts: Vec<DescriptorCargoArtifactReport>,
5013    /// Path-free descriptor-unit summaries.
5014    pub units: Vec<DescriptorCargoUnitReport>,
5015}
5016
5017impl DescriptorCargoReport {
5018    pub(crate) fn from_output(output: &DescriptorCargoOutput) -> Self {
5019        Self {
5020            cargo_artifacts: output
5021                .cargo_artifacts
5022                .iter()
5023                .map(|artifact| DescriptorCargoArtifactReport {
5024                    package_id: artifact.package_id.clone(),
5025                    target_name: artifact.target.name.clone(),
5026                    target_kinds: artifact.target.kind.clone(),
5027                    fresh: artifact.fresh,
5028                })
5029                .collect(),
5030            units: output
5031                .units
5032                .iter()
5033                .map(|unit| DescriptorCargoUnitReport {
5034                    unit: unit.unit,
5035                    cargo_package_name: unit.sidecar.cargo_package_name.clone(),
5036                    crate_name: unit.sidecar.crate_name.clone(),
5037                    descriptor_object_hash: unit.sidecar.descriptor_object_hash.clone(),
5038                })
5039                .collect(),
5040        }
5041    }
5042}
5043
5044/// Exclusive lease for one canonical descriptor target, independent of which
5045/// cache directory or orchestration mode is using it.
5046pub(crate) struct DescriptorTargetLease {
5047    _file: File,
5048}
5049
5050/// Opaque lease retaining exclusive authority over one descriptor target.
5051///
5052/// Consume it with `crate::rsjs::pipeline::link_descriptor_transport` or
5053/// [`finish_descriptor_run`].
5054#[must_use = "descriptor Cargo leases retain filesystem locks until consumed or dropped"]
5055pub struct DescriptorCargoLease {
5056    output: DescriptorCargoOutput,
5057    _target_lease: DescriptorTargetLease,
5058}
5059
5060impl fmt::Debug for DescriptorCargoLease {
5061    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
5062        formatter
5063            .debug_struct("DescriptorCargoLease")
5064            .field("artifacts", &self.output.cargo_artifacts.len())
5065            .field("units", &self.output.units.len())
5066            .finish_non_exhaustive()
5067    }
5068}
5069
5070/// Private half of the sealed public descriptor-run capability.
5071pub(crate) mod descriptor_run_sealed {
5072    use super::DescriptorCargoOutput;
5073
5074    pub(crate) trait Sealed {
5075        fn output(&self) -> &DescriptorCargoOutput;
5076
5077        fn into_output(self) -> DescriptorCargoOutput
5078        where
5079            Self: Sized;
5080    }
5081}
5082
5083/// A descriptor Cargo run whose mutable target remains exclusively leased.
5084///
5085/// This trait is sealed. It exists so the safe consuming linker can accept
5086/// cached and uncached runs without exposing their raw path-bearing output.
5087#[allow(private_bounds)]
5088pub trait DescriptorCargoRun: descriptor_run_sealed::Sealed {}
5089
5090impl descriptor_run_sealed::Sealed for DescriptorCargoLease {
5091    fn output(&self) -> &DescriptorCargoOutput {
5092        &self.output
5093    }
5094
5095    fn into_output(self) -> DescriptorCargoOutput {
5096        self.output
5097    }
5098}
5099
5100impl DescriptorCargoRun for DescriptorCargoLease {}
5101
5102/// Borrow a path-free diagnostic report while retaining the run lease.
5103pub fn descriptor_run_report(run: &impl DescriptorCargoRun) -> DescriptorCargoReport {
5104    DescriptorCargoReport::from_output(descriptor_run_sealed::Sealed::output(run))
5105}
5106
5107/// Consume a descriptor run without linking and return only path-free data.
5108pub fn finish_descriptor_run(run: impl DescriptorCargoRun) -> DescriptorCargoReport {
5109    let report = descriptor_run_report(&run);
5110    drop(descriptor_run_sealed::Sealed::into_output(run));
5111    report
5112}
5113
5114/// Run descriptor compilation with the hidden wrapper and collect only
5115/// invocation-authoritative outputs.
5116pub fn run_descriptor_cargo(
5117    request: &DescriptorCargoRequest,
5118) -> Result<DescriptorCargoLease, DescriptorCargoRunError> {
5119    validate_descriptor_managed_paths(request)?;
5120    let target_lease = acquire_descriptor_target_lease(&request.target_directory)?;
5121    reject_cached_crash_journal(&request.target_directory)?;
5122    let output = run_descriptor_cargo_with_empty_policy(
5123        request,
5124        false,
5125        false,
5126        DescriptorStagingPreparation::Fresh,
5127    )?;
5128    Ok(DescriptorCargoLease {
5129        output,
5130        _target_lease: target_lease,
5131    })
5132}
5133
5134/// Remove one successfully consumed invocation-local descriptor staging tree.
5135///
5136/// This is deliberately not part of `DescriptorCargoLease`'s drop path: failed
5137/// linking/finalization keeps its exact staging evidence. Callers may invoke
5138/// this only after all staging-backed descriptor units have been consumed.
5139/// The exact request path is revalidated and must still carry the marker that
5140/// the descriptor runner wrote before only that staging directory is removed.
5141pub(crate) fn remove_successful_descriptor_staging(
5142    request: &DescriptorCargoRequest,
5143) -> Result<(), DescriptorCargoRunError> {
5144    let managed = validate_descriptor_managed_paths(request)?;
5145    let staging = managed.staging;
5146    let owned = descriptor_staging_marker_is_valid(&staging).map_err(|source| {
5147        DescriptorCargoRunError::ReadCompletedStagingMarker {
5148            path: staging.clone(),
5149            source,
5150        }
5151    })?;
5152    if !owned {
5153        return Err(DescriptorCargoRunError::UnownedCompletedStaging(staging));
5154    }
5155    let metadata = fs::symlink_metadata(&staging).map_err(|source| {
5156        DescriptorCargoRunError::InspectCompletedStaging {
5157            path: staging.clone(),
5158            source,
5159        }
5160    })?;
5161    if !metadata.file_type().is_dir() {
5162        return Err(DescriptorCargoRunError::UnsafeCompletedStaging(staging));
5163    }
5164    fs::remove_dir_all(&staging).map_err(|source| DescriptorCargoRunError::RemoveCompletedStaging {
5165        path: staging,
5166        source,
5167    })
5168}
5169
5170fn reject_cached_crash_journal(target_directory: &Path) -> Result<(), DescriptorCargoRunError> {
5171    let journal = descriptor_target_dirty_journal_path(target_directory)?;
5172    match fs::symlink_metadata(&journal) {
5173        Ok(metadata) if metadata.file_type().is_file() => Err(
5174            DescriptorCargoRunError::CachedCrashJournalRequiresRecovery(journal),
5175        ),
5176        Ok(_) => Err(DescriptorCargoRunError::UnsafeTargetJournal(journal)),
5177        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(()),
5178        Err(source) => Err(DescriptorCargoRunError::ReadTargetJournal {
5179            path: journal,
5180            source,
5181        }),
5182    }
5183}
5184
5185pub(crate) fn run_descriptor_cargo_allow_empty(
5186    request: &DescriptorCargoRequest,
5187) -> Result<DescriptorCargoOutput, DescriptorCargoRunError> {
5188    // This cache-only path consumes a unique staging directory written by the
5189    // wrapper child that just exited. The wrapper hashes each object before it
5190    // atomically publishes the sidecar; the cache then verifies the same hash
5191    // while materializing the object before exposing the merged output.
5192    run_descriptor_cargo_with_empty_policy(request, true, true, DescriptorStagingPreparation::Fresh)
5193}
5194
5195/// Resume the exact marker-owned staging root recorded by an interrupted
5196/// cached descriptor transaction.
5197///
5198/// Cargo still runs against the persistent target and emits a new complete
5199/// artifact enumeration. The wrapper writes through a fresh child attempt so
5200/// recompiling the same unit cannot overwrite earlier provisional evidence.
5201/// Sidecars from every completed attempt remain candidates until the cache
5202/// revalidates them against that enumeration and the current inputs.
5203pub(crate) fn run_descriptor_cargo_allow_empty_resuming(
5204    request: &DescriptorCargoRequest,
5205) -> Result<DescriptorCargoOutput, DescriptorCargoRunError> {
5206    run_descriptor_cargo_with_empty_policy(
5207        request,
5208        true,
5209        false,
5210        DescriptorStagingPreparation::ResumeOwned,
5211    )
5212}
5213
5214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5215enum DescriptorStagingPreparation {
5216    Fresh,
5217    ResumeOwned,
5218}
5219
5220fn run_descriptor_cargo_with_empty_policy(
5221    request: &DescriptorCargoRequest,
5222    allow_empty_units: bool,
5223    trust_atomic_wrapper_hashes: bool,
5224    staging_preparation: DescriptorStagingPreparation,
5225) -> Result<DescriptorCargoOutput, DescriptorCargoRunError> {
5226    if !request.wrapper.is_absolute() {
5227        return Err(DescriptorCargoRunError::RelativeWrapper(
5228            request.wrapper.clone(),
5229        ));
5230    }
5231    if !request.working_directory.is_absolute() {
5232        return Err(DescriptorCargoRunError::RelativeWorkingDirectory(
5233            request.working_directory.clone(),
5234        ));
5235    }
5236    if !request.staging_directory.is_absolute() {
5237        return Err(DescriptorCargoRunError::RelativeStagingDirectory(
5238            request.staging_directory.clone(),
5239        ));
5240    }
5241    validate_descriptor_managed_paths(request)?;
5242    if request.cargo_args.is_empty() {
5243        return Err(DescriptorCargoRunError::MissingCargoArguments);
5244    }
5245    if env::var_os(COMPONENT_DESCRIPTOR_DIRS_ENV).is_some()
5246        || request
5247            .environment
5248            .contains_key(OsStr::new(COMPONENT_DESCRIPTOR_DIRS_ENV))
5249    {
5250        return Err(DescriptorCargoRunError::UnsupportedEnvironment(
5251            COMPONENT_DESCRIPTOR_DIRS_ENV,
5252        ));
5253    }
5254    if let Some(argument) = request.cargo_args.iter().find(|argument| {
5255        let argument = argument.to_string_lossy();
5256        argument.starts_with("--message-format")
5257            || argument == "--target-dir"
5258            || argument.starts_with("--target-dir=")
5259    }) {
5260        return Err(DescriptorCargoRunError::ReservedCargoArgument(
5261            argument.clone(),
5262        ));
5263    }
5264    if let Some(name) = request
5265        .environment
5266        .keys()
5267        .find(|name| name.to_str().is_some_and(wrapper_control_environment))
5268    {
5269        return Err(DescriptorCargoRunError::ReservedEnvironment(name.clone()));
5270    }
5271    if env::var_os("RUSTC_WORKSPACE_WRAPPER").is_some()
5272        || request
5273            .environment
5274            .contains_key(OsStr::new("RUSTC_WORKSPACE_WRAPPER"))
5275    {
5276        return Err(DescriptorCargoRunError::ExistingWorkspaceWrapper);
5277    }
5278    if env::var_os("RUSTC_WRAPPER").is_some()
5279        || request
5280            .environment
5281            .contains_key(OsStr::new("RUSTC_WRAPPER"))
5282    {
5283        return Err(DescriptorCargoRunError::ExistingRustcWrapper);
5284    }
5285    prepare_descriptor_target_directory(&request.target_directory)?;
5286    let staging_parent = request
5287        .staging_directory
5288        .parent()
5289        .ok_or_else(|| {
5290            DescriptorCargoRunError::StagingWithoutParent(request.staging_directory.clone())
5291        })?
5292        .to_path_buf();
5293    fs::create_dir_all(&staging_parent).map_err(|source| {
5294        DescriptorCargoRunError::CreateStagingParent {
5295            path: staging_parent,
5296            source,
5297        }
5298    })?;
5299    let wrapper_staging = prepare_descriptor_staging_directory(request, staging_preparation)?;
5300
5301    let mut command = Command::new(&request.cargo);
5302    command
5303        .current_dir(&request.working_directory)
5304        .args(&request.cargo_args)
5305        .arg("--target-dir")
5306        .arg(&request.target_directory)
5307        .arg("--message-format=json-render-diagnostics")
5308        .envs(&request.environment);
5309    scrub_wrapper_control_environment(&mut command);
5310    command
5311        .env("RUSTC_WRAPPER", &request.wrapper)
5312        .env_remove("RUSTC_WORKSPACE_WRAPPER")
5313        .env(WRAPPER_MODE_ENV, WRAPPER_MODE_DESCRIPTOR_V1)
5314        .env(DESCRIPTOR_STAGING_DIR_ENV, &wrapper_staging)
5315        .env(DESCRIPTOR_TARGET_DIR_ENV, &request.target_directory)
5316        .env(
5317            SOURCE_EXCLUSION_DIR_ENV,
5318            &request.source_exclusion_directory,
5319        )
5320        .stdout(Stdio::piped())
5321        .stderr(Stdio::inherit());
5322    let mut child = command
5323        .spawn()
5324        .map_err(|source| DescriptorCargoRunError::SpawnCargo {
5325            program: PathBuf::from(&request.cargo),
5326            source,
5327        })?;
5328    let stdout = child
5329        .stdout
5330        .take()
5331        .ok_or(DescriptorCargoRunError::MissingCargoStdout)?;
5332    let mut collector = CargoArtifactCollector::default();
5333    for line in BufReader::new(stdout).lines() {
5334        let line = match line {
5335            Ok(line) => line,
5336            Err(source) => {
5337                let _ = child.kill();
5338                let _ = child.wait();
5339                return Err(DescriptorCargoRunError::ReadCargoStdout(source));
5340            }
5341        };
5342        forward_rendered_cargo_diagnostic(&line);
5343        if let Err(source) = collector.ingest_line(&line) {
5344            let _ = child.kill();
5345            let _ = child.wait();
5346            return Err(DescriptorCargoRunError::CargoProtocol(source));
5347        }
5348    }
5349    let status = child
5350        .wait()
5351        .map_err(DescriptorCargoRunError::WaitForCargo)?;
5352    if !status.success() {
5353        return Err(DescriptorCargoRunError::CargoFailed(status));
5354    }
5355    let cargo_artifacts = collector
5356        .finish()
5357        .map_err(DescriptorCargoRunError::CargoProtocol)?;
5358    let units = if staging_preparation == DescriptorStagingPreparation::ResumeOwned {
5359        load_descriptor_recovery_units(&request.staging_directory)?
5360    } else {
5361        let units_directory = request.staging_directory.join("units");
5362        if allow_empty_units && !units_directory.exists() {
5363            Vec::new()
5364        } else {
5365            let loaded = if trust_atomic_wrapper_hashes {
5366                load_descriptor_unit_sidecars_trusting_wrapper_hashes(&request.staging_directory)
5367            } else {
5368                load_descriptor_unit_sidecars(&request.staging_directory)
5369            };
5370            match loaded {
5371                Ok(units) => units,
5372                Err(DescriptorSidecarError::NoUnitSidecars(_)) if allow_empty_units => Vec::new(),
5373                Err(source) => return Err(DescriptorCargoRunError::Sidecars(source)),
5374            }
5375        }
5376    };
5377    Ok(DescriptorCargoOutput {
5378        cargo_artifacts,
5379        units,
5380    })
5381}
5382
5383fn prepare_descriptor_staging_directory(
5384    request: &DescriptorCargoRequest,
5385    preparation: DescriptorStagingPreparation,
5386) -> Result<PathBuf, DescriptorCargoRunError> {
5387    let metadata = match fs::symlink_metadata(&request.staging_directory) {
5388        Ok(metadata) => Some(metadata),
5389        Err(source) if source.kind() == io::ErrorKind::NotFound => None,
5390        Err(source) => {
5391            return Err(DescriptorCargoRunError::InspectCompletedStaging {
5392                path: request.staging_directory.clone(),
5393                source,
5394            });
5395        }
5396    };
5397
5398    if let Some(metadata) = metadata {
5399        if preparation == DescriptorStagingPreparation::Fresh {
5400            return Err(DescriptorCargoRunError::StagingAlreadyExists(
5401                request.staging_directory.clone(),
5402            ));
5403        }
5404        if !metadata.file_type().is_dir() {
5405            return Err(DescriptorCargoRunError::UnsafeCompletedStaging(
5406                request.staging_directory.clone(),
5407            ));
5408        }
5409        let owned =
5410            descriptor_staging_marker_is_valid(&request.staging_directory).map_err(|source| {
5411                DescriptorCargoRunError::ReadCompletedStagingMarker {
5412                    path: request.staging_directory.clone(),
5413                    source,
5414                }
5415            })?;
5416        if !owned {
5417            return Err(DescriptorCargoRunError::UnownedCompletedStaging(
5418                request.staging_directory.clone(),
5419            ));
5420        }
5421        return create_descriptor_recovery_attempt(&request.staging_directory);
5422    }
5423
5424    fs::create_dir(&request.staging_directory).map_err(|source| {
5425        DescriptorCargoRunError::CreateStaging {
5426            path: request.staging_directory.clone(),
5427            source,
5428        }
5429    })?;
5430    write_ownership_marker(
5431        &request.staging_directory,
5432        DESCRIPTOR_STAGING_MARKER_FILE,
5433        DESCRIPTOR_STAGING_MARKER_BYTES,
5434    )
5435    .map_err(|source| DescriptorCargoRunError::CreateStagingMarker {
5436        path: request.staging_directory.clone(),
5437        source,
5438    })?;
5439    match preparation {
5440        DescriptorStagingPreparation::Fresh => Ok(request.staging_directory.clone()),
5441        DescriptorStagingPreparation::ResumeOwned => {
5442            create_descriptor_recovery_attempt(&request.staging_directory)
5443        }
5444    }
5445}
5446
5447fn create_descriptor_recovery_attempt(
5448    staging_directory: &Path,
5449) -> Result<PathBuf, DescriptorCargoRunError> {
5450    let attempts_directory = staging_directory.join(DESCRIPTOR_RECOVERY_ATTEMPTS_DIRECTORY);
5451    match fs::symlink_metadata(&attempts_directory) {
5452        Ok(metadata) if metadata.file_type().is_dir() => {}
5453        Ok(_) => {
5454            return Err(DescriptorCargoRunError::UnexpectedRecoveryStagingEntry(
5455                attempts_directory,
5456            ));
5457        }
5458        Err(source) if source.kind() == io::ErrorKind::NotFound => {
5459            fs::create_dir(&attempts_directory).map_err(|source| {
5460                DescriptorCargoRunError::RecoveryStagingIo {
5461                    operation: "create",
5462                    path: attempts_directory.clone(),
5463                    source,
5464                }
5465            })?;
5466        }
5467        Err(source) => {
5468            return Err(DescriptorCargoRunError::RecoveryStagingIo {
5469                operation: "inspect",
5470                path: attempts_directory,
5471                source,
5472            });
5473        }
5474    }
5475    // Validate every prior attempt before adding another writer location. A
5476    // repeated recovery may leave any number of empty or partially populated
5477    // attempts, but never an unrecognized entry or redirected path.
5478    descriptor_recovery_staging_directories(staging_directory)?;
5479
5480    loop {
5481        let nonce = ATOMIC_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
5482        let attempt = attempts_directory.join(format!(
5483            "{DESCRIPTOR_RECOVERY_ATTEMPT_PREFIX}{}-{nonce}",
5484            std::process::id()
5485        ));
5486        match fs::create_dir(&attempt) {
5487            Ok(()) => return Ok(attempt),
5488            Err(source) if source.kind() == io::ErrorKind::AlreadyExists => continue,
5489            Err(source) => {
5490                return Err(DescriptorCargoRunError::RecoveryStagingIo {
5491                    operation: "create",
5492                    path: attempt,
5493                    source,
5494                });
5495            }
5496        }
5497    }
5498}
5499
5500fn load_descriptor_recovery_units(
5501    staging_directory: &Path,
5502) -> Result<Vec<ValidatedDescriptorUnit>, DescriptorCargoRunError> {
5503    let mut units = Vec::new();
5504    for candidate_staging in descriptor_recovery_staging_directories(staging_directory)? {
5505        let units_directory = candidate_staging.join("units");
5506        match fs::symlink_metadata(&units_directory) {
5507            Ok(metadata) if metadata.file_type().is_dir() => {}
5508            Ok(_) => {
5509                return Err(DescriptorCargoRunError::UnexpectedRecoveryStagingEntry(
5510                    units_directory,
5511                ));
5512            }
5513            Err(source) if source.kind() == io::ErrorKind::NotFound => continue,
5514            Err(source) => {
5515                return Err(DescriptorCargoRunError::RecoveryStagingIo {
5516                    operation: "inspect",
5517                    path: units_directory,
5518                    source,
5519                });
5520            }
5521        }
5522        match load_descriptor_unit_sidecars_for_recovery(&candidate_staging) {
5523            Ok(mut candidate_units) => units.append(&mut candidate_units),
5524            Err(DescriptorSidecarError::NoUnitSidecars(_)) => {}
5525            Err(source) => return Err(DescriptorCargoRunError::Sidecars(source)),
5526        }
5527    }
5528    Ok(units)
5529}
5530
5531fn descriptor_recovery_staging_directories(
5532    staging_directory: &Path,
5533) -> Result<Vec<PathBuf>, DescriptorCargoRunError> {
5534    let attempts_directory = staging_directory.join(DESCRIPTOR_RECOVERY_ATTEMPTS_DIRECTORY);
5535    let metadata = match fs::symlink_metadata(&attempts_directory) {
5536        Ok(metadata) => metadata,
5537        Err(source) if source.kind() == io::ErrorKind::NotFound => {
5538            return Ok(vec![staging_directory.to_path_buf()]);
5539        }
5540        Err(source) => {
5541            return Err(DescriptorCargoRunError::RecoveryStagingIo {
5542                operation: "inspect",
5543                path: attempts_directory,
5544                source,
5545            });
5546        }
5547    };
5548    if !metadata.file_type().is_dir() {
5549        return Err(DescriptorCargoRunError::UnexpectedRecoveryStagingEntry(
5550            attempts_directory,
5551        ));
5552    }
5553
5554    let entries = fs::read_dir(&attempts_directory).map_err(|source| {
5555        DescriptorCargoRunError::RecoveryStagingIo {
5556            operation: "enumerate",
5557            path: attempts_directory.clone(),
5558            source,
5559        }
5560    })?;
5561    let mut directories = vec![staging_directory.to_path_buf()];
5562    for entry in entries {
5563        let entry = entry.map_err(|source| DescriptorCargoRunError::RecoveryStagingIo {
5564            operation: "enumerate",
5565            path: attempts_directory.clone(),
5566            source,
5567        })?;
5568        let path = entry.path();
5569        let file_type =
5570            entry
5571                .file_type()
5572                .map_err(|source| DescriptorCargoRunError::RecoveryStagingIo {
5573                    operation: "inspect",
5574                    path: path.clone(),
5575                    source,
5576                })?;
5577        if !file_type.is_dir() || !descriptor_recovery_attempt_name(entry.file_name().as_os_str()) {
5578            return Err(DescriptorCargoRunError::UnexpectedRecoveryStagingEntry(
5579                path,
5580            ));
5581        }
5582        directories.push(path);
5583    }
5584    directories[1..].sort();
5585    Ok(directories)
5586}
5587
5588fn descriptor_recovery_attempt_name(name: &OsStr) -> bool {
5589    let Some(name) = name.to_str() else {
5590        return false;
5591    };
5592    let Some(coordinate) = name.strip_prefix(DESCRIPTOR_RECOVERY_ATTEMPT_PREFIX) else {
5593        return false;
5594    };
5595    let Some((process, nonce)) = coordinate.split_once('-') else {
5596        return false;
5597    };
5598    !process.is_empty()
5599        && process.bytes().all(|byte| byte.is_ascii_digit())
5600        && !nonce.is_empty()
5601        && nonce.bytes().all(|byte| byte.is_ascii_digit())
5602}
5603
5604#[derive(Clone, Debug, PartialEq, Eq)]
5605pub(crate) struct ValidatedDescriptorManagedPaths {
5606    pub(crate) working: PathBuf,
5607    pub(crate) staging: PathBuf,
5608    pub(crate) target: PathBuf,
5609    pub(crate) source_exclusion: PathBuf,
5610}
5611
5612pub(crate) fn validate_descriptor_managed_paths(
5613    request: &DescriptorCargoRequest,
5614) -> Result<ValidatedDescriptorManagedPaths, DescriptorCargoRunError> {
5615    if !request.working_directory.is_absolute() {
5616        return Err(DescriptorCargoRunError::RelativeWorkingDirectory(
5617            request.working_directory.clone(),
5618        ));
5619    }
5620    if !request.staging_directory.is_absolute() {
5621        return Err(DescriptorCargoRunError::RelativeStagingDirectory(
5622            request.staging_directory.clone(),
5623        ));
5624    }
5625    if !request.target_directory.is_absolute() {
5626        return Err(DescriptorCargoRunError::RelativeTargetDirectory(
5627            request.target_directory.clone(),
5628        ));
5629    }
5630    if !request.source_exclusion_directory.is_absolute() {
5631        return Err(DescriptorCargoRunError::RelativeSourceExclusionDirectory(
5632            request.source_exclusion_directory.clone(),
5633        ));
5634    }
5635    for path in [
5636        &request.working_directory,
5637        &request.staging_directory,
5638        &request.target_directory,
5639        &request.source_exclusion_directory,
5640    ] {
5641        if path.components().any(|component| {
5642            matches!(
5643                component,
5644                std::path::Component::CurDir | std::path::Component::ParentDir
5645            )
5646        }) {
5647            return Err(DescriptorCargoRunError::AmbiguousManagedDirectory(
5648                path.clone(),
5649            ));
5650        }
5651    }
5652    let normalized_working = normalize_descriptor_managed_path(&request.working_directory)?;
5653    let normalized_target = normalize_descriptor_managed_path(&request.target_directory)?;
5654    let normalized_staging = normalize_descriptor_managed_path(&request.staging_directory)?;
5655    let normalized_exclusion =
5656        normalize_descriptor_managed_path(&request.source_exclusion_directory)?;
5657    if normalized_target == normalized_exclusion
5658        || !normalized_target.starts_with(&normalized_exclusion)
5659    {
5660        return Err(DescriptorCargoRunError::TargetOutsideSourceExclusion {
5661            target: normalized_target,
5662            exclusion: normalized_exclusion,
5663        });
5664    }
5665    if normalized_staging == normalized_exclusion
5666        || !normalized_staging.starts_with(&normalized_exclusion)
5667    {
5668        return Err(DescriptorCargoRunError::StagingOutsideSourceExclusion {
5669            staging: normalized_staging,
5670            exclusion: normalized_exclusion,
5671        });
5672    }
5673    validate_plain_managed_descendant(
5674        "target",
5675        &request.source_exclusion_directory,
5676        &request.target_directory,
5677    )?;
5678    validate_plain_managed_descendant(
5679        "staging",
5680        &request.source_exclusion_directory,
5681        &request.staging_directory,
5682    )?;
5683    if managed_paths_overlap(&normalized_target, &normalized_staging) {
5684        return Err(
5685            DescriptorCargoRunError::OverlappingTargetAndStagingDirectories {
5686                target: normalized_target.clone(),
5687                staging: normalized_staging.clone(),
5688            },
5689        );
5690    }
5691    if normalized_exclusion == normalized_working
5692        || normalized_working.starts_with(&normalized_exclusion)
5693    {
5694        return Err(DescriptorCargoRunError::UnsafeSourceExclusion {
5695            exclusion: normalized_exclusion,
5696            working: normalized_working,
5697        });
5698    }
5699    Ok(ValidatedDescriptorManagedPaths {
5700        working: normalized_working,
5701        staging: normalized_staging,
5702        target: normalized_target,
5703        source_exclusion: normalized_exclusion,
5704    })
5705}
5706
5707pub(crate) fn acquire_descriptor_target_lease(
5708    target_directory: &Path,
5709) -> Result<DescriptorTargetLease, DescriptorCargoRunError> {
5710    let lock_path = descriptor_target_state_path(target_directory, "lock")?;
5711    let lock_directory = lock_path
5712        .parent()
5713        .expect("descriptor target state paths always have a lock directory");
5714    create_plain_lock_directory(lock_directory)?;
5715    match fs::symlink_metadata(&lock_path) {
5716        Ok(metadata) if !metadata.file_type().is_file() => {
5717            return Err(DescriptorCargoRunError::UnsafeTargetLock(lock_path));
5718        }
5719        Ok(_) => {}
5720        Err(source) if source.kind() == io::ErrorKind::NotFound => {}
5721        Err(source) => {
5722            return Err(DescriptorCargoRunError::OpenTargetLock {
5723                path: lock_path,
5724                source,
5725            });
5726        }
5727    }
5728    let file = OpenOptions::new()
5729        .create(true)
5730        .read(true)
5731        .write(true)
5732        .truncate(false)
5733        .open(&lock_path)
5734        .map_err(|source| DescriptorCargoRunError::OpenTargetLock {
5735            path: lock_path.clone(),
5736            source,
5737        })?;
5738    file.lock()
5739        .map_err(|source| DescriptorCargoRunError::AcquireTargetLock {
5740            path: lock_path,
5741            source,
5742        })?;
5743    Ok(DescriptorTargetLease { _file: file })
5744}
5745
5746/// Crash journal shared by every cache namespace that operates on one exact
5747/// descriptor target. The caller must hold [`DescriptorTargetLease`] while
5748/// reading, replacing, or removing this path.
5749pub(crate) fn descriptor_target_dirty_journal_path(
5750    target_directory: &Path,
5751) -> Result<PathBuf, DescriptorCargoRunError> {
5752    descriptor_target_state_path(target_directory, "dirty.json")
5753}
5754
5755fn descriptor_target_state_path(
5756    target_directory: &Path,
5757    suffix: &str,
5758) -> Result<PathBuf, DescriptorCargoRunError> {
5759    if !target_directory.is_absolute() {
5760        return Err(DescriptorCargoRunError::RelativeTargetDirectory(
5761            target_directory.to_path_buf(),
5762        ));
5763    }
5764    let target = normalize_descriptor_managed_path(target_directory)?;
5765    let parent = target
5766        .parent()
5767        .ok_or_else(|| DescriptorCargoRunError::TargetLockWithoutParent(target.clone()))?;
5768    let path_bytes = target
5769        .to_str()
5770        .ok_or_else(|| DescriptorCargoRunError::NonUtf8TargetLock(target.clone()))?
5771        .as_bytes();
5772    let mut hash = Sha256::new();
5773    hash.update(b"proa.rsjs.descriptor-target-lock.v1");
5774    hash.update((path_bytes.len() as u64).to_be_bytes());
5775    hash.update(path_bytes);
5776    let identity = hex_digest(&hash.finalize().into());
5777    Ok(parent
5778        .join(".proa-rsjs-target-locks")
5779        .join(format!("{identity}.{suffix}")))
5780}
5781
5782pub(crate) fn normalize_descriptor_managed_path(
5783    path: &Path,
5784) -> Result<PathBuf, DescriptorCargoRunError> {
5785    if contains_lexical_dot_component(path) {
5786        return Err(DescriptorCargoRunError::AmbiguousManagedDirectory(
5787            path.to_path_buf(),
5788        ));
5789    }
5790    normalize_managed_path_identity(path).map_err(|source| {
5791        DescriptorCargoRunError::NormalizeManagedDirectory {
5792            path: path.to_path_buf(),
5793            source,
5794        }
5795    })
5796}
5797
5798pub(crate) fn managed_paths_overlap(first: &Path, second: &Path) -> bool {
5799    first == second || first.starts_with(second) || second.starts_with(first)
5800}
5801
5802fn validate_plain_managed_descendant(
5803    kind: &'static str,
5804    anchor: &Path,
5805    descendant: &Path,
5806) -> Result<(), DescriptorCargoRunError> {
5807    let relative = descendant.strip_prefix(anchor).map_err(|_| {
5808        DescriptorCargoRunError::ManagedDirectoryNotLexicallyContained {
5809            kind,
5810            path: descendant.to_path_buf(),
5811            anchor: anchor.to_path_buf(),
5812        }
5813    })?;
5814    if relative.as_os_str().is_empty() {
5815        return Err(
5816            DescriptorCargoRunError::ManagedDirectoryNotLexicallyContained {
5817                kind,
5818                path: descendant.to_path_buf(),
5819                anchor: anchor.to_path_buf(),
5820            },
5821        );
5822    }
5823    let mut current = anchor.to_path_buf();
5824    let mut reached_missing_component = false;
5825    for component in relative.components() {
5826        let std::path::Component::Normal(component) = component else {
5827            return Err(DescriptorCargoRunError::AmbiguousManagedDirectory(
5828                descendant.to_path_buf(),
5829            ));
5830        };
5831        current.push(component);
5832        if reached_missing_component {
5833            continue;
5834        }
5835        match fs::symlink_metadata(&current) {
5836            Ok(metadata) if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() => {
5837                return Err(DescriptorCargoRunError::UnsafeManagedDirectoryComponent {
5838                    kind,
5839                    path: current,
5840                });
5841            }
5842            Ok(_) => {}
5843            Err(source) if source.kind() == io::ErrorKind::NotFound => {
5844                reached_missing_component = true;
5845            }
5846            Err(source) => {
5847                return Err(DescriptorCargoRunError::InspectManagedDirectory {
5848                    kind,
5849                    path: current,
5850                    source,
5851                });
5852            }
5853        }
5854    }
5855    Ok(())
5856}
5857
5858pub(crate) fn normalize_managed_path_identity(path: &Path) -> io::Result<PathBuf> {
5859    use std::path::Component;
5860
5861    if !path.is_absolute() {
5862        return Err(io::Error::new(
5863            io::ErrorKind::InvalidInput,
5864            "managed path is not absolute",
5865        ));
5866    }
5867    if contains_lexical_dot_component(path) {
5868        return Err(io::Error::new(
5869            io::ErrorKind::InvalidInput,
5870            "managed path contains `.` or `..`",
5871        ));
5872    }
5873    let mut lexical = PathBuf::new();
5874    for component in path.components() {
5875        match component {
5876            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
5877                lexical.push(component.as_os_str());
5878            }
5879            Component::CurDir => {}
5880            Component::ParentDir => {
5881                if !lexical.pop() {
5882                    return Err(io::Error::new(
5883                        io::ErrorKind::InvalidInput,
5884                        "managed path escapes its filesystem root",
5885                    ));
5886                }
5887            }
5888        }
5889    }
5890    let mut ancestor = lexical.clone();
5891    let mut suffix = Vec::new();
5892    loop {
5893        match fs::symlink_metadata(&ancestor) {
5894            Ok(_) => break,
5895            Err(source) if source.kind() == io::ErrorKind::NotFound => {
5896                let name = ancestor.file_name().ok_or_else(|| {
5897                    io::Error::new(
5898                        io::ErrorKind::NotFound,
5899                        "managed path has no existing ancestor",
5900                    )
5901                })?;
5902                suffix.push(name.to_os_string());
5903                ancestor.pop();
5904            }
5905            Err(source) => return Err(source),
5906        }
5907    }
5908    let mut normalized = fs::canonicalize(&ancestor)?;
5909    for component in suffix.into_iter().rev() {
5910        normalized.push(component);
5911    }
5912    Ok(normalized)
5913}
5914
5915#[cfg(unix)]
5916fn contains_lexical_dot_component(path: &Path) -> bool {
5917    use std::os::unix::ffi::OsStrExt as _;
5918
5919    path.as_os_str()
5920        .as_bytes()
5921        .split(|byte| *byte == b'/')
5922        .any(|component| matches!(component, b"." | b".."))
5923}
5924
5925#[cfg(windows)]
5926fn contains_lexical_dot_component(path: &Path) -> bool {
5927    use std::os::windows::ffi::OsStrExt as _;
5928
5929    let mut component = Vec::new();
5930    for unit in path.as_os_str().encode_wide().chain([b'/' as u16]) {
5931        if unit == b'/' as u16 || unit == b'\\' as u16 {
5932            if component.as_slice() == [b'.' as u16]
5933                || component.as_slice() == [b'.' as u16, b'.' as u16]
5934            {
5935                return true;
5936            }
5937            component.clear();
5938        } else {
5939            component.push(unit);
5940        }
5941    }
5942    false
5943}
5944
5945fn create_plain_lock_directory(path: &Path) -> Result<(), DescriptorCargoRunError> {
5946    fs::create_dir_all(path).map_err(|source| {
5947        DescriptorCargoRunError::CreateTargetLockDirectory {
5948            path: path.to_path_buf(),
5949            source,
5950        }
5951    })?;
5952    let metadata = fs::symlink_metadata(path).map_err(|source| {
5953        DescriptorCargoRunError::CreateTargetLockDirectory {
5954            path: path.to_path_buf(),
5955            source,
5956        }
5957    })?;
5958    if !metadata.file_type().is_dir() {
5959        return Err(DescriptorCargoRunError::UnsafeTargetLock(
5960            path.to_path_buf(),
5961        ));
5962    }
5963    Ok(())
5964}
5965
5966pub(crate) fn descriptor_target_marker_is_valid(path: &Path) -> io::Result<bool> {
5967    ownership_marker_is_valid(
5968        path,
5969        DESCRIPTOR_TARGET_MARKER_FILE,
5970        DESCRIPTOR_TARGET_MARKER_BYTES,
5971    )
5972}
5973
5974pub(crate) fn descriptor_staging_marker_is_valid(path: &Path) -> io::Result<bool> {
5975    ownership_marker_is_valid(
5976        path,
5977        DESCRIPTOR_STAGING_MARKER_FILE,
5978        DESCRIPTOR_STAGING_MARKER_BYTES,
5979    )
5980}
5981
5982fn ownership_marker_is_valid(path: &Path, name: &str, bytes: &[u8]) -> io::Result<bool> {
5983    let marker = path.join(name);
5984    let metadata = match fs::symlink_metadata(&marker) {
5985        Ok(metadata) => metadata,
5986        Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(false),
5987        Err(source) => return Err(source),
5988    };
5989    if !metadata.file_type().is_file() {
5990        return Ok(false);
5991    }
5992    Ok(fs::read(marker)? == bytes)
5993}
5994
5995pub(crate) fn prepare_descriptor_target_directory(
5996    path: &Path,
5997) -> Result<(), DescriptorCargoRunError> {
5998    match fs::symlink_metadata(path) {
5999        Ok(metadata) if !metadata.file_type().is_dir() => {
6000            return Err(DescriptorCargoRunError::DescriptorTargetNotDirectory(
6001                path.to_path_buf(),
6002            ));
6003        }
6004        Ok(_) => {
6005            if descriptor_target_marker_is_valid(path).map_err(|source| {
6006                DescriptorCargoRunError::ReadDescriptorTargetMarker {
6007                    path: path.to_path_buf(),
6008                    source,
6009                }
6010            })? {
6011                return Ok(());
6012            }
6013            let mut entries = fs::read_dir(path).map_err(|source| {
6014                DescriptorCargoRunError::ReadDescriptorTarget {
6015                    path: path.to_path_buf(),
6016                    source,
6017                }
6018            })?;
6019            if entries.next().is_some() {
6020                return Err(DescriptorCargoRunError::UnownedDescriptorTarget(
6021                    path.to_path_buf(),
6022                ));
6023            }
6024        }
6025        Err(source) if source.kind() == io::ErrorKind::NotFound => {
6026            fs::create_dir_all(path).map_err(|source| {
6027                DescriptorCargoRunError::CreateDescriptorTarget {
6028                    path: path.to_path_buf(),
6029                    source,
6030                }
6031            })?;
6032        }
6033        Err(source) => {
6034            return Err(DescriptorCargoRunError::ReadDescriptorTarget {
6035                path: path.to_path_buf(),
6036                source,
6037            });
6038        }
6039    }
6040
6041    write_ownership_marker(
6042        path,
6043        DESCRIPTOR_TARGET_MARKER_FILE,
6044        DESCRIPTOR_TARGET_MARKER_BYTES,
6045    )
6046    .map_err(
6047        |source| DescriptorCargoRunError::CreateDescriptorTargetMarker {
6048            path: path.join(DESCRIPTOR_TARGET_MARKER_FILE),
6049            source,
6050        },
6051    )
6052}
6053
6054fn write_ownership_marker(path: &Path, name: &str, bytes: &[u8]) -> io::Result<()> {
6055    let marker = path.join(name);
6056    let mut file = OpenOptions::new()
6057        .create_new(true)
6058        .write(true)
6059        .open(&marker)?;
6060    file.write_all(bytes).and_then(|()| file.sync_all())?;
6061    sync_created_directory(path)
6062}
6063
6064#[cfg(unix)]
6065fn sync_created_directory(path: &Path) -> io::Result<()> {
6066    File::open(path)?.sync_all()
6067}
6068
6069#[cfg(not(unix))]
6070fn sync_created_directory(_path: &Path) -> io::Result<()> {
6071    Ok(())
6072}
6073
6074fn forward_rendered_cargo_diagnostic(line: &str) {
6075    let Ok(value) = serde_json::from_str::<Value>(line) else {
6076        return;
6077    };
6078    if value.get("reason").and_then(Value::as_str) != Some("compiler-message") {
6079        return;
6080    }
6081    if let Some(rendered) = value
6082        .get("message")
6083        .and_then(|message| message.get("rendered"))
6084        .and_then(Value::as_str)
6085    {
6086        eprint!("{rendered}");
6087    }
6088}
6089
6090/// Descriptor Cargo process/orchestration failure.
6091#[derive(Debug, Error)]
6092pub enum DescriptorCargoRunError {
6093    /// Wrapper path is not invocation-stable.
6094    #[error("descriptor wrapper path must be absolute: `{0}`")]
6095    RelativeWrapper(PathBuf),
6096    /// Cargo working directory must be explicit.
6097    #[error("descriptor Cargo working directory must be absolute: `{0}`")]
6098    RelativeWorkingDirectory(PathBuf),
6099    /// Staging path must be explicit.
6100    #[error("descriptor staging directory must be absolute: `{0}`")]
6101    RelativeStagingDirectory(PathBuf),
6102    /// Descriptor target is an exact deletion/recovery boundary.
6103    #[error("descriptor target directory must be absolute: `{0}`")]
6104    RelativeTargetDirectory(PathBuf),
6105    /// Generated source exclusion must be explicit and phase invariant.
6106    #[error("descriptor source exclusion directory must be absolute: `{0}`")]
6107    RelativeSourceExclusionDirectory(PathBuf),
6108    /// Exact descriptor output must be contained by the generated subtree.
6109    #[error("descriptor target `{target}` must be inside source exclusion `{exclusion}`")]
6110    TargetOutsideSourceExclusion {
6111        /// Exact target.
6112        target: PathBuf,
6113        /// Exact excluded generated root.
6114        exclusion: PathBuf,
6115    },
6116    /// Invocation staging is generated state too; allowing it inside a
6117    /// package's hashed source tree makes later unit identities depend on
6118    /// compile order and stale sidecars.
6119    #[error("descriptor staging `{staging}` must be inside source exclusion `{exclusion}`")]
6120    StagingOutsideSourceExclusion {
6121        /// Fresh invocation-local staging directory.
6122        staging: PathBuf,
6123        /// Exact excluded generated root.
6124        exclusion: PathBuf,
6125    },
6126    /// Managed deletion/identity boundaries must have one unambiguous lexical
6127    /// spelling before filesystem canonicalization.
6128    #[error("descriptor managed directory contains `.` or `..`: `{0}`")]
6129    AmbiguousManagedDirectory(PathBuf),
6130    /// Managed outputs must be lexical descendants of the exact generated
6131    /// root as well as canonical descendants of it.
6132    #[error("descriptor {kind} `{path}` is not lexically inside generated root `{anchor}`")]
6133    ManagedDirectoryNotLexicallyContained {
6134        /// Managed output role.
6135        kind: &'static str,
6136        /// Rejected output root.
6137        path: PathBuf,
6138        /// Exact generated trust anchor.
6139        anchor: PathBuf,
6140    },
6141    /// Existing descendants may not redirect generated writes through a
6142    /// symlink or special file.
6143    #[error("unsafe existing descriptor {kind} path component: `{path}`")]
6144    UnsafeManagedDirectoryComponent {
6145        /// Managed output role.
6146        kind: &'static str,
6147        /// Unsafe existing component.
6148        path: PathBuf,
6149    },
6150    /// Existing managed descendants could not be inspected safely.
6151    #[error("failed to inspect descriptor {kind} path component `{path}`: {source}")]
6152    InspectManagedDirectory {
6153        /// Managed output role.
6154        kind: &'static str,
6155        /// Component being inspected.
6156        path: PathBuf,
6157        /// Filesystem failure.
6158        #[source]
6159        source: io::Error,
6160    },
6161    /// Target and staging are independently deleted/replaced and therefore
6162    /// cannot contain one another.
6163    #[error("descriptor target `{target}` and staging `{staging}` overlap")]
6164    OverlappingTargetAndStagingDirectories {
6165        /// Persistent Cargo target.
6166        target: PathBuf,
6167        /// Invocation-local staging directory.
6168        staging: PathBuf,
6169    },
6170    /// Excluding the Cargo working directory (or one of its ancestors) would
6171    /// erase actual package inputs from source-closure identity.
6172    #[error(
6173        "descriptor source exclusion `{exclusion}` would contain working directory `{working}`"
6174    )]
6175    UnsafeSourceExclusion {
6176        /// Exact normalized generated root.
6177        exclusion: PathBuf,
6178        /// Exact normalized Cargo working directory.
6179        working: PathBuf,
6180    },
6181    /// A normalized target must retain a filesystem parent for its sibling
6182    /// lock namespace.
6183    #[error("descriptor target has no parent for its lock: `{0}`")]
6184    TargetLockWithoutParent(PathBuf),
6185    /// The lock identity must be portable canonical UTF-8 rather than a lossy
6186    /// rendering of an OS path.
6187    #[error("descriptor target lock path is not UTF-8: `{0}`")]
6188    NonUtf8TargetLock(PathBuf),
6189    /// Canonical managed-directory identity could not be resolved safely.
6190    #[error("failed to normalize descriptor managed directory `{path}`: {source}")]
6191    NormalizeManagedDirectory {
6192        /// Requested managed path.
6193        path: PathBuf,
6194        /// Path normalization failure.
6195        #[source]
6196        source: io::Error,
6197    },
6198    /// The sibling target-lock directory could not be created or inspected.
6199    #[error("failed to create descriptor target lock directory `{path}`: {source}")]
6200    CreateTargetLockDirectory {
6201        /// Lock directory.
6202        path: PathBuf,
6203        /// I/O failure.
6204        #[source]
6205        source: io::Error,
6206    },
6207    /// Symlinks and non-files are never accepted as target-lock entries.
6208    #[error("unsafe descriptor target lock entry: `{0}`")]
6209    UnsafeTargetLock(PathBuf),
6210    /// The target lock could not be opened.
6211    #[error("failed to open descriptor target lock `{path}`: {source}")]
6212    OpenTargetLock {
6213        /// Exact lock file.
6214        path: PathBuf,
6215        /// I/O failure.
6216        #[source]
6217        source: io::Error,
6218    },
6219    /// Another descriptor invocation's target lease could not be acquired.
6220    #[error("failed to acquire descriptor target lock `{path}`: {source}")]
6221    AcquireTargetLock {
6222        /// Exact lock file.
6223        path: PathBuf,
6224        /// Lock failure.
6225        #[source]
6226        source: io::Error,
6227    },
6228    /// Only the cached runner has enough authority to reconcile a cached
6229    /// crash journal with immutable generations and pointer commits.
6230    #[error(
6231        "descriptor target has an interrupted cached generation journal `{0}`; recover it with the cached runner or use a fresh descriptor target"
6232    )]
6233    CachedCrashJournalRequiresRecovery(PathBuf),
6234    /// A target crash journal may not be redirected or replaced by a special
6235    /// filesystem entry.
6236    #[error("unsafe descriptor target crash journal: `{0}`")]
6237    UnsafeTargetJournal(PathBuf),
6238    /// The target crash journal could not be inspected while holding the
6239    /// canonical target lease.
6240    #[error("failed to inspect descriptor target crash journal `{path}`: {source}")]
6241    ReadTargetJournal {
6242        /// Exact journal path.
6243        path: PathBuf,
6244        /// I/O failure.
6245        #[source]
6246        source: io::Error,
6247    },
6248    /// No Cargo subcommand/selection was supplied.
6249    #[error("descriptor Cargo invocation has no arguments")]
6250    MissingCargoArguments,
6251    /// The runner owns Cargo's JSON protocol.
6252    #[error("descriptor Cargo argument `{0:?}` is reserved; cargo-proa supplies message format")]
6253    ReservedCargoArgument(OsString),
6254    /// Wrapper-control variables belong exclusively to cargo-proa.
6255    #[error("descriptor Cargo environment `{0:?}` is reserved")]
6256    ReservedEnvironment(OsString),
6257    /// Proc-macro filesystem fallbacks are not part of exact build identity.
6258    #[error("descriptor Cargo environment `{0}` is unsupported by the exact linked pipeline")]
6259    UnsupportedEnvironment(&'static str),
6260    /// Existing nonempty directories cannot be silently claimed for recovery.
6261    #[error("descriptor target directory is not owned by cargo-proa: `{0}`")]
6262    UnownedDescriptorTarget(PathBuf),
6263    /// The target path must be a directory.
6264    #[error("descriptor target path is not a directory: `{0}`")]
6265    DescriptorTargetNotDirectory(PathBuf),
6266    /// Descriptor target creation failed.
6267    #[error("failed to create descriptor target directory `{path}`: {source}")]
6268    CreateDescriptorTarget {
6269        /// Exact target.
6270        path: PathBuf,
6271        /// I/O failure.
6272        #[source]
6273        source: io::Error,
6274    },
6275    /// Existing descriptor target state could not be inspected.
6276    #[error("failed to inspect descriptor target directory `{path}`: {source}")]
6277    ReadDescriptorTarget {
6278        /// Exact target.
6279        path: PathBuf,
6280        /// I/O failure.
6281        #[source]
6282        source: io::Error,
6283    },
6284    /// Target ownership marker could not be read.
6285    #[error("failed to read descriptor target ownership marker in `{path}`: {source}")]
6286    ReadDescriptorTargetMarker {
6287        /// Exact target.
6288        path: PathBuf,
6289        /// I/O failure.
6290        #[source]
6291        source: io::Error,
6292    },
6293    /// Target ownership marker could not be durably created.
6294    #[error("failed to create descriptor target ownership marker `{path}`: {source}")]
6295    CreateDescriptorTargetMarker {
6296        /// Exact marker.
6297        path: PathBuf,
6298        /// I/O failure.
6299        #[source]
6300        source: io::Error,
6301    },
6302    /// Existing wrappers are not represented by the current identity model.
6303    #[error("RUSTC_WORKSPACE_WRAPPER is set; unset both Cargo rustc wrapper variables before invoking cargo-proa")]
6304    ExistingWorkspaceWrapper,
6305    /// An inherited wrapper is outside the descriptor/final cache identity.
6306    #[error(
6307        "RUSTC_WRAPPER is set; unset it before invoking cargo-proa so descriptor cache identity cannot bypass wrapper semantics"
6308    )]
6309    ExistingRustcWrapper,
6310    /// Ordinary invocations cannot reuse staging; cached crash recovery uses a
6311    /// separate marker-validated path that revalidates every retained record.
6312    #[error("descriptor staging directory already exists: `{0}`")]
6313    StagingAlreadyExists(PathBuf),
6314    /// Staging root has no parent.
6315    #[error("descriptor staging directory has no parent: `{0}`")]
6316    StagingWithoutParent(PathBuf),
6317    /// Staging parent creation failed.
6318    #[error("failed to create descriptor staging parent `{path}`: {source}")]
6319    CreateStagingParent {
6320        /// Parent path.
6321        path: PathBuf,
6322        /// I/O failure.
6323        #[source]
6324        source: io::Error,
6325    },
6326    /// Fresh staging creation failed.
6327    #[error("failed to create fresh descriptor staging directory `{path}`: {source}")]
6328    CreateStaging {
6329        /// Fresh path.
6330        path: PathBuf,
6331        /// I/O failure.
6332        #[source]
6333        source: io::Error,
6334    },
6335    /// Fresh staging ownership marker could not be durably created.
6336    #[error("failed to create descriptor staging ownership marker in `{path}`: {source}")]
6337    CreateStagingMarker {
6338        /// Fresh staging root.
6339        path: PathBuf,
6340        /// I/O failure.
6341        #[source]
6342        source: io::Error,
6343    },
6344    /// A recovery attempt directory could not be created, inspected, or
6345    /// enumerated beneath the marker-owned staging root.
6346    #[error("failed to {operation} descriptor recovery staging path `{path}`: {source}")]
6347    RecoveryStagingIo {
6348        /// Filesystem operation that failed.
6349        operation: &'static str,
6350        /// Exact recovery path.
6351        path: PathBuf,
6352        /// I/O failure.
6353        #[source]
6354        source: io::Error,
6355    },
6356    /// Recovery attempts accept only strict runner-named plain directories.
6357    #[error("unexpected descriptor recovery staging entry: `{0}`")]
6358    UnexpectedRecoveryStagingEntry(PathBuf),
6359    /// Successful cleanup requires the descriptor runner's exact ownership
6360    /// marker to remain readable.
6361    #[error("failed to read completed descriptor staging ownership marker in `{path}`: {source}")]
6362    ReadCompletedStagingMarker {
6363        /// Exact invocation-local staging root.
6364        path: PathBuf,
6365        /// I/O failure.
6366        #[source]
6367        source: io::Error,
6368    },
6369    /// A successful linked run cannot delete staging it cannot prove it owns.
6370    #[error("refusing to remove unowned completed descriptor staging directory `{0}`")]
6371    UnownedCompletedStaging(PathBuf),
6372    /// The marker-bearing staging root must still be a plain directory.
6373    #[error("refusing to remove non-directory completed descriptor staging path `{0}`")]
6374    UnsafeCompletedStaging(PathBuf),
6375    /// The completed staging root could not be inspected after marker
6376    /// validation.
6377    #[error("failed to inspect completed descriptor staging directory `{path}`: {source}")]
6378    InspectCompletedStaging {
6379        /// Exact invocation-local staging root.
6380        path: PathBuf,
6381        /// I/O failure.
6382        #[source]
6383        source: io::Error,
6384    },
6385    /// Exact marker-owned staging cleanup failed.
6386    #[error("failed to remove completed descriptor staging directory `{path}`: {source}")]
6387    RemoveCompletedStaging {
6388        /// Exact invocation-local staging root.
6389        path: PathBuf,
6390        /// I/O failure.
6391        #[source]
6392        source: io::Error,
6393    },
6394    /// Cargo could not be spawned.
6395    #[error("failed to run Cargo `{program}`: {source}")]
6396    SpawnCargo {
6397        /// Program path.
6398        program: PathBuf,
6399        /// Process failure.
6400        #[source]
6401        source: io::Error,
6402    },
6403    /// Piped Cargo stdout was unexpectedly unavailable.
6404    #[error("descriptor Cargo process has no piped stdout")]
6405    MissingCargoStdout,
6406    /// Cargo JSON stream could not be read.
6407    #[error("failed to read descriptor Cargo stdout: {0}")]
6408    ReadCargoStdout(io::Error),
6409    /// Cargo process wait failed.
6410    #[error("failed to wait for descriptor Cargo: {0}")]
6411    WaitForCargo(io::Error),
6412    /// Cargo exited unsuccessfully.
6413    #[error("descriptor Cargo compilation failed with {0}")]
6414    CargoFailed(ExitStatus),
6415    /// Cargo's JSON stream was malformed or incomplete.
6416    #[error(transparent)]
6417    CargoProtocol(CargoMessageError),
6418    /// Wrapper outputs did not validate.
6419    #[error(transparent)]
6420    Sidecars(DescriptorSidecarError),
6421}
6422
6423#[derive(Clone, Copy)]
6424enum JsonFieldKind {
6425    NonemptyString,
6426    Array,
6427    Object,
6428}
6429
6430fn validate_auxiliary_message(
6431    value: &Value,
6432    line: usize,
6433    reason: &str,
6434    required: &[(&str, JsonFieldKind)],
6435) -> Result<(), CargoMessageError> {
6436    let valid = required.iter().all(|(field, kind)| {
6437        value.get(*field).is_some_and(|value| match kind {
6438            JsonFieldKind::NonemptyString => value.as_str().is_some_and(|value| !value.is_empty()),
6439            JsonFieldKind::Array => value.is_array(),
6440            JsonFieldKind::Object => value.is_object(),
6441        })
6442    });
6443    if valid {
6444        Ok(())
6445    } else {
6446        Err(CargoMessageError::MalformedAuxiliaryMessage {
6447            line,
6448            reason: reason.to_string(),
6449        })
6450    }
6451}
6452
6453/// Exact caller-provided selector for one wrapper unit.
6454#[derive(Clone, Debug, PartialEq)]
6455pub struct CargoArtifactExpectation {
6456    /// Descriptor unit to associate with the Cargo artifact.
6457    pub unit: DescriptorCargoUnitId,
6458    /// Exact Cargo package ID.
6459    pub package_id: String,
6460    /// Exact target name.
6461    pub target_name: String,
6462    /// Exact Cargo target-kind set.
6463    pub target_kinds: BTreeSet<String>,
6464    /// Exact crate-type set.
6465    pub crate_types: BTreeSet<String>,
6466    /// Exact enabled-feature set.
6467    pub features: BTreeSet<String>,
6468    /// Exact Cargo profile JSON.
6469    pub profile: Value,
6470    /// At least one exact Cargo-enumerated path required for the match.
6471    pub required_filenames: BTreeSet<PathBuf>,
6472}
6473
6474/// Match each descriptor unit to exactly one Cargo-enumerated artifact.
6475pub fn match_exact_cargo_artifacts(
6476    artifacts: &[CargoCompilerArtifact],
6477    expectations: &[CargoArtifactExpectation],
6478) -> Result<BTreeMap<DescriptorCargoUnitId, CargoCompilerArtifact>, ArtifactMatchError> {
6479    let mut matched = BTreeMap::new();
6480    let mut claimed_messages = BTreeSet::new();
6481
6482    for expectation in expectations {
6483        if expectation.required_filenames.is_empty() {
6484            return Err(ArtifactMatchError::NoRequiredFilenames(expectation.unit));
6485        }
6486        if matched.contains_key(&expectation.unit) {
6487            return Err(ArtifactMatchError::DuplicateUnitExpectation(
6488                expectation.unit,
6489            ));
6490        }
6491
6492        let candidates = artifacts
6493            .iter()
6494            .enumerate()
6495            .filter(|(_, artifact)| {
6496                artifact.package_id == expectation.package_id
6497                    && artifact.target.name == expectation.target_name
6498                    && artifact.target.kind == expectation.target_kinds
6499                    && artifact.target.crate_types == expectation.crate_types
6500                    && artifact.features == expectation.features
6501                    && artifact.profile == expectation.profile
6502                    && expectation
6503                        .required_filenames
6504                        .is_subset(&artifact.filenames)
6505            })
6506            .collect::<Vec<_>>();
6507
6508        let (message_index, artifact) = match candidates.as_slice() {
6509            [] => return Err(ArtifactMatchError::MissingArtifact(expectation.unit)),
6510            [(message_index, artifact)] => (*message_index, (*artifact).clone()),
6511            _ => {
6512                return Err(ArtifactMatchError::AmbiguousArtifact {
6513                    unit: expectation.unit,
6514                    matches: candidates.len(),
6515                });
6516            }
6517        };
6518        if !claimed_messages.insert(message_index) {
6519            return Err(ArtifactMatchError::ArtifactClaimedByMultipleUnits {
6520                artifact: artifact
6521                    .filenames
6522                    .iter()
6523                    .next()
6524                    .cloned()
6525                    .expect("collector rejects artifacts without filenames"),
6526            });
6527        }
6528        matched.insert(expectation.unit, artifact);
6529    }
6530
6531    Ok(matched)
6532}
6533
6534/// Join wrapper units to Cargo messages from the same invocation using exact
6535/// manifest/source identity plus the realized target, crate-type, and feature
6536/// sets.
6537///
6538/// Host paths participate only in this freshness join. They are excluded from
6539/// the canonical Cargo-unit and link-plan identities.
6540pub fn join_descriptor_units_to_cargo_artifacts(
6541    units: &[ValidatedDescriptorUnit],
6542    artifacts: &[CargoCompilerArtifact],
6543) -> Result<BTreeMap<DescriptorCargoUnitId, CargoCompilerArtifact>, UnitArtifactJoinError> {
6544    let mut joined = BTreeMap::new();
6545    let mut claimed_artifacts = BTreeSet::new();
6546    for unit in units {
6547        let manifest_path = unit
6548            .sidecar
6549            .cargo_manifest_path
6550            .as_ref()
6551            .ok_or(UnitArtifactJoinError::MissingCargoManifest(unit.unit))?;
6552        if !manifest_path.is_absolute() {
6553            return Err(UnitArtifactJoinError::RelativeCargoManifest {
6554                unit: unit.unit,
6555                path: manifest_path.clone(),
6556            });
6557        }
6558        let crate_types = unit
6559            .sidecar
6560            .crate_types
6561            .iter()
6562            .cloned()
6563            .collect::<BTreeSet<_>>();
6564        if crate_types.len() != unit.sidecar.crate_types.len() {
6565            return Err(UnitArtifactJoinError::DuplicateCrateType(unit.unit));
6566        }
6567        let features = unit
6568            .sidecar
6569            .features
6570            .iter()
6571            .cloned()
6572            .collect::<BTreeSet<_>>();
6573        if features.len() != unit.sidecar.features.len() {
6574            return Err(UnitArtifactJoinError::DuplicateFeature(unit.unit));
6575        }
6576        let cargo_extra_filename = unit.sidecar.cargo_extra_filename.as_deref();
6577        if let Some(cargo_extra_filename) = cargo_extra_filename {
6578            validate_cargo_extra_filename(cargo_extra_filename).map_err(|reason| {
6579                UnitArtifactJoinError::InvalidCargoExtraFilename {
6580                    unit: unit.unit,
6581                    value: cargo_extra_filename.to_string(),
6582                    reason,
6583                }
6584            })?;
6585        }
6586
6587        let mut candidates = Vec::new();
6588        for (index, artifact) in artifacts.iter().enumerate() {
6589            if artifact.manifest_path != *manifest_path
6590                || normalize_cargo_crate_name(&artifact.target.name) != unit.sidecar.crate_name
6591                || artifact.target.crate_types != crate_types
6592                || artifact.features != features
6593            {
6594                continue;
6595            }
6596            let source_hash =
6597                hash_file(&artifact.target.src_path, FILE_HASH_DOMAIN).map_err(|source| {
6598                    UnitArtifactJoinError::HashCargoSource {
6599                        path: artifact.target.src_path.clone(),
6600                        source,
6601                    }
6602                })?;
6603            let output_identity_matches = match cargo_extra_filename {
6604                Some(suffix) => {
6605                    artifact_has_cargo_extra_filename(artifact, &unit.sidecar.crate_name, suffix)
6606                        || (unit.sidecar.cargo_primary_package
6607                            && crate_types.contains("bin")
6608                            && artifact.executable.is_some()
6609                            && artifact_has_unhashed_primary_output(
6610                                artifact,
6611                                &unit.sidecar.crate_name,
6612                            ))
6613                }
6614                // Cargo can also emit canonical unhashed outputs for a
6615                // dependency that declares `cdylib` alongside `rlib`. Match
6616                // the exact compiler-artifact record instead of assuming only
6617                // the primary package can lack `-C extra-filename`.
6618                None => artifact_has_unhashed_primary_output(artifact, &unit.sidecar.crate_name),
6619            };
6620            if hex_digest(&source_hash) == unit.sidecar.source_hash && output_identity_matches {
6621                candidates.push((index, artifact));
6622            }
6623        }
6624
6625        let (index, artifact) = match candidates.as_slice() {
6626            [] => return Err(UnitArtifactJoinError::MissingArtifact(unit.unit)),
6627            [(index, artifact)] => (*index, (*artifact).clone()),
6628            _ => {
6629                return Err(UnitArtifactJoinError::AmbiguousArtifact {
6630                    unit: unit.unit,
6631                    matches: candidates.len(),
6632                });
6633            }
6634        };
6635        if !claimed_artifacts.insert(index) {
6636            return Err(UnitArtifactJoinError::ArtifactClaimedTwice {
6637                path: artifact
6638                    .filenames
6639                    .iter()
6640                    .next()
6641                    .cloned()
6642                    .expect("CargoArtifactCollector requires filenames"),
6643            });
6644        }
6645        joined.insert(unit.unit, artifact);
6646    }
6647    Ok(joined)
6648}
6649
6650/// Join every descriptor unit for which Cargo emitted a distinct
6651/// `compiler-artifact` message.
6652///
6653/// Host/target feature contexts without their own Cargo artifact are skipped;
6654/// they can still enter a root manifest only when an exact reachable
6655/// dependency artifact resolves them later.
6656pub fn join_cargo_enumerated_descriptor_units(
6657    units: &[ValidatedDescriptorUnit],
6658    artifacts: &[CargoCompilerArtifact],
6659) -> Result<BTreeMap<DescriptorCargoUnitId, CargoCompilerArtifact>, UnitArtifactJoinError> {
6660    let mut joined = BTreeMap::new();
6661    let mut claimed = BTreeMap::<
6662        (
6663            PathBuf,
6664            String,
6665            BTreeSet<String>,
6666            BTreeSet<String>,
6667            BTreeSet<PathBuf>,
6668        ),
6669        DescriptorCargoUnitId,
6670    >::new();
6671
6672    for unit in units {
6673        let one =
6674            match join_descriptor_units_to_cargo_artifacts(std::slice::from_ref(unit), artifacts) {
6675                Ok(one) => one,
6676                // Cargo can invoke rustc for host/target feature contexts for
6677                // which it publishes no distinct `compiler-artifact` message.
6678                // Such units are not roots and cannot enter the root extern graph:
6679                // if a reachable `--extern` refers to one, dependency-hash
6680                // resolution below still fails closed.
6681                Err(UnitArtifactJoinError::MissingArtifact(_)) => continue,
6682                Err(error) => return Err(error),
6683            };
6684        let artifact = one
6685            .into_values()
6686            .next()
6687            .expect("one-unit join returns one artifact");
6688        let key = (
6689            artifact.manifest_path.clone(),
6690            artifact.target.name.clone(),
6691            artifact.target.kind.clone(),
6692            artifact.target.crate_types.clone(),
6693            artifact.filenames.clone(),
6694        );
6695        if claimed.insert(key, unit.unit).is_some() {
6696            return Err(UnitArtifactJoinError::ArtifactClaimedTwice {
6697                path: artifact
6698                    .filenames
6699                    .iter()
6700                    .next()
6701                    .cloned()
6702                    .expect("CargoArtifactCollector requires filenames"),
6703            });
6704        }
6705        joined.insert(unit.unit, artifact);
6706    }
6707    Ok(joined)
6708}
6709
6710fn normalize_cargo_crate_name(name: &str) -> String {
6711    name.replace('-', "_")
6712}
6713
6714fn artifact_has_cargo_extra_filename(
6715    artifact: &CargoCompilerArtifact,
6716    crate_name: &str,
6717    cargo_extra_filename: &str,
6718) -> bool {
6719    artifact.filenames.iter().any(|path| {
6720        artifact_filename_has_cargo_extra_filename(path, crate_name, cargo_extra_filename)
6721    }) || artifact.executable.as_ref().is_some_and(|path| {
6722        artifact_filename_has_cargo_extra_filename(path, crate_name, cargo_extra_filename)
6723    })
6724}
6725
6726fn artifact_filename_has_cargo_extra_filename(
6727    path: &Path,
6728    crate_name: &str,
6729    cargo_extra_filename: &str,
6730) -> bool {
6731    let Some(filename) = path.file_name().and_then(OsStr::to_str) else {
6732        return false;
6733    };
6734    [crate_name.to_string(), format!("lib{crate_name}")]
6735        .into_iter()
6736        .any(|prefix| {
6737            filename.strip_prefix(&prefix).is_some_and(|remainder| {
6738                remainder == cargo_extra_filename
6739                    || remainder
6740                        .strip_prefix(cargo_extra_filename)
6741                        .is_some_and(|extension| extension.starts_with('.'))
6742            })
6743        })
6744}
6745
6746fn artifact_has_unhashed_primary_output(
6747    artifact: &CargoCompilerArtifact,
6748    crate_name: &str,
6749) -> bool {
6750    artifact
6751        .filenames
6752        .iter()
6753        .any(|path| artifact_filename_is_unhashed_primary_output(path, crate_name))
6754        || artifact.executable.as_ref().is_some_and(|path| {
6755            artifact.filenames.contains(path)
6756                && artifact_filename_is_unhashed_primary_output(path, crate_name)
6757        })
6758}
6759
6760fn artifact_filename_is_unhashed_primary_output(path: &Path, crate_name: &str) -> bool {
6761    let Some(filename) = path.file_name().and_then(OsStr::to_str) else {
6762        return false;
6763    };
6764    let normalized = normalize_cargo_crate_name(filename);
6765    normalized == crate_name
6766        || normalized
6767            .strip_prefix(crate_name)
6768            .is_some_and(|extension| extension.starts_with('.'))
6769        || normalized.strip_prefix("lib").is_some_and(|library| {
6770            library == crate_name
6771                || library
6772                    .strip_prefix(crate_name)
6773                    .is_some_and(|extension| extension.starts_with('.'))
6774        })
6775}
6776
6777/// Build one root-specific external link manifest from exact Cargo messages,
6778/// wrapper sidecars, and descriptor objects.
6779pub(crate) fn build_link_unit_manifest(
6780    invocation: InvocationId,
6781    root_unit: DescriptorCargoUnitId,
6782    root_artifact: &Path,
6783    root_role: ArtifactRole,
6784    output: &DescriptorCargoOutput,
6785) -> Result<LinkUnitManifest, LinkManifestAssemblyError> {
6786    let topology = prepare_link_manifest(root_unit, root_artifact, root_role, output)?;
6787    let mut hasher = FilesystemLinkManifestHasher::new(root_artifact, &topology)?;
6788    assemble_link_unit_manifest(
6789        invocation,
6790        root_unit,
6791        root_artifact,
6792        root_role,
6793        &topology,
6794        &mut hasher,
6795    )
6796}
6797
6798trait LinkManifestHasher {
6799    fn hash_single(&mut self, path: &Path, domain: &[u8]) -> io::Result<[u8; 32]>;
6800
6801    fn hash_dependency(&mut self, path: &Path) -> io::Result<([u8; 32], [u8; 32])>;
6802}
6803
6804struct FilesystemLinkManifestHasher {
6805    hashes: BTreeMap<PathBuf, ([u8; 32], [u8; 32])>,
6806}
6807
6808impl FilesystemLinkManifestHasher {
6809    fn new(
6810        root_artifact: &Path,
6811        topology: &PreparedLinkManifest<'_>,
6812    ) -> Result<Self, LinkManifestAssemblyError> {
6813        let mut paths = BTreeSet::from([root_artifact.to_path_buf()]);
6814        for unit in &topology.reachable {
6815            let descriptor = topology
6816                .unit_by_id
6817                .get(unit)
6818                .expect("prepared reachable units have descriptor records");
6819            paths.insert(descriptor.descriptor_object.clone());
6820            paths.extend(
6821                topology
6822                    .dependencies_by_unit
6823                    .get(unit)
6824                    .expect("prepared reachable units have dependency records")
6825                    .iter()
6826                    .map(|dependency| dependency.path.clone()),
6827            );
6828        }
6829        let paths = paths.into_iter().collect::<Vec<_>>();
6830        let hashed = paths
6831            .par_iter()
6832            .map(|path| {
6833                (
6834                    path.clone(),
6835                    hash_file_two_domains(path, FILE_HASH_DOMAIN, LINK_ARTIFACT_HASH_DOMAIN),
6836                )
6837            })
6838            .collect::<Vec<_>>();
6839        let mut hashes = BTreeMap::new();
6840        for (path, result) in hashed {
6841            let hash = result.map_err(|source| LinkManifestAssemblyError::HashArtifact {
6842                path: path.clone(),
6843                source,
6844            })?;
6845            hashes.insert(path, hash);
6846        }
6847        Ok(Self { hashes })
6848    }
6849
6850    fn hashes(&self, path: &Path) -> io::Result<([u8; 32], [u8; 32])> {
6851        self.hashes.get(path).copied().ok_or_else(|| {
6852            io::Error::new(
6853                io::ErrorKind::InvalidInput,
6854                format!(
6855                    "link manifest requested an unplanned artifact `{}`",
6856                    path.display()
6857                ),
6858            )
6859        })
6860    }
6861}
6862
6863impl LinkManifestHasher for FilesystemLinkManifestHasher {
6864    fn hash_single(&mut self, path: &Path, domain: &[u8]) -> io::Result<[u8; 32]> {
6865        let (input, link) = self.hashes(path)?;
6866        if domain == FILE_HASH_DOMAIN {
6867            Ok(input)
6868        } else if domain == LINK_ARTIFACT_HASH_DOMAIN {
6869            Ok(link)
6870        } else {
6871            Err(io::Error::new(
6872                io::ErrorKind::InvalidInput,
6873                "link manifest requested an unsupported hash domain",
6874            ))
6875        }
6876    }
6877
6878    fn hash_dependency(&mut self, path: &Path) -> io::Result<([u8; 32], [u8; 32])> {
6879        self.hashes(path)
6880    }
6881}
6882
6883#[derive(Clone)]
6884struct RealizedLinkDependency {
6885    to: DescriptorCargoUnitId,
6886    extern_name: String,
6887    path: PathBuf,
6888    role: ArtifactRole,
6889    expected_input_hash: String,
6890}
6891
6892struct PreparedLinkManifest<'a> {
6893    unit_by_id: BTreeMap<DescriptorCargoUnitId, &'a ValidatedDescriptorUnit>,
6894    dependencies_by_unit: BTreeMap<DescriptorCargoUnitId, Vec<RealizedLinkDependency>>,
6895    reachable: BTreeSet<DescriptorCargoUnitId>,
6896}
6897
6898#[cfg(test)]
6899fn build_link_unit_manifest_with_hasher(
6900    invocation: InvocationId,
6901    root_unit: DescriptorCargoUnitId,
6902    root_artifact: &Path,
6903    root_role: ArtifactRole,
6904    output: &DescriptorCargoOutput,
6905    hasher: &mut impl LinkManifestHasher,
6906) -> Result<LinkUnitManifest, LinkManifestAssemblyError> {
6907    let topology = prepare_link_manifest(root_unit, root_artifact, root_role, output)?;
6908    assemble_link_unit_manifest(
6909        invocation,
6910        root_unit,
6911        root_artifact,
6912        root_role,
6913        &topology,
6914        hasher,
6915    )
6916}
6917
6918fn prepare_link_manifest<'a>(
6919    root_unit: DescriptorCargoUnitId,
6920    root_artifact: &Path,
6921    root_role: ArtifactRole,
6922    output: &'a DescriptorCargoOutput,
6923) -> Result<PreparedLinkManifest<'a>, LinkManifestAssemblyError> {
6924    if !root_role.is_root() {
6925        return Err(LinkManifestAssemblyError::NonRootRole(root_role));
6926    }
6927    if !root_artifact.is_absolute() {
6928        return Err(LinkManifestAssemblyError::RelativeRootArtifact(
6929            root_artifact.to_path_buf(),
6930        ));
6931    }
6932    let joined = join_cargo_enumerated_descriptor_units(&output.units, &output.cargo_artifacts)
6933        .map_err(LinkManifestAssemblyError::Join)?;
6934    let root_cargo_artifact = joined
6935        .get(&root_unit)
6936        .ok_or(LinkManifestAssemblyError::UnknownRootUnit(root_unit))?;
6937    let root_is_enumerated = root_cargo_artifact.filenames.contains(root_artifact)
6938        || root_cargo_artifact.executable.as_deref() == Some(root_artifact);
6939    if !root_is_enumerated {
6940        return Err(LinkManifestAssemblyError::RootArtifactNotEnumerated {
6941            unit: root_unit,
6942            path: root_artifact.to_path_buf(),
6943        });
6944    }
6945
6946    let unit_by_id = output
6947        .units
6948        .iter()
6949        .map(|unit| (unit.unit, unit))
6950        .collect::<BTreeMap<_, _>>();
6951    let mut artifact_by_path =
6952        BTreeMap::<PathBuf, Vec<(DescriptorCargoUnitId, ArtifactRole)>>::new();
6953    for (unit, artifact) in &joined {
6954        for path in &artifact.filenames {
6955            if !path.is_file() {
6956                return Err(LinkManifestAssemblyError::MissingCargoFilename(
6957                    path.clone(),
6958                ));
6959            }
6960            if let Some(role) = classify_dependency_artifact(artifact, path) {
6961                artifact_by_path
6962                    .entry(path.clone())
6963                    .or_default()
6964                    .push((*unit, role));
6965            }
6966        }
6967        if let Some(path) = &artifact.executable {
6968            if !artifact.filenames.contains(path) && path.is_file() {
6969                artifact_by_path
6970                    .entry(path.clone())
6971                    .or_default()
6972                    .push((*unit, ArtifactRole::RootExecutable));
6973            }
6974        }
6975        if let Some(path) = uplifted_root_lib_hashed_rlib(artifact) {
6976            artifact_by_path
6977                .entry(path)
6978                .or_default()
6979                .push((*unit, ArtifactRole::RustLibrary));
6980        }
6981    }
6982    for candidates in artifact_by_path.values_mut() {
6983        candidates.sort_by(|left, right| {
6984            left.0
6985                .as_bytes()
6986                .cmp(right.0.as_bytes())
6987                .then_with(|| left.1.cmp(&right.1))
6988        });
6989        candidates.dedup();
6990    }
6991
6992    let mut dependencies_by_unit =
6993        BTreeMap::<DescriptorCargoUnitId, Vec<RealizedLinkDependency>>::new();
6994    for unit in &output.units {
6995        let mut dependencies = Vec::new();
6996        for (extern_name, dependency) in &unit.sidecar.dependency_artifacts {
6997            let candidates = artifact_by_path.get(&dependency.path).ok_or_else(|| {
6998                LinkManifestAssemblyError::UnresolvedDependencyArtifact {
6999                    unit: unit.unit,
7000                    extern_name: extern_name.clone(),
7001                    path: dependency.path.clone(),
7002                    artifact_hash: dependency.content_hash.clone(),
7003                }
7004            })?;
7005            let (to, role) = match candidates.as_slice() {
7006                [(to, role)] => (*to, *role),
7007                _ => {
7008                    return Err(LinkManifestAssemblyError::AmbiguousDependencyArtifact {
7009                        unit: unit.unit,
7010                        extern_name: extern_name.clone(),
7011                        path: dependency.path.clone(),
7012                        artifact_hash: dependency.content_hash.clone(),
7013                        matches: candidates.len(),
7014                    });
7015                }
7016            };
7017            if to == unit.unit {
7018                return Err(LinkManifestAssemblyError::SelfDependency {
7019                    unit: unit.unit,
7020                    extern_name: extern_name.clone(),
7021                });
7022            }
7023            dependencies.push(RealizedLinkDependency {
7024                to,
7025                extern_name: extern_name.clone(),
7026                path: dependency.path.clone(),
7027                role,
7028                expected_input_hash: dependency.content_hash.clone(),
7029            });
7030        }
7031        dependencies.sort_by(|left, right| {
7032            left.extern_name
7033                .cmp(&right.extern_name)
7034                .then_with(|| left.to.as_bytes().cmp(right.to.as_bytes()))
7035        });
7036        dependencies_by_unit.insert(unit.unit, dependencies);
7037    }
7038
7039    let mut reachable = BTreeSet::new();
7040    let mut pending = vec![root_unit];
7041    while let Some(unit) = pending.pop() {
7042        if !reachable.insert(unit) {
7043            continue;
7044        }
7045        let dependencies = dependencies_by_unit
7046            .get(&unit)
7047            .ok_or(LinkManifestAssemblyError::UnknownReachableUnit(unit))?;
7048        for dependency in dependencies.iter().rev() {
7049            pending.push(dependency.to);
7050        }
7051    }
7052
7053    Ok(PreparedLinkManifest {
7054        unit_by_id,
7055        dependencies_by_unit,
7056        reachable,
7057    })
7058}
7059
7060fn assemble_link_unit_manifest(
7061    invocation: InvocationId,
7062    root_unit: DescriptorCargoUnitId,
7063    root_artifact: &Path,
7064    root_role: ArtifactRole,
7065    topology: &PreparedLinkManifest<'_>,
7066    hasher: &mut impl LinkManifestHasher,
7067) -> Result<LinkUnitManifest, LinkManifestAssemblyError> {
7068    let PreparedLinkManifest {
7069        unit_by_id,
7070        dependencies_by_unit,
7071        reachable,
7072    } = topology;
7073
7074    let mut artifacts = Vec::new();
7075    let mut dependency_edges = BTreeSet::new();
7076    let mut included_dependency_artifacts =
7077        BTreeSet::<(DescriptorCargoUnitId, ArtifactRole, SemanticHash)>::new();
7078    let mut dependency_content = BTreeMap::<PathBuf, ([u8; 32], SemanticHash)>::new();
7079    for unit in reachable {
7080        let descriptor = unit_by_id
7081            .get(unit)
7082            .ok_or(LinkManifestAssemblyError::UnknownReachableUnit(*unit))?;
7083        let object_hash = hasher
7084            .hash_single(&descriptor.descriptor_object, LINK_ARTIFACT_HASH_DOMAIN)
7085            .map_err(|source| LinkManifestAssemblyError::HashArtifact {
7086                path: descriptor.descriptor_object.clone(),
7087                source,
7088            })?;
7089        artifacts.push(LinkArtifact {
7090            unit: unit.as_abi_id(),
7091            role: ArtifactRole::DescriptorObject,
7092            content: SemanticHash::from_bytes(object_hash),
7093            path: descriptor.descriptor_object.to_string_lossy().into_owned(),
7094        });
7095
7096        for dependency in dependencies_by_unit
7097            .get(unit)
7098            .expect("reachable units were validated")
7099        {
7100            if !reachable.contains(&dependency.to) {
7101                return Err(LinkManifestAssemblyError::ReachabilityInvariant {
7102                    from: *unit,
7103                    to: dependency.to,
7104                });
7105            }
7106            dependency_edges.insert(LinkUnitDependency {
7107                from: unit.as_abi_id(),
7108                to: dependency.to.as_abi_id(),
7109                extern_name: dependency.extern_name.clone(),
7110            });
7111            let (input_hash, content) = match dependency_content.get(&dependency.path) {
7112                Some(content) => *content,
7113                None => {
7114                    let (input_hash, link_hash) = hasher
7115                        .hash_dependency(&dependency.path)
7116                        .map_err(|source| LinkManifestAssemblyError::HashArtifact {
7117                            path: dependency.path.clone(),
7118                            source,
7119                        })?;
7120                    let content = (input_hash, SemanticHash::from_bytes(link_hash));
7121                    dependency_content.insert(dependency.path.clone(), content);
7122                    content
7123                }
7124            };
7125            let actual_input_hash = hex_digest(&input_hash);
7126            if actual_input_hash != dependency.expected_input_hash {
7127                return Err(LinkManifestAssemblyError::DependencyArtifactHashMismatch {
7128                    unit: *unit,
7129                    extern_name: dependency.extern_name.clone(),
7130                    path: dependency.path.clone(),
7131                    expected: dependency.expected_input_hash.clone(),
7132                    actual: actual_input_hash,
7133                });
7134            }
7135            if included_dependency_artifacts.insert((dependency.to, dependency.role, content)) {
7136                artifacts.push(LinkArtifact {
7137                    unit: dependency.to.as_abi_id(),
7138                    role: dependency.role,
7139                    content,
7140                    path: dependency.path.to_string_lossy().into_owned(),
7141                });
7142            }
7143        }
7144    }
7145
7146    let root_content = hasher
7147        .hash_single(root_artifact, LINK_ARTIFACT_HASH_DOMAIN)
7148        .map_err(|source| LinkManifestAssemblyError::HashArtifact {
7149            path: root_artifact.to_path_buf(),
7150            source,
7151        })?;
7152    artifacts.push(LinkArtifact {
7153        unit: root_unit.as_abi_id(),
7154        role: root_role,
7155        content: SemanticHash::from_bytes(root_content),
7156        path: root_artifact.to_string_lossy().into_owned(),
7157    });
7158    artifacts.sort_by(|left, right| {
7159        left.unit
7160            .as_bytes()
7161            .cmp(right.unit.as_bytes())
7162            .then_with(|| left.role.cmp(&right.role))
7163            .then_with(|| left.content.as_bytes().cmp(right.content.as_bytes()))
7164    });
7165
7166    let manifest = LinkUnitManifest {
7167        invocation,
7168        root_unit: root_unit.as_abi_id(),
7169        artifacts,
7170        dependencies: dependency_edges,
7171    };
7172    manifest
7173        .validate()
7174        .map_err(LinkManifestAssemblyError::InvalidManifest)?;
7175    Ok(manifest)
7176}
7177
7178/// Cargo reports a root package's lib artifact at its uplifted destination
7179/// (`target/debug/libX.rlib`) plus the hashed `deps/libX-<hash>.rmeta`, while
7180/// same-package dependents are compiled against the hashed
7181/// `deps/libX-<hash>.rlib` that the message never lists. Derive that hashed
7182/// rlib from the message's own hashed rmeta filename; both names come from one
7183/// compiler-artifact message, so the pairing cannot cross units.
7184pub(crate) fn uplifted_root_lib_hashed_rlib(artifact: &CargoCompilerArtifact) -> Option<PathBuf> {
7185    if !artifact.target.crate_types.contains("lib") {
7186        return None;
7187    }
7188    let crate_name = normalize_cargo_crate_name(&artifact.target.name);
7189    let uplifted = format!("lib{crate_name}.rlib");
7190    artifact
7191        .filenames
7192        .iter()
7193        .find(|path| path.file_name().and_then(OsStr::to_str) == Some(uplifted.as_str()))?;
7194    let hashed_prefix = format!("lib{crate_name}-");
7195    let rmeta = artifact.filenames.iter().find(|path| {
7196        path.file_name()
7197            .and_then(OsStr::to_str)
7198            .is_some_and(|name| name.starts_with(&hashed_prefix) && name.ends_with(".rmeta"))
7199    })?;
7200    let hashed_rlib = format!(
7201        "{}.rlib",
7202        rmeta.file_name()?.to_str()?.strip_suffix(".rmeta")?
7203    );
7204    let candidate = rmeta.parent()?.join(hashed_rlib);
7205    candidate.is_file().then_some(candidate)
7206}
7207
7208pub(crate) fn classify_dependency_artifact(
7209    artifact: &CargoCompilerArtifact,
7210    path: &Path,
7211) -> Option<ArtifactRole> {
7212    if artifact.target.kind.contains("proc-macro") {
7213        return Some(ArtifactRole::ProcMacro);
7214    }
7215    match path.extension().and_then(OsStr::to_str) {
7216        Some("rlib") => Some(ArtifactRole::RustLibrary),
7217        Some("rmeta") => Some(ArtifactRole::RustMetadata),
7218        Some("a") | Some("lib") => Some(ArtifactRole::StaticLibrary),
7219        Some("so") | Some("dylib") | Some("dll") => Some(ArtifactRole::DynamicLibrary),
7220        Some("o") | Some("obj") => Some(ArtifactRole::Object),
7221        _ => None,
7222    }
7223}
7224
7225/// Failure while constructing one root's exact external link manifest.
7226#[derive(Debug, Error)]
7227pub enum LinkManifestAssemblyError {
7228    /// Caller supplied a dependency role for the selected root.
7229    #[error("artifact role {0:?} is not a root role")]
7230    NonRootRole(ArtifactRole),
7231    /// Root path must come directly from Cargo.
7232    #[error("root artifact path must be absolute: `{0}`")]
7233    RelativeRootArtifact(PathBuf),
7234    /// Sidecar/Cargo freshness join failed.
7235    #[error(transparent)]
7236    Join(UnitArtifactJoinError),
7237    /// Root unit was not part of the joined invocation.
7238    #[error("selected root Cargo unit {0} was not produced by this descriptor invocation")]
7239    UnknownRootUnit(DescriptorCargoUnitId),
7240    /// Root path was not in that unit's Cargo message.
7241    #[error("root artifact `{path}` was not enumerated for Cargo unit {unit}")]
7242    RootArtifactNotEnumerated {
7243        /// Selected unit.
7244        unit: DescriptorCargoUnitId,
7245        /// Exact path.
7246        path: PathBuf,
7247    },
7248    /// Cargo advertised a missing file.
7249    #[error("Cargo-enumerated artifact is missing: `{0}`")]
7250    MissingCargoFilename(PathBuf),
7251    /// Exact artifact hashing failed.
7252    #[error("failed to hash link artifact `{path}`: {source}")]
7253    HashArtifact {
7254        /// Exact path.
7255        path: PathBuf,
7256        /// I/O failure.
7257        #[source]
7258        source: io::Error,
7259    },
7260    /// An extern input did not correspond to a sidecar-backed Cargo artifact.
7261    #[error(
7262        "descriptor unit {unit} extern `{extern_name}` references Cargo-unenumerated artifact `{path}` with hash `{artifact_hash}`"
7263    )]
7264    UnresolvedDependencyArtifact {
7265        /// Consumer.
7266        unit: DescriptorCargoUnitId,
7267        /// Rust extern name.
7268        extern_name: String,
7269        /// Exact path passed to rustc.
7270        path: PathBuf,
7271        /// Wrapper input hash.
7272        artifact_hash: String,
7273    },
7274    /// An exact dependency path was enumerated by multiple units.
7275    #[error(
7276        "descriptor unit {unit} extern `{extern_name}` artifact `{path}` with hash `{artifact_hash}` matches {matches} Cargo units"
7277    )]
7278    AmbiguousDependencyArtifact {
7279        /// Consumer.
7280        unit: DescriptorCargoUnitId,
7281        /// Rust extern name.
7282        extern_name: String,
7283        /// Exact path passed to rustc.
7284        path: PathBuf,
7285        /// Wrapper input hash.
7286        artifact_hash: String,
7287        /// Candidate count.
7288        matches: usize,
7289    },
7290    /// A Cargo-enumerated extern changed after the wrapper captured its input.
7291    #[error(
7292        "descriptor unit {unit} extern `{extern_name}` artifact `{path}` changed after descriptor input capture: expected hash `{expected}`, found `{actual}`"
7293    )]
7294    DependencyArtifactHashMismatch {
7295        /// Consumer.
7296        unit: DescriptorCargoUnitId,
7297        /// Rust extern name.
7298        extern_name: String,
7299        /// Exact Cargo-enumerated path.
7300        path: PathBuf,
7301        /// Wrapper-time descriptor-domain hash.
7302        expected: String,
7303        /// Assembly-time descriptor-domain hash.
7304        actual: String,
7305    },
7306    /// Cargo graph must not self-reference.
7307    #[error("descriptor unit {unit} extern `{extern_name}` resolves to itself")]
7308    SelfDependency {
7309        /// Consumer.
7310        unit: DescriptorCargoUnitId,
7311        /// Rust extern name.
7312        extern_name: String,
7313    },
7314    /// Reached an ID with no wrapper sidecar.
7315    #[error("descriptor root graph reaches unknown Cargo unit {0}")]
7316    UnknownReachableUnit(DescriptorCargoUnitId),
7317    /// Internal closure bug.
7318    #[error("descriptor reachability omitted dependency {from} -> {to}")]
7319    ReachabilityInvariant {
7320        /// Consumer.
7321        from: DescriptorCargoUnitId,
7322        /// Dependency.
7323        to: DescriptorCargoUnitId,
7324    },
7325    /// Canonical manifest validation failed.
7326    #[error("assembled link-unit manifest is invalid: {0}")]
7327    InvalidManifest(rsjs_ir::build::BuildIdentityError),
7328}
7329
7330/// Freshness-join failure between wrapper sidecars and Cargo JSON.
7331#[derive(Debug, Error)]
7332pub enum UnitArtifactJoinError {
7333    /// Direct rustc invocation lacks Cargo provenance and cannot enter a root
7334    /// manifest.
7335    #[error("descriptor unit {0} has no Cargo manifest provenance")]
7336    MissingCargoManifest(DescriptorCargoUnitId),
7337    /// Cargo manifest provenance must be absolute.
7338    #[error("descriptor unit {unit} reports relative Cargo manifest `{path}`")]
7339    RelativeCargoManifest {
7340        /// Unit being joined.
7341        unit: DescriptorCargoUnitId,
7342        /// Invalid path.
7343        path: PathBuf,
7344    },
7345    /// Sidecar normalization failed closed.
7346    #[error("descriptor unit {0} repeats a crate type")]
7347    DuplicateCrateType(DescriptorCargoUnitId),
7348    /// Sidecar normalization failed closed.
7349    #[error("descriptor unit {0} repeats a Cargo feature")]
7350    DuplicateFeature(DescriptorCargoUnitId),
7351    /// Output discriminators are exact filename fragments, never paths.
7352    #[error("descriptor unit {unit} has invalid Cargo extra-filename `{value}`: {reason}")]
7353    InvalidCargoExtraFilename {
7354        /// Unit being joined.
7355        unit: DescriptorCargoUnitId,
7356        /// Rejected discriminator.
7357        value: String,
7358        /// Validation detail.
7359        reason: String,
7360    },
7361    /// Cargo source bytes could not be validated.
7362    #[error("failed to hash Cargo source `{path}` while joining descriptor units: {source}")]
7363    HashCargoSource {
7364        /// Exact Cargo source path.
7365        path: PathBuf,
7366        /// I/O failure.
7367        #[source]
7368        source: io::Error,
7369    },
7370    /// No Cargo message describes this exact unit.
7371    #[error("no Cargo compiler-artifact matches descriptor unit {0}")]
7372    MissingArtifact(DescriptorCargoUnitId),
7373    /// More than one Cargo message could authorize this unit.
7374    #[error("descriptor unit {unit} ambiguously matches {matches} Cargo compiler-artifacts")]
7375    AmbiguousArtifact {
7376        /// Unit being joined.
7377        unit: DescriptorCargoUnitId,
7378        /// Candidate count.
7379        matches: usize,
7380    },
7381    /// One Cargo message cannot authorize two wrapper units.
7382    #[error("Cargo compiler-artifact `{path}` was claimed by multiple descriptor units")]
7383    ArtifactClaimedTwice {
7384        /// Representative exact filename.
7385        path: PathBuf,
7386    },
7387}
7388
7389/// Hidden rustc-wrapper failure.
7390#[derive(Debug, Error)]
7391pub enum WrapperError {
7392    /// Required wrapper configuration is missing.
7393    #[error("missing required RSJS wrapper environment variable `{0}`")]
7394    MissingEnvironment(&'static str),
7395    /// Process environment names must be deterministic UTF-8 hash inputs.
7396    #[error("RSJS wrapper environment contains a non-UTF-8 variable name: {0:?}")]
7397    NonUtf8EnvironmentName(OsString),
7398    /// Process environment values must be deterministic UTF-8 hash inputs.
7399    #[error("RSJS wrapper environment variable `{name}` has a non-UTF-8 value: {value:?}")]
7400    NonUtf8EnvironmentValue {
7401        /// Variable name.
7402        name: String,
7403        /// Rejected value.
7404        value: OsString,
7405    },
7406    /// A future/unknown wrapper protocol was requested.
7407    #[error("unsupported RSJS rustc-wrapper mode `{0}`")]
7408    UnsupportedWrapperMode(String),
7409    /// Relative staging paths would depend on Cargo's invocation cwd.
7410    #[error("descriptor staging directory must be absolute: `{0}`")]
7411    RelativeStagingDirectory(PathBuf),
7412    /// Descriptor source-closure exclusion must name the exact Cargo target.
7413    #[error("descriptor target directory must be absolute: `{0}`")]
7414    RelativeDescriptorTargetDirectory(PathBuf),
7415    /// Package source exclusion must use one exact absolute generated root.
7416    #[error("descriptor source exclusion directory must be absolute: `{0}`")]
7417    RelativeSourceExclusionDirectory(PathBuf),
7418    /// Package closure identity requires one absolute Cargo package root.
7419    #[error("Cargo manifest directory must be absolute: `{0}`")]
7420    RelativeCargoManifestDirectory(PathBuf),
7421    /// Final maps are resolved before Cargo starts and must be exact.
7422    #[error("final unit-map path must be absolute: `{0}`")]
7423    RelativeFinalUnitMap(PathBuf),
7424    /// Final target confinement begins at one exact absolute runner path.
7425    #[error("final Cargo target must be absolute: `{0}`")]
7426    RelativeFinalTarget(PathBuf),
7427    /// The runner-owned final target must remain a plain directory.
7428    #[error("unsafe final Cargo target `{0}`")]
7429    UnsafeFinalTarget(PathBuf),
7430    /// Cargo OUT_DIR must be a strict lexical descendant of the final target.
7431    #[error("Cargo OUT_DIR `{out_dir}` is outside final target `{target}`")]
7432    OutDirOutsideFinalTarget {
7433        /// Cargo-provided build output directory.
7434        out_dir: PathBuf,
7435        /// Exact invocation- and wrapper-policy-scoped final target.
7436        target: PathBuf,
7437    },
7438    /// Proc macros consume one exact content-addressed final plan.
7439    #[error("final link-plan path must be absolute: `{0}`")]
7440    RelativeFinalPlan(PathBuf),
7441    /// Final mode must be explicitly authorized by the orchestrator.
7442    #[error("RSJS final wrapper requires `RSJS_FINAL_PHASE=1`")]
7443    InvalidFinalPhase,
7444    /// Hash inputs use one exact lowercase encoding.
7445    #[error("invalid SHA-256 in `{name}` (`{value}`): {reason}")]
7446    InvalidSha256 {
7447        /// Environment or field name.
7448        name: &'static str,
7449        /// Rejected value.
7450        value: String,
7451        /// Validation detail.
7452        reason: String,
7453    },
7454    /// Cargo's rustc output discriminator must be one safe filename fragment.
7455    #[error("invalid Cargo extra-filename in {context} (`{value}`): {reason}")]
7456    InvalidCargoExtraFilename {
7457        /// Validation boundary.
7458        context: &'static str,
7459        /// Rejected discriminator.
7460        value: String,
7461        /// Validation detail.
7462        reason: String,
7463    },
7464    /// Content-addressed filename did not match the expected hash.
7465    #[error("final unit map `{path}` must be named `{expected}`")]
7466    FinalUnitMapFilename {
7467        /// Exact path.
7468        path: PathBuf,
7469        /// Expected filename.
7470        expected: String,
7471    },
7472    /// Map bytes could not be read.
7473    #[error("failed to read final unit map `{path}`: {source}")]
7474    ReadFinalUnitMap {
7475        /// Exact path.
7476        path: PathBuf,
7477        /// I/O failure.
7478        #[source]
7479        source: io::Error,
7480    },
7481    /// Content-addressed map bytes changed.
7482    #[error("final unit map `{path}` has SHA-256 `{actual}`; expected `{expected}`")]
7483    FinalUnitMapHashMismatch {
7484        /// Exact path.
7485        path: PathBuf,
7486        /// Required digest.
7487        expected: String,
7488        /// Actual digest.
7489        actual: String,
7490    },
7491    /// Map JSON was malformed.
7492    #[error("failed to parse final unit map `{path}`: {source}")]
7493    ParseFinalUnitMap {
7494        /// Exact path.
7495        path: PathBuf,
7496        /// JSON failure.
7497        #[source]
7498        source: serde_json::Error,
7499    },
7500    /// Wrong external map format.
7501    #[error("unsupported final unit-map format `{0}`")]
7502    FinalUnitMapFormat(String),
7503    /// Wrong map schema.
7504    #[error("final unit-map schema {actual} is unsupported; expected {expected}")]
7505    FinalUnitMapSchema {
7506        /// Actual version.
7507        actual: u16,
7508        /// Required version.
7509        expected: u16,
7510    },
7511    /// Map and final compilation named different plans.
7512    #[error("final unit-map plan ID mismatch: expected `{expected}`, found `{actual}`")]
7513    FinalUnitMapPlanId {
7514        /// Environment plan.
7515        expected: String,
7516        /// Map plan.
7517        actual: String,
7518    },
7519    /// Map and final compilation named different exact plan files.
7520    #[error(
7521        "final unit-map linked-plan SHA-256 mismatch: expected `{expected}`, found `{actual}`"
7522    )]
7523    FinalUnitMapPlanFileHash {
7524        /// Environment hash.
7525        expected: String,
7526        /// Map hash.
7527        actual: String,
7528    },
7529    /// Serialized entries must be strictly coordinate-sorted.
7530    #[error("final unit-map entries are not in strict canonical coordinate order")]
7531    NonCanonicalFinalUnitMap,
7532    /// Deserialized coordinate must remain phase invariant.
7533    #[error("final unit-map coordinate has relative manifest path `{0}`")]
7534    RelativeMappedManifest(PathBuf),
7535    /// Set-valued coordinate field was duplicated or unsorted.
7536    #[error("final unit-map coordinate has non-canonical `{0}` values")]
7537    NonCanonicalFinalCoordinate(&'static str),
7538    /// Optional profile names cannot use an empty sentinel.
7539    #[error("final unit-map coordinate contains an empty Cargo profile")]
7540    EmptyFinalProfile,
7541    /// Descriptor coordinates cannot contain final cfgs.
7542    #[error("final unit-map descriptor coordinate contains a final-plan cfg")]
7543    FinalCoordinateContainsPlanCfg,
7544    /// Map feature list disagreed with its cfgs.
7545    #[error("final unit-map coordinate feature list disagrees with its cfgs")]
7546    FinalCoordinateFeatureMismatch,
7547    /// Two entries would let wrapper order choose identity.
7548    #[error(
7549        "final coordinate {coordinate:?} ambiguously maps to Cargo units {first} and {second}"
7550    )]
7551    AmbiguousFinalUnitCoordinate {
7552        /// Ambiguous coordinate.
7553        coordinate: FinalUnitCoordinate,
7554        /// First unit.
7555        first: String,
7556        /// Second unit.
7557        second: String,
7558    },
7559    /// Cargo-owned inputs may not contain a wrapper-owned final cfg.
7560    #[error("Cargo's rustc invocation contains reserved plan cfg `{0}` before wrapper injection")]
7561    UnexpectedFinalPlanCfg(String),
7562    /// Cargo did not provide the real rustc executable as `argv[1]`.
7563    #[error("Cargo's rustc-wrapper invocation did not include the rustc executable")]
7564    MissingRustcProgram,
7565    /// Cargo silently composes a configured workspace wrapper inside Proa's
7566    /// wrapper. That extra program is not part of descriptor/final identity.
7567    #[error(
7568        "Cargo composed unsupported `build.rustc-workspace-wrapper` program {wrapper:?} before rustc {rustc:?}; remove that Cargo setting before invoking cargo-proa"
7569    )]
7570    ComposedWorkspaceWrapper {
7571        /// Workspace wrapper inserted by Cargo.
7572        wrapper: OsString,
7573        /// Actual rustc program nested inside the workspace wrapper.
7574        rustc: OsString,
7575    },
7576    /// rustc could not be launched.
7577    #[error("failed to run rustc `{program}`: {source}")]
7578    SpawnRustc {
7579        /// Program supplied by Cargo.
7580        program: PathBuf,
7581        /// Process error.
7582        #[source]
7583        source: io::Error,
7584    },
7585    /// rustc version material could not be obtained.
7586    #[error("`{program} -vV` failed with {status}")]
7587    RustcIdentityFailed {
7588        /// Program supplied by Cargo.
7589        program: PathBuf,
7590        /// Failed exit status.
7591        status: ExitStatus,
7592    },
7593    /// rustc option lacks a required following value.
7594    #[error("rustc option `{0}` is missing its value")]
7595    MissingRustcOptionValue(&'static str),
7596    /// Cargo compilation must request one dep-info output for exact generated
7597    /// source auditing.
7598    #[error("Cargo's rustc invocation did not request `--emit=dep-info`")]
7599    MissingDepInfoOutput,
7600    /// Multiple dep-info destinations would make the audited source set
7601    /// order-dependent.
7602    #[error("Cargo's rustc invocation requested more than one dep-info output")]
7603    DuplicateDepInfoOutput,
7604    /// A default dep-info path cannot be inferred safely when rustc also owns
7605    /// a single explicit output path.
7606    #[error("Cargo's rustc invocation combines default dep-info with `-o`; an explicit dep-info path is required")]
7607    UnsupportedDefaultDepInfoWithOutput,
7608    /// The wrapper could not resolve a relative rustc output path.
7609    #[error("failed to resolve the rustc wrapper current directory: {0}")]
7610    CurrentDirectory(io::Error),
7611    /// Paths may be non-UTF-8, but rustc option spelling must be unambiguous.
7612    #[error("descriptor wrapper does not support this non-UTF-8 rustc argument: {0:?}")]
7613    NonUtf8RustcArgument(OsString),
7614    /// A future rustc option must be classified before entering unit identity.
7615    #[error("descriptor wrapper does not yet classify rustc option `{0}`")]
7616    UnsupportedRustcOption(String),
7617    /// Binary dependency dep-info would bind descriptor/final target-specific
7618    /// rlibs, metadata, and sysroot artifacts into the source protocol.
7619    #[error("`-Zbinary-dep-depinfo` is unsupported by the exact observed-input protocol")]
7620    UnsupportedBinaryDepDepInfo,
7621    /// rustc's logical environment injection is not yet modeled separately
7622    /// from the wrapper process environment.
7623    #[error("`--env-set` is unsupported by the exact observed-input protocol")]
7624    UnsupportedLogicalEnvironmentInjection,
7625    /// rustc remapping changes dep-info path spelling, so the strict v1
7626    /// generated-input audit cannot resolve those paths back to exact files.
7627    #[error("rustc path remapping option `{0}` is unsupported by the exact observed-input audit")]
7628    UnsupportedDepInfoPathRemapping(String),
7629    /// No `--crate-name` was present.
7630    #[error("descriptor rustc invocation has no `--crate-name`")]
7631    MissingCrateName,
7632    /// No crate type was present.
7633    #[error("descriptor rustc invocation has no `--crate-type`")]
7634    MissingCrateType,
7635    /// No source input was present.
7636    #[error("descriptor rustc invocation has no source input")]
7637    MissingRustcInput,
7638    /// More than one positional source was present.
7639    #[error("descriptor rustc invocation has multiple positional source inputs")]
7640    MultipleRustcInputs,
7641    /// `--extern` syntax is incomplete.
7642    #[error("malformed rustc `--extern` value `{0}`")]
7643    MalformedExtern(String),
7644    /// Two paths for the same extern name had different bytes.
7645    #[error("rustc invocation contains conflicting artifacts for extern `{0}`")]
7646    ConflictingExtern(String),
7647    /// Exact Cargo joins require the absolute path Cargo reports in JSON.
7648    #[error("rustc invocation contains relative extern artifact `{0}`")]
7649    RelativeExternArtifact(PathBuf),
7650    /// A source or exact dependency artifact could not be hashed.
7651    #[error("failed to hash exact descriptor input `{path}`: {source}")]
7652    HashInput {
7653        /// Exact input path.
7654        path: PathBuf,
7655        /// Read error.
7656        #[source]
7657        source: io::Error,
7658    },
7659    /// The conservative package-local source closure could not be hashed.
7660    #[error("failed to hash Cargo package source closure `{path}`: {source}")]
7661    HashPackageSourceClosure {
7662        /// Exact Cargo package root.
7663        path: PathBuf,
7664        /// Traversal or read error.
7665        #[source]
7666        source: io::Error,
7667    },
7668    /// Cargo build-script output directories must be absolute.
7669    #[error("Cargo OUT_DIR must be absolute: `{0}`")]
7670    RelativeOutDir(PathBuf),
7671    /// Relative dep-info bases would make cached source resolution depend on
7672    /// the caller process cwd.
7673    #[error("rustc dep-info working directory must be absolute: `{0}`")]
7674    RelativeDepInfoWorkingDirectory(PathBuf),
7675    /// The descriptor OUT_DIR must be owned by the exact descriptor target.
7676    #[error("Cargo OUT_DIR `{out_dir}` is outside descriptor target `{target}`")]
7677    OutDirOutsideDescriptorTarget {
7678        /// Cargo-provided build output directory.
7679        out_dir: PathBuf,
7680        /// Orchestrator-owned target directory.
7681        target: PathBuf,
7682    },
7683    /// rustc's exact dep-info could not be read.
7684    #[error("failed to read rustc dep-info `{path}`: {source}")]
7685    ReadDepInfo {
7686        /// Exact dep-info path.
7687        path: PathBuf,
7688        /// Read failure.
7689        #[source]
7690        source: io::Error,
7691    },
7692    /// A stale dep-info output could not be removed before rustc.
7693    #[error("failed to prepare rustc dep-info output `{path}`: {source}")]
7694    WriteDepInfo {
7695        /// Exact dep-info path.
7696        path: PathBuf,
7697        /// Filesystem failure.
7698        #[source]
7699        source: io::Error,
7700    },
7701    /// Dep-info paths must remain regular files owned by rustc.
7702    #[error("unsafe rustc dep-info output `{0}`")]
7703    UnsafeDepInfoOutput(PathBuf),
7704    /// rustc's dep-info encoding cannot represent this path without
7705    /// ambiguity (non-UTF-8, backslash, non-space whitespace, or trailing
7706    /// space on a file).
7707    #[error("path `{0}` cannot be represented unambiguously in rustc dep-info")]
7708    UnrepresentableDepInfoPath(PathBuf),
7709    /// The wrapper may remove only Cargo target-owned dep-info outputs.
7710    #[error("rustc dep-info output `{path}` is outside exact target `{target}`")]
7711    DepInfoOutsideTarget {
7712        /// Rejected dep-info path.
7713        path: PathBuf,
7714        /// Orchestrator-owned target.
7715        target: PathBuf,
7716    },
7717    /// rustc's dep-info was not canonical Makefile dependency syntax.
7718    #[error("malformed rustc dep-info `{path}`: {reason}")]
7719    MalformedDepInfo {
7720        /// Exact dep-info path.
7721        path: PathBuf,
7722        /// Parse detail.
7723        reason: String,
7724    },
7725    /// A generated source input could not be inspected or hashed.
7726    #[error("failed to inspect rustc-declared OUT_DIR dependency `{path}`: {source}")]
7727    ReadOutDirDependency {
7728        /// Exact generated input.
7729        path: PathBuf,
7730        /// Filesystem failure.
7731        #[source]
7732        source: io::Error,
7733    },
7734    /// Generated source inputs must be regular files beneath one exact OUT_DIR.
7735    #[error("unsafe rustc-declared OUT_DIR dependency `{0}`")]
7736    UnsafeOutDirDependency(PathBuf),
7737    /// One dep-info file cannot report conflicting bytes for the same portable
7738    /// generated-source path.
7739    #[error("conflicting rustc-declared OUT_DIR dependency `{0}`")]
7740    ConflictingOutDirDependency(String),
7741    /// OUT_DIR presence, its portable coordinate, and its live path must agree.
7742    #[error("inconsistent OUT_DIR state in observed-input metadata")]
7743    InconsistentObservedOutDir,
7744    /// A serialized OUT_DIR coordinate is not a portable relative path.
7745    #[error("invalid observed OUT_DIR coordinate: {0}")]
7746    InvalidObservedOutDirCoordinate(String),
7747    /// Serialized generated-source paths are strict portable relative paths.
7748    #[error("invalid OUT_DIR dependency path `{path}`: {reason}")]
7749    InvalidOutDirDependencyPath {
7750        /// Rejected path.
7751        path: String,
7752        /// Validation detail.
7753        reason: String,
7754    },
7755    /// Dependency records are sorted and unique so map order cannot select
7756    /// behavior.
7757    #[error("OUT_DIR dependency records are not strictly sorted and unique")]
7758    NonCanonicalOutDirDependencies,
7759    /// Non-OUT_DIR observed source paths must be canonical absolute paths.
7760    #[error("observed source dependency path must be absolute: `{0}`")]
7761    RelativeObservedSource(PathBuf),
7762    /// An observed source could not be inspected or hashed.
7763    #[error("failed to inspect rustc-declared source dependency `{path}`: {source}")]
7764    ReadObservedSource {
7765        /// Exact source path.
7766        path: PathBuf,
7767        /// Filesystem failure.
7768        #[source]
7769        source: io::Error,
7770    },
7771    /// Symlinks and special files are not stable exact source inputs.
7772    #[error("unsafe rustc-declared source dependency `{0}`")]
7773    UnsafeObservedSource(PathBuf),
7774    /// Canonical aliases cannot appear twice in one exact source set.
7775    #[error("conflicting rustc-declared source dependency `{0}`")]
7776    ConflictingObservedSource(PathBuf),
7777    /// Absolute source records are sorted and unique.
7778    #[error("observed source dependency records are not strictly sorted and unique")]
7779    NonCanonicalSourceDependencies,
7780    /// Live source bytes changed after descriptor observation.
7781    #[error("source file changed between RSJS compilation passes: `{path}`")]
7782    ObservedSourceHashMismatch {
7783        /// Exact source path.
7784        path: PathBuf,
7785        /// Descriptor-time hash.
7786        expected: String,
7787        /// Current hash.
7788        actual: String,
7789    },
7790    /// Environment records are sorted, unique, and cannot contain wrapper
7791    /// control names.
7792    #[error("observed environment dependency records are not strictly canonical")]
7793    NonCanonicalEnvironmentDependencies,
7794    /// Environment names must be nonempty and cannot be phase-owned controls.
7795    #[error("invalid observed environment dependency name `{name}`")]
7796    InvalidEnvironmentDependencyName {
7797        /// Rejected name. Values are never included.
7798        name: String,
7799    },
7800    /// One dep-info file declared the same environment variable twice.
7801    #[error("rustc dep-info repeats environment dependency `{name}`")]
7802    DuplicateEnvironmentDependency {
7803        /// Repeated name. Values are never included.
7804        name: String,
7805    },
7806    /// Current user/Cargo environment presence or value hash diverged.
7807    #[error("observed environment dependency `{name}` differs from descriptor compilation")]
7808    ObservedEnvironmentMismatch {
7809        /// Divergent name. Values are deliberately redacted.
7810        name: String,
7811    },
7812    /// A compiler-tracked wrapper control disagreed with the exact child
7813    /// environment. Its value remains redacted.
7814    #[error("phase-owned environment dependency `{name}` disagrees with the wrapper protocol")]
7815    PhaseOwnedEnvironmentMismatch {
7816        /// Divergent phase-owned name.
7817        name: String,
7818    },
7819    /// Phase-owned paths/IDs must be UTF-8 before rustc can report them in its
7820    /// UTF-8 dep-info protocol.
7821    #[error("phase-owned environment dependency `{0}` is not UTF-8")]
7822    NonUtf8PhaseOwnedEnvironment(&'static str),
7823    /// A mapped unit that consumed generated source requires Cargo's OUT_DIR.
7824    #[error("mapped final unit consumed OUT_DIR dependencies but final rustc has no OUT_DIR")]
7825    MissingOutDirForDependencies,
7826    /// Cached sidecars are validated before any generated path is joined.
7827    #[error("invalid cached OUT_DIR dependency metadata: {0}")]
7828    InvalidCachedOutDirDependencies(String),
7829    /// Current Cargo-authoritative dep-info no longer names the exact cached
7830    /// generation. Values remain redacted.
7831    #[error("cached observed inputs differ for descriptor unit {unit}")]
7832    CachedObservedInputsMismatch {
7833        /// Cached base unit.
7834        unit: DescriptorCargoUnitId,
7835    },
7836    /// Current generated source bytes diverged before final compilation.
7837    #[error("generated source changed between RSJS compilation passes: `{path}`")]
7838    OutDirDependencyHashMismatch {
7839        /// Exact final input path.
7840        path: PathBuf,
7841        /// Descriptor-time hash.
7842        expected: String,
7843        /// Current final hash.
7844        actual: String,
7845    },
7846    /// Final rustc observed a different generated-source set than descriptor
7847    /// rustc. This intentionally rejects final-only includes in v1.
7848    #[error("final rustc OUT_DIR dependency set differs from descriptor compilation (expected {expected:?}, observed {actual:?})")]
7849    FinalOutDirDependencySetMismatch {
7850        /// Descriptor-time exact set.
7851        expected: Vec<DescriptorOutDirDependency>,
7852        /// Final rustc exact set.
7853        actual: Vec<DescriptorOutDirDependency>,
7854    },
7855    /// Final rustc observed another exact non-OUT_DIR source set.
7856    #[error("final rustc source dependency set differs from descriptor compilation (expected {expected:?}, observed {actual:?})")]
7857    FinalSourceDependencySetMismatch {
7858        /// Descriptor-time exact set.
7859        expected: Vec<DescriptorSourceDependency>,
7860        /// Final rustc exact set.
7861        actual: Vec<DescriptorSourceDependency>,
7862    },
7863    /// Final rustc observed another redacted environment set.
7864    #[error("final rustc environment dependency set differs from descriptor compilation (expected {expected:?}, observed {actual:?})")]
7865    FinalEnvironmentDependencySetMismatch {
7866        /// Descriptor-time redacted set.
7867        expected: Vec<DescriptorEnvironmentDependency>,
7868        /// Final rustc redacted set.
7869        actual: Vec<DescriptorEnvironmentDependency>,
7870    },
7871    /// Cargo's build-script output declares the arbitrary rustc-env names.
7872    #[error(
7873        "failed to read Cargo build-script rustc-env declarations for OUT_DIR {out_dir:?}: {source}"
7874    )]
7875    ReadBuildScriptEnvironment {
7876        /// Cargo-provided output directory, when one was present.
7877        out_dir: Option<PathBuf>,
7878        /// Missing/malformed build-script output.
7879        #[source]
7880        source: io::Error,
7881    },
7882    /// Staging directory creation failed.
7883    #[error("failed to create descriptor staging directory `{path}`: {source}")]
7884    CreateStagingDirectory {
7885        /// Directory path.
7886        path: PathBuf,
7887        /// I/O error.
7888        #[source]
7889        source: io::Error,
7890    },
7891    /// Successful rustc did not produce the explicitly requested object.
7892    #[error("rustc succeeded without producing exact descriptor object `{0}`")]
7893    MissingDescriptorObject(PathBuf),
7894    /// Unit sidecar serialization failed.
7895    #[error("failed to serialize descriptor unit sidecar: {0}")]
7896    SerializeUnitSidecar(serde_json::Error),
7897    /// Sidecar target has no valid parent.
7898    #[error("descriptor sidecar path has no parent: `{0}`")]
7899    SidecarWithoutParent(PathBuf),
7900    /// Sidecar path has no UTF-8 filename.
7901    #[error("descriptor sidecar has an invalid filename: `{0}`")]
7902    InvalidSidecarFileName(PathBuf),
7903    /// Atomic sidecar write failed.
7904    #[error("failed to atomically write descriptor sidecar `{path}`: {source}")]
7905    WriteSidecar {
7906        /// Output or temporary path.
7907        path: PathBuf,
7908        /// I/O error.
7909        #[source]
7910        source: io::Error,
7911    },
7912    /// Same content identity unexpectedly produced different sidecar bytes.
7913    #[error("descriptor unit sidecar conflicts with an existing file: `{0}`")]
7914    ConflictingUnitSidecar(PathBuf),
7915    /// A sidecar or orchestrator input contained a malformed unit identity.
7916    #[error("invalid descriptor Cargo-unit identity `{value}`: {reason}")]
7917    InvalidCargoUnitId {
7918        /// Rejected representation.
7919        value: String,
7920        /// Validation detail.
7921        reason: String,
7922    },
7923}
7924
7925struct RustcWrapperDiagnostic {
7926    code: &'static str,
7927    message: String,
7928    notes: Vec<String>,
7929    help: Option<&'static str>,
7930}
7931
7932impl RustcWrapperDiagnostic {
7933    fn for_error(error: &WrapperError) -> Self {
7934        match error {
7935            WrapperError::ObservedSourceHashMismatch { path, .. } => Self {
7936                code: "RSJS0001",
7937                message: "a source file changed while RSJS was linking".to_string(),
7938                notes: vec![
7939                    format!("changed file: `{}`", path.display()),
7940                    "RSJS stopped before combining stale descriptor output with current source"
7941                        .to_string(),
7942                ],
7943                help: Some(
7944                    "retry the command after the file stops changing; if this repeats, check for a formatter or generator that keeps rewriting it",
7945                ),
7946            },
7947            WrapperError::OutDirDependencyHashMismatch { path, .. } => Self {
7948                code: "RSJS0002",
7949                message: "generated source changed while RSJS was linking".to_string(),
7950                notes: vec![
7951                    format!("changed generated file: `{}`", path.display()),
7952                    "RSJS stopped before combining stale descriptor output with current generated source"
7953                        .to_string(),
7954                ],
7955                help: Some(
7956                    "retry the command; if this repeats, check the build script or generator that owns this file",
7957                ),
7958            },
7959            WrapperError::ObservedEnvironmentMismatch { name } => Self {
7960                code: "RSJS0003",
7961                message: "the build environment changed while RSJS was linking".to_string(),
7962                notes: vec![
7963                    format!("changed environment variable: `{name}`"),
7964                    "RSJS stopped before combining artifacts built with different environments"
7965                        .to_string(),
7966                ],
7967                help: Some("retry the command with a stable build environment"),
7968            },
7969            _ => Self {
7970                code: "RSJS0000",
7971                message: format!("RSJS compiler wrapper failed: {error}"),
7972                notes: Vec::new(),
7973                help: None,
7974            },
7975        }
7976    }
7977
7978    fn rendered(&self) -> String {
7979        let mut rendered = format!("error[{}]: {}\n", self.code, self.message);
7980        for note in &self.notes {
7981            let _ = writeln!(rendered, "  = note: {note}");
7982        }
7983        if let Some(help) = self.help {
7984            let _ = writeln!(rendered, "  = help: {help}");
7985        }
7986        rendered
7987    }
7988}
7989
7990/// Render a hidden wrapper failure using rustc's JSON diagnostic protocol.
7991///
7992/// Cargo recognizes this as a compiler error and therefore does not replace
7993/// the useful failure with its full internal wrapper/rustc command line.
7994pub(crate) fn rustc_wrapper_diagnostic_json(error: &WrapperError) -> String {
7995    let diagnostic = RustcWrapperDiagnostic::for_error(error);
7996    let mut children = diagnostic
7997        .notes
7998        .iter()
7999        .map(|message| {
8000            serde_json::json!({
8001                "message": message,
8002                "code": null,
8003                "level": "note",
8004                "spans": [],
8005                "children": [],
8006                "rendered": null,
8007            })
8008        })
8009        .collect::<Vec<_>>();
8010    if let Some(help) = diagnostic.help {
8011        children.push(serde_json::json!({
8012            "message": help,
8013            "code": null,
8014            "level": "help",
8015            "spans": [],
8016            "children": [],
8017            "rendered": null,
8018        }));
8019    }
8020    serde_json::json!({
8021        "$message_type": "diagnostic",
8022        "message": diagnostic.message,
8023        "code": {
8024            "code": diagnostic.code,
8025            "explanation": null,
8026        },
8027        "level": "error",
8028        "spans": [],
8029        "children": children,
8030        "rendered": diagnostic.rendered(),
8031    })
8032    .to_string()
8033}
8034
8035/// Emit one Cargo-readable compiler diagnostic for a hidden wrapper failure.
8036pub(crate) fn emit_rustc_wrapper_diagnostic(error: &WrapperError) -> io::Result<()> {
8037    let stderr = io::stderr();
8038    let mut stderr = stderr.lock();
8039    writeln!(stderr, "{}", rustc_wrapper_diagnostic_json(error))
8040}
8041
8042/// Cargo JSON protocol failure.
8043#[derive(Debug, Error)]
8044pub enum CargoMessageError {
8045    /// Stream line could not be read.
8046    #[error("failed to read Cargo JSON line {line}: {source}")]
8047    Read {
8048        /// One-based line number.
8049        line: usize,
8050        /// I/O error.
8051        #[source]
8052        source: io::Error,
8053    },
8054    /// Cargo emitted an empty stdout line in JSON mode.
8055    #[error("empty Cargo JSON message at line {line}")]
8056    EmptyLine {
8057        /// One-based line number.
8058        line: usize,
8059    },
8060    /// JSON syntax is malformed.
8061    #[error("malformed Cargo JSON at line {line}: {source}")]
8062    MalformedJson {
8063        /// One-based line number.
8064        line: usize,
8065        /// JSON error.
8066        #[source]
8067        source: serde_json::Error,
8068    },
8069    /// Required `reason` discriminator is absent.
8070    #[error("Cargo JSON message at line {line} has no string `reason`")]
8071    MissingReason {
8072        /// One-based line number.
8073        line: usize,
8074    },
8075    /// A future reason must be reviewed before it is ignored.
8076    #[error("unsupported Cargo JSON reason `{reason}` at line {line}")]
8077    UnknownReason {
8078        /// One-based line number.
8079        line: usize,
8080        /// Cargo reason.
8081        reason: String,
8082    },
8083    /// A known non-artifact message omitted fields needed to trust the stream.
8084    #[error("malformed Cargo `{reason}` message at line {line}")]
8085    MalformedAuxiliaryMessage {
8086        /// One-based line number.
8087        line: usize,
8088        /// Cargo reason.
8089        reason: String,
8090    },
8091    /// Artifact message does not match Cargo's required schema.
8092    #[error("malformed Cargo compiler-artifact at line {line}: {source}")]
8093    MalformedCompilerArtifact {
8094        /// One-based line number.
8095        line: usize,
8096        /// JSON error.
8097        #[source]
8098        source: serde_json::Error,
8099    },
8100    /// Semantically required artifact identity material was empty.
8101    #[error("incomplete Cargo compiler-artifact at line {line}")]
8102    IncompleteCompilerArtifact {
8103        /// One-based line number.
8104        line: usize,
8105    },
8106    /// Cargo repeated exactly the same artifact message.
8107    #[error(
8108        "duplicate Cargo compiler-artifact for `{package_id}` target `{target}` at line {line}"
8109    )]
8110    DuplicateCompilerArtifact {
8111        /// One-based line number.
8112        line: usize,
8113        /// Cargo package.
8114        package_id: String,
8115        /// Cargo target.
8116        target: String,
8117    },
8118    /// Terminal message lacks its success flag.
8119    #[error("malformed Cargo build-finished message at line {line}")]
8120    MalformedBuildFinished {
8121        /// One-based line number.
8122        line: usize,
8123    },
8124    /// Any content after the terminal record is suspicious.
8125    #[error("Cargo JSON message appeared after build-finished at line {line}")]
8126    MessageAfterBuildFinished {
8127        /// One-based line number.
8128        line: usize,
8129    },
8130    /// Cargo reported compilation failure.
8131    #[error("descriptor Cargo compilation failed")]
8132    CargoBuildFailed,
8133    /// Stream ended without a terminal record.
8134    #[error("Cargo JSON stream ended without build-finished")]
8135    MissingBuildFinished,
8136}
8137
8138/// Failure to join Cargo-enumerated artifacts to wrapper units.
8139#[derive(Debug, Error, PartialEq, Eq)]
8140pub enum ArtifactMatchError {
8141    /// Exact path membership is required.
8142    #[error("descriptor unit {0} has no required Cargo filename")]
8143    NoRequiredFilenames(DescriptorCargoUnitId),
8144    /// A unit selector was repeated.
8145    #[error("descriptor unit {0} has duplicate artifact expectations")]
8146    DuplicateUnitExpectation(DescriptorCargoUnitId),
8147    /// No message matched every selector field.
8148    #[error("no exact Cargo compiler-artifact matched descriptor unit {0}")]
8149    MissingArtifact(DescriptorCargoUnitId),
8150    /// More than one message matched every selector field.
8151    #[error("descriptor unit {unit} matched {matches} Cargo compiler-artifacts")]
8152    AmbiguousArtifact {
8153        /// Descriptor unit.
8154        unit: DescriptorCargoUnitId,
8155        /// Candidate count.
8156        matches: usize,
8157    },
8158    /// Two units attempted to claim one Cargo message.
8159    #[error("Cargo compiler-artifact `{artifact}` was claimed by multiple descriptor units")]
8160    ArtifactClaimedByMultipleUnits {
8161        /// Representative exact Cargo path.
8162        artifact: PathBuf,
8163    },
8164}
8165
8166#[cfg(test)]
8167mod tests;