Skip to main content

eggpack_core/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3//! Producer-side release planning and finalized artifact evidence.
4
5mod builder;
6pub mod digest;
7mod finalization;
8mod floor;
9mod qualification;
10pub use builder::*;
11pub use digest::*;
12pub use finalization::*;
13pub use floor::*;
14pub use qualification::*;
15
16use eggpack_contract::{
17    expected_release_files, validate_release_inventory, DistributionContract, ExpandedAssets,
18    ExtrasPolicy, ReleaseInventory,
19};
20pub use eggpack_manifest::{validate_sha256_hex, Sha256Error};
21use eggpack_manifest::{
22    ArchiveMemberRecord, ArtifactForm, ArtifactRecord, BundleRecord, ByteEvidence, ReleaseManifest,
23    TargetRecord,
24};
25use serde::{Deserialize, Serialize};
26#[cfg(test)]
27use std::fs;
28use std::{collections::BTreeMap, fmt, path::PathBuf};
29
30#[cfg(test)]
31pub(crate) fn test_temp_dir(label: &str) -> PathBuf {
32    use std::sync::atomic::{AtomicU64, Ordering};
33    static NEXT: AtomicU64 = AtomicU64::new(0);
34    loop {
35        let id = NEXT.fetch_add(1, Ordering::Relaxed);
36        let path =
37            std::env::temp_dir().join(format!("eggpack-{label}-{}-{id}", std::process::id()));
38        match fs::create_dir(&path) {
39            Ok(()) => return path,
40            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
41            Err(error) => panic!("create test temp directory: {error}"),
42        }
43    }
44}
45
46/// Explicit mapping of one target's expanded contract filenames to local finalized files.
47#[derive(Debug, Clone)]
48pub struct FinalizedTargetInput {
49    /// Contract canonical triple or unambiguous alias.
50    pub target: String,
51    /// Explicit flat release filename to local path mappings, including checksum sidecars.
52    pub release_files: BTreeMap<String, PathBuf>,
53    /// Explicit archive-member source path to finalized local member bytes.
54    pub archive_members: BTreeMap<String, PathBuf>,
55}
56
57/// Caller-supplied identity and finalized file inventory for one release.
58#[derive(Debug, Clone)]
59pub struct FinalizedReleaseInput {
60    /// Opaque product id.
61    pub product_id: String,
62    /// Opaque release id/version used in contract expansion.
63    pub release_id: String,
64    /// Opaque source revision.
65    pub source_revision: String,
66    /// Selected finalized target inventories.
67    pub targets: Vec<FinalizedTargetInput>,
68    /// Bounded producer evidence references.
69    pub evidence_references: Vec<String>,
70}
71
72/// Manifest construction failure. Paths and file contents are intentionally omitted.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct CoreError(String);
75impl fmt::Display for CoreError {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(&self.0)
78    }
79}
80impl std::error::Error for CoreError {}
81fn err(s: impl Into<String>) -> CoreError {
82    CoreError(s.into())
83}
84/// Whether a host requirement matches a canonical target triple.
85///
86/// This is the **single** producer-side host/target match rule. Architecture
87/// is a triple prefix (`x86_64-`, `aarch64-`, `armv7-`) and the operating
88/// system is a triple predicate (`-linux-`, `-apple-darwin`, `-windows-`).
89///
90/// `Qualification::Native` is host-matched against this predicate, and
91/// `eggpack-ci` calls it instead of carrying an independent copy.
92pub fn host_matches_target(host: HostRequirement, triple: &str) -> bool {
93    let arch = match host.arch {
94        HostArch::X86_64 => triple.starts_with("x86_64-"),
95        HostArch::Aarch64 => triple.starts_with("aarch64-"),
96        HostArch::Armv7 => triple.starts_with("armv7-"),
97    };
98    let os = match host.os {
99        HostOs::Linux => triple.contains("-linux-"),
100        HostOs::Macos => triple.ends_with("-apple-darwin"),
101        HostOs::Windows => triple.contains("-windows-"),
102    };
103    arch && os
104}
105/// Whether a cross-tool pin is a complete version.
106///
107/// A pin must name a full `MAJOR.MINOR.PATCH`, optionally followed by a SemVer
108/// pre-release and/or build suffix. A partial pin is not a version: `0` and
109/// `0.14` match almost any reported version under the preflight's comparison,
110/// which would leave a declared toolchain requirement effectively unset while
111/// every check still reported success.
112fn valid_tool_version(value: &str) -> bool {
113    let core = value.split(['-', '+']).next().unwrap_or_default();
114    let parts: Vec<&str> = core.split('.').collect();
115    !value.is_empty()
116        && value.len() <= 64
117        && value
118            .bytes()
119            .all(|b| b.is_ascii_alphanumeric() || b".+-_".contains(&b))
120        && parts.len() == 3
121        && parts
122            .iter()
123            .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
124}
125
126/// Why a declared compatibility floor does not apply to a target.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum FloorApplicabilityError {
129    /// A glibc floor was declared for a target that is not GNU/Linux.
130    NotGlibcTarget,
131    /// A macOS floor was declared for a target that is not macOS.
132    NotMacosTarget,
133    /// A macOS floor was declared for a cargo-zigbuild build.
134    MacosFloorUnderZigbuild,
135}
136
137/// The compatibility-floor half of the floor rule that concerns the target
138/// triple alone.
139///
140/// A glibc floor applies only to a `-linux-gnu` triple and a macOS floor only
141/// to an `-apple-darwin` triple. The strategy half of the same rule lives in
142/// [`floor_applies_to_strategy`]; the two are composed by the canonical
143/// [`validate_floor_applicability`].
144fn floor_applies_to_triple(
145    floor: &CompatibilityFloor,
146    triple: &str,
147) -> Result<(), FloorApplicabilityError> {
148    match floor {
149        CompatibilityFloor::None => Ok(()),
150        CompatibilityFloor::Glibc { .. } if !triple.contains("-linux-gnu") => {
151            Err(FloorApplicabilityError::NotGlibcTarget)
152        }
153        CompatibilityFloor::Macos { .. } if !triple.ends_with("-apple-darwin") => {
154            Err(FloorApplicabilityError::NotMacosTarget)
155        }
156        _ => Ok(()),
157    }
158}
159
160/// The compatibility-floor half of the floor rule that concerns the build
161/// strategy alone.
162///
163/// A macOS floor cannot be satisfied by a cargo-zigbuild build: the cross
164/// tool does not produce a macOS deployment target, so the declared floor
165/// could never be proven.
166fn floor_applies_to_strategy(
167    floor: &CompatibilityFloor,
168    strategy: BuildStrategy,
169) -> Result<(), FloorApplicabilityError> {
170    match (floor, strategy) {
171        (CompatibilityFloor::Macos { .. }, BuildStrategy::CargoZigbuild) => {
172            Err(FloorApplicabilityError::MacosFloorUnderZigbuild)
173        }
174        _ => Ok(()),
175    }
176}
177
178/// Whether the declared compatibility floor applies to a target triple and a
179/// build strategy.
180///
181/// This is the **single** producer-side floor-applicability rule. It composes
182/// the two halves of the rule: a glibc floor requires a `-linux-gnu` triple
183/// and a macOS floor requires an `-apple-darwin` triple, and a macOS floor is
184/// incompatible with a cargo-zigbuild build.
185///
186/// `eggpack-ci` applies it to a projected plan instead of re-deriving the
187/// floor rules.
188pub fn validate_floor_applicability(
189    floor: &CompatibilityFloor,
190    strategy: BuildStrategy,
191    triple: &str,
192) -> Result<(), FloorApplicabilityError> {
193    floor_applies_to_triple(floor, triple)?;
194    floor_applies_to_strategy(floor, strategy)
195}
196
197/// Validate one target policy against its canonical target triple.
198///
199/// This is the **single** producer-side policy validation rule. It covers the
200/// toolchain requirement shape, the cross-tool presence rule for the selected
201/// strategy, the compatibility-floor applicability rule, and the
202/// native-qualification host match.
203///
204/// `eggpack-ci` applies it to a `CIPlan` instead of re-deriving any of those
205/// rules. The macOS-floor-under-cargo-zigbuild refusal is enforced where the
206/// build command is derived, so policy resolution keeps its outcome; the
207/// canonical floor rule covers it.
208pub fn validate_policy(policy: &TargetPolicy, triple: &str) -> Result<(), CoreError> {
209    if policy.toolchain.rust.is_empty()
210        || policy.toolchain.rust.len() > 64
211        || !policy
212            .toolchain
213            .rust
214            .bytes()
215            .all(|b| b.is_ascii_alphanumeric() || b".+-_".contains(&b))
216        || policy
217            .toolchain
218            .cargo_zigbuild
219            .as_ref()
220            .is_some_and(|v| !valid_tool_version(v))
221        || policy
222            .toolchain
223            .zig
224            .as_ref()
225            .is_some_and(|v| !valid_tool_version(v))
226    {
227        return Err(err(
228            "toolchain requirement is empty, overlong, or not a complete version",
229        ));
230    }
231    match policy.strategy {
232        BuildStrategy::NativeCargo => {
233            if policy.toolchain.cargo_zigbuild.is_some() || policy.toolchain.zig.is_some() {
234                return Err(err(
235                    "native Cargo strategy must not declare cross-build tool versions",
236                ));
237            }
238        }
239        BuildStrategy::CargoZigbuild => {
240            if policy.toolchain.cargo_zigbuild.is_none() || policy.toolchain.zig.is_none() {
241                return Err(err(
242                    "cargo-zigbuild strategy requires explicit cargo-zigbuild and Zig versions",
243                ));
244            }
245        }
246    }
247    if let Err(error) = floor_applies_to_triple(&policy.floor, triple) {
248        return Err(match error {
249            FloorApplicabilityError::NotGlibcTarget => {
250                err("glibc floor applies only to GNU/Linux targets")
251            }
252            FloorApplicabilityError::NotMacosTarget => {
253                err("macOS floor applies only to macOS targets")
254            }
255            FloorApplicabilityError::MacosFloorUnderZigbuild => {
256                err("macOS floor cannot use cargo-zigbuild")
257            }
258        });
259    }
260    if policy.qualification == Qualification::Native {
261        let host = policy.qualification_host.unwrap_or(HostRequirement {
262            os: policy.host_os,
263            arch: policy.host_arch,
264        });
265        if !host_matches_target(host, triple) {
266            return Err(err(
267                "native qualification requires a qualification host matching the target OS/arch",
268            ));
269        }
270    }
271    Ok(())
272}
273
274/// Why an exact release tag was refused for safety reasons.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum ExactTagSafetyError {
277    /// The tag is empty or longer than the documented bound.
278    OutOfBounds,
279    /// The tag contains a control character.
280    ControlCharacters,
281    /// The tag contains a character that is special to a query or a shell.
282    QueryOrInjectionCharacters,
283    /// The tag has an unsafe path shape.
284    UnsafePathShape,
285    /// The tag has a shape that is unsafe as a git ref path.
286    UnsafeGitRefPath,
287}
288
289/// The longest exact release tag that is considered at all.
290const MAX_EXACT_TAG_BYTES: usize = 128;
291
292/// Whether an exact release tag is safe to handle.
293///
294/// This is the **single** exact-tag safety rule in the workspace. It carries
295/// the union of the two concern sets that previously existed as separate
296/// partial rules:
297///
298/// - the git-ref-path concerns — a tag used as
299///   `refs/tags/<tag>^{commit}` must not contain `..`, must not begin or end
300///   with `/`, must not end with `.`, must not contain `@{`, must not contain
301///   `^`, `:`, `*`, `[` or `~`, and must not carry an empty, `.`-leading, or
302///   `.lock`-ending path component;
303/// - the shell-metacharacter concerns — a tag arriving from a workflow
304///   dispatch input must not contain `?`, `#`, `@`, a space, `\`, `'`, `"`,
305///   `` ` `` or `$`.
306///
307/// A tag is accepted only if it satisfies every concern, so the accepted set
308/// is the intersection of the two former accepted sets: this rule can only
309/// refuse more, never accept more.
310///
311/// This validator is **safety only**. The canonical *format* check — a
312/// `vX.Y.Z` stable version — is a separate, named concern with its own
313/// diagnostic, and a tag that is safe but not canonical is refused by the
314/// format check.
315pub fn validate_exact_tag_safety(tag: &str) -> Result<(), ExactTagSafetyError> {
316    if tag.is_empty() || tag.len() > MAX_EXACT_TAG_BYTES {
317        return Err(ExactTagSafetyError::OutOfBounds);
318    }
319    if tag.chars().any(char::is_control) {
320        return Err(ExactTagSafetyError::ControlCharacters);
321    }
322    if tag.contains(['?', '#', '@', ' ', '\\', '\'', '"', '`', '$']) {
323        return Err(ExactTagSafetyError::QueryOrInjectionCharacters);
324    }
325    if tag.contains("..") || tag.starts_with('/') || tag.ends_with('/') {
326        return Err(ExactTagSafetyError::UnsafePathShape);
327    }
328    if tag.ends_with('.')
329        || tag.contains("@{")
330        || tag.contains(['^', ':', '*', '[', '~'])
331        || tag.split('/').any(|component| {
332            component.is_empty() || component.starts_with('.') || component.ends_with(".lock")
333        })
334    {
335        return Err(ExactTagSafetyError::UnsafeGitRefPath);
336    }
337    Ok(())
338}
339
340/// Build and hash a complete schema-v1 manifest from explicitly supplied files.
341pub fn build_manifest(
342    contract: &DistributionContract,
343    input: &FinalizedReleaseInput,
344) -> Result<ReleaseManifest, CoreError> {
345    if contract.product.id != input.product_id {
346        return Err(err("product identity does not match contract"));
347    }
348    if input.targets.is_empty() || input.targets.len() > 256 {
349        return Err(err("target count out of bounds"));
350    }
351    let mut target_records = Vec::new();
352    let mut seen = std::collections::HashSet::new();
353    for target in &input.targets {
354        let expanded = contract
355            .expand(&target.target, &input.release_id)
356            .map_err(|_| err("target expansion failed"))?;
357        if !seen.insert(expanded.triple.clone()) {
358            return Err(err("duplicate canonical target"));
359        }
360        let expected = expected_release_files(contract, &target.target, &input.release_id)
361            .map_err(|_| err("expected inventory derivation failed"))?;
362        let inventory = ReleaseInventory::new(target.release_files.keys().cloned())
363            .map_err(|_| err("invalid release inventory"))?;
364        if !validate_release_inventory(&expected, &inventory, ExtrasPolicy::Exact).is_conformant() {
365            return Err(err("release inventory is incomplete or contains extras"));
366        }
367        let artifact = |name: &str| -> Result<ArtifactRecord, CoreError> {
368            let path = target
369                .release_files
370                .get(name)
371                .ok_or_else(|| err("required artifact path missing"))?;
372            let (size, sha256) = file_digest(path)
373                .map_err(|error| err(format!("finalized file {}", error.reason())))?;
374            Ok(ArtifactRecord {
375                name: name.to_string(),
376                size,
377                sha256,
378            })
379        };
380        let record_form = match expanded.assets {
381            ExpandedAssets::Direct(d) => {
382                if !target.archive_members.is_empty() {
383                    return Err(err("unexpected archive member inputs"));
384                }
385                ArtifactForm::Direct {
386                    artifact: artifact(&d.asset_file)?,
387                    install: d.install_name,
388                }
389            }
390            ExpandedAssets::Bundle(b) => {
391                if !target.archive_members.is_empty() {
392                    return Err(err("unexpected archive member inputs"));
393                }
394                ArtifactForm::Bundle {
395                    entries: b
396                        .entries
397                        .iter()
398                        .map(|e| {
399                            Ok(BundleRecord {
400                                artifact: artifact(&e.asset_file)?,
401                                install: e.install_name.clone(),
402                            })
403                        })
404                        .collect::<Result<_, CoreError>>()?,
405                }
406            }
407            ExpandedAssets::Archive(a) => {
408                if target.archive_members.len() != a.members.len() {
409                    return Err(err("archive member inventory incomplete or has extras"));
410                }
411                let members = a
412                    .members
413                    .iter()
414                    .map(|m| {
415                        let p = target
416                            .archive_members
417                            .get(&m.source)
418                            .ok_or_else(|| err("required archive member path missing"))?;
419                        let (size, sha256) = file_digest(p)
420                            .map_err(|error| err(format!("finalized file {}", error.reason())))?;
421                        Ok(ArchiveMemberRecord {
422                            source: m.source.clone(),
423                            install: m.install_name.clone(),
424                            bytes: ByteEvidence { size, sha256 },
425                        })
426                    })
427                    .collect::<Result<_, CoreError>>()?;
428                ArtifactForm::Archive {
429                    artifact: artifact(&a.archive_file)?,
430                    members,
431                }
432            }
433        };
434        target_records.push(TargetRecord {
435            target: expanded.triple,
436            form: record_form,
437        });
438    }
439    let manifest = ReleaseManifest {
440        schema_version: 1,
441        product_id: input.product_id.clone(),
442        release_id: input.release_id.clone(),
443        source_revision: input.source_revision.clone(),
444        targets: target_records,
445        evidence_references: input.evidence_references.clone(),
446    };
447    manifest
448        .validate()
449        .map_err(|_| err("constructed manifest violates schema-v1 bounds"))?;
450    Ok(manifest)
451}
452
453/// Explicit finite build strategy. Planning never executes either strategy.
454#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
455#[serde(rename_all = "snake_case")]
456pub enum BuildStrategy {
457    /// Native Cargo target build.
458    NativeCargo,
459    /// Cargo zigbuild cross-target build.
460    CargoZigbuild,
461}
462/// Host operating system family.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
464#[serde(rename_all = "snake_case")]
465pub enum HostOs {
466    /// Linux.
467    Linux,
468    /// macOS.
469    Macos,
470    /// Windows.
471    Windows,
472}
473/// Host CPU architecture family.
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(rename_all = "snake_case")]
476pub enum HostArch {
477    /// x86-64.
478    X86_64,
479    /// 64-bit ARM.
480    Aarch64,
481    /// 32-bit ARM.
482    Armv7,
483}
484/// Qualification classification stored as intent, not proof.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
486#[serde(rename_all = "snake_case")]
487pub enum Qualification {
488    /// Run on matching native host.
489    ///
490    /// Native qualification describes where and how the exact produced
491    /// candidate is proved; it is independent of `BuildStrategy`. A
492    /// cross-tool-built candidate (`CargoZigbuild`) is admissible here
493    /// whenever the effective qualification host matches the target's
494    /// operating system and architecture, and it earns native qualification
495    /// only by executing on that host.
496    Native,
497    /// Qualification is deferred.
498    DeferredNative,
499    /// Run under emulation.
500    Emulated,
501    /// Structural checks only.
502    Structural,
503}
504/// Support and release gating tier.
505#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(rename_all = "snake_case")]
507pub enum SupportTier {
508    /// Required release target.
509    Required,
510    /// Supported without gating.
511    NonGating,
512    /// Experimental target.
513    Experimental,
514}
515/// Provider-neutral OS/architecture capability required of a host.
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
517#[serde(deny_unknown_fields)]
518pub struct HostRequirement {
519    /// Host operating system family.
520    pub os: HostOs,
521    /// Host architecture family.
522    pub arch: HostArch,
523}
524/// Explicit compiler/toolchain requirements; no version is inferred from the host.
525///
526/// Schema version 1 is preserved: `zig` is an additive optional field so
527/// historical documents without Zig remain parseable. Current
528/// `CargoZigbuild` resolution fails closed when either cross-tool version is
529/// absent and never falls back to an ambient Zig; `NativeCargo` requires both
530/// cross-tool fields to be absent.
531#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
532#[serde(deny_unknown_fields)]
533pub struct ToolchainRequirement {
534    /// Exact or policy-bounded Rust toolchain string.
535    pub rust: String,
536    /// Optional exact cargo-zigbuild version when that strategy is selected.
537    #[serde(default, skip_serializing_if = "Option::is_none")]
538    pub cargo_zigbuild: Option<String>,
539    /// Optional exact Zig version when the cargo-zigbuild strategy is selected.
540    #[serde(default, skip_serializing_if = "Option::is_none")]
541    pub zig: Option<String>,
542}
543/// Explicit compatibility floor for produced binaries.
544#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
546pub enum CompatibilityFloor {
547    /// No additional deployment floor.
548    None,
549    /// Minimum GNU libc version.
550    Glibc {
551        /// Major version.
552        major: u16,
553        /// Minor version.
554        minor: u16,
555    },
556    /// Minimum macOS deployment version.
557    Macos {
558        /// Major version.
559        major: u16,
560        /// Minor version.
561        minor: u16,
562    },
563}
564/// One target policy in PackConfig v1.
565#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
566#[serde(deny_unknown_fields)]
567pub struct TargetPolicy {
568    /// Canonical contract triple.
569    pub target: String,
570    /// Build strategy.
571    pub strategy: BuildStrategy,
572    /// Build host OS.
573    pub host_os: HostOs,
574    /// Build host architecture.
575    pub host_arch: HostArch,
576    /// Optional separate machine capability for qualification.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub qualification_host: Option<HostRequirement>,
579    /// Required compiler and optional cross-build tool versions.
580    pub toolchain: ToolchainRequirement,
581    /// Compatibility/deployment floor asserted by producer policy.
582    ///
583    /// The floor is a build-policy input carried into the cross-tool build
584    /// command. Native qualification evidence proves that the exact candidate
585    /// executes on the qualifying native host; it is not independent proof that
586    /// the produced binary honours this declared minimum runtime.
587    pub floor: CompatibilityFloor,
588    /// Qualification intent.
589    pub qualification: Qualification,
590    /// Release support tier.
591    pub support: SupportTier,
592}
593/// Strict PackConfig v1 document.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595#[serde(deny_unknown_fields)]
596pub struct PackConfig {
597    /// Schema version exactly 1.
598    pub schema_version: u32,
599    /// Per-target producer policies.
600    pub targets: Vec<TargetPolicy>,
601}
602/// Canonically ordered pure release planning result.
603#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
604#[serde(deny_unknown_fields)]
605pub struct ReleasePlan {
606    /// Schema version exactly 1.
607    pub schema_version: u32,
608    /// Opaque release id.
609    pub release_id: String,
610    /// Opaque source revision.
611    pub source_revision: String,
612    /// Target plans sorted by canonical triple.
613    pub targets: Vec<PlannedTarget>,
614}
615/// One selected target's canonical policy and contract-derived artifact form.
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(deny_unknown_fields)]
618pub struct PlannedTarget {
619    /// Canonical contract triple.
620    pub target: String,
621    /// Producer policy resolved for this canonical target.
622    pub policy: TargetPolicy,
623    /// Artifact identity derived exclusively from the contract.
624    pub artifact_form: PlannedAssetForm,
625    /// Verification status of the declared compatibility floor.
626    ///
627    /// The status is derived from the policy by
628    /// [`planned_floor_status`], so a plan either states the status its
629    /// declaration implies or it is rejected. A document that omits the field
630    /// is read as `NotDeclared`, which is refused for any target that
631    /// declares a floor.
632    #[serde(default)]
633    pub floor_status: FloorVerificationStatus,
634}
635/// Contract-derived release artifact form.
636#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
637#[serde(rename_all = "snake_case")]
638pub enum PlannedAssetForm {
639    /// One direct release artifact.
640    Direct,
641    /// Multiple sibling artifacts.
642    Bundle,
643    /// One archive artifact with required members.
644    Archive,
645}
646impl ReleasePlan {
647    /// Validate the plan's bounds and the agreement between each declared
648    /// floor and the floor status the plan states for it.
649    ///
650    /// A plan that declares a floor and does not state a status for it is
651    /// invalid: the status is a pure function of the policy, so a missing or
652    /// contradictory status fails closed.
653    pub fn validate(&self) -> Result<(), CoreError> {
654        if self.schema_version != 1
655            || self.release_id.is_empty()
656            || self.source_revision.is_empty()
657            || self.targets.is_empty()
658        {
659            return Err(err("invalid ReleasePlan bounds"));
660        }
661        for planned in &self.targets {
662            if planned.floor_status != planned_floor_status(&planned.policy) {
663                return Err(err(
664                    "ReleasePlan floor status does not match the declared compatibility floor",
665                ));
666            }
667        }
668        Ok(())
669    }
670    /// Serialize the canonically ordered plan as deterministic compact JSON.
671    pub fn to_json(&self) -> Result<String, CoreError> {
672        self.validate()?;
673        serde_json::to_string(self).map_err(|_| err("ReleasePlan serialization failed"))
674    }
675}
676impl PackConfig {
677    /// Parse strict TOML PackConfig v1.
678    pub fn from_toml(s: &str) -> Result<Self, CoreError> {
679        let c: Self = toml::from_str(s).map_err(|_| err("invalid PackConfig TOML"))?;
680        if c.schema_version != 1 || c.targets.is_empty() {
681            return Err(err("invalid PackConfig version or empty targets"));
682        }
683        // Bounded at parse time, like every other count in the workspace
684        // (bindings, manifest targets, inventory entries, archive members).
685        // The file is caller-supplied, so an unbounded target array would
686        // allocate before anything downstream could reject it.
687        if c.targets.len() > 256 {
688            return Err(err("PackConfig target count out of bounds"));
689        }
690        let mut seen = std::collections::HashSet::new();
691        // Parse stays lenient about the additive Zig field so historical
692        // schema-v1 documents without Zig remain parseable; strict
693        // presence rules (CargoZigbuild requires both versions, NativeCargo
694        // requires neither) are enforced by resolution/validation, which
695        // fails closed rather than selecting an ambient Zig.
696        if c.targets.iter().any(|p| {
697            p.target.is_empty()
698                || !seen.insert(&p.target)
699                || p.toolchain.rust.is_empty()
700                || p.toolchain.rust.len() > 64
701                || (p.strategy == BuildStrategy::CargoZigbuild)
702                    != p.toolchain.cargo_zigbuild.is_some()
703        }) {
704            return Err(err("invalid or duplicate PackConfig target"));
705        }
706        Ok(c)
707    }
708    /// Resolve selected targets against the distribution contract without side effects.
709    pub fn resolve(
710        &self,
711        contract: &DistributionContract,
712        release_id: &str,
713        source_revision: &str,
714        selected: &[String],
715    ) -> Result<ReleasePlan, CoreError> {
716        if self.schema_version != 1 {
717            return Err(err("unsupported PackConfig version"));
718        }
719        let mut policies = BTreeMap::new();
720        for p in &self.targets {
721            let t = contract
722                .resolve(&p.target)
723                .map_err(|_| err("PackConfig contains unsupported target"))?;
724            validate_policy(p, &t.triple)?;
725            if policies.insert(t.triple.clone(), p).is_some() {
726                return Err(err("duplicate canonical policy target"));
727            }
728        }
729        let mut targets = Vec::new();
730        let mut seen = std::collections::HashSet::new();
731        for s in selected {
732            let t = contract
733                .resolve(s)
734                .map_err(|_| err("unknown selected target"))?;
735            if !seen.insert(t.triple.clone()) {
736                return Err(err("duplicate selected target"));
737            }
738            let mut policy = policies
739                .get(&t.triple)
740                .copied()
741                .ok_or_else(|| err("selected target has no policy"))?
742                .clone();
743            policy.target = t.triple.clone();
744            let artifact_form = match &t.asset {
745                eggpack_contract::AssetForm::Direct { .. } => PlannedAssetForm::Direct,
746                eggpack_contract::AssetForm::Bundle { .. } => PlannedAssetForm::Bundle,
747                eggpack_contract::AssetForm::Archive { .. } => PlannedAssetForm::Archive,
748            };
749            let floor_status = planned_floor_status(&policy);
750            targets.push(PlannedTarget {
751                target: t.triple.clone(),
752                policy,
753                artifact_form,
754                floor_status,
755            });
756        }
757        if targets.is_empty() {
758            return Err(err("no selected targets"));
759        }
760        targets.sort_by(|a, b| a.target.cmp(&b.target));
761        Ok(ReleasePlan {
762            schema_version: 1,
763            release_id: release_id.into(),
764            source_revision: source_revision.into(),
765            targets,
766        })
767    }
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773    #[test]
774    fn test_temp_roots_are_unique_under_parallel_and_repeated_calls() {
775        let existing = test_temp_dir("stale");
776        let next = test_temp_dir("stale");
777        assert_ne!(existing, next);
778        let workers = (0..16)
779            .map(|_| std::thread::spawn(|| test_temp_dir("parallel")))
780            .collect::<Vec<_>>();
781        let roots = workers
782            .into_iter()
783            .map(|worker| worker.join().unwrap())
784            .collect::<std::collections::BTreeSet<_>>();
785        assert_eq!(roots.len(), 16);
786        for path in roots.into_iter().chain([existing, next]) {
787            fs::remove_dir_all(path).unwrap();
788        }
789    }
790    #[test]
791    fn pack_config_resolves_targets_in_canonical_order() {
792        let contract = DistributionContract::parse_toml_str(include_str!(
793            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
794        ))
795        .unwrap();
796        let config = PackConfig {
797            schema_version: 1,
798            targets: vec![TargetPolicy {
799                target: "x86_64-unknown-linux-gnu".into(),
800                strategy: BuildStrategy::NativeCargo,
801                host_os: HostOs::Linux,
802                host_arch: HostArch::X86_64,
803                qualification_host: None,
804                toolchain: ToolchainRequirement {
805                    rust: "1.89.0".into(),
806                    cargo_zigbuild: None,
807                    zig: None,
808                },
809                floor: CompatibilityFloor::None,
810                qualification: Qualification::Native,
811                support: SupportTier::Required,
812            }],
813        };
814        let selected = vec!["linux-x64".into()];
815        assert_eq!(
816            config
817                .resolve(&contract, "1.2.6", "abc", &selected)
818                .unwrap()
819                .targets[0]
820                .target,
821            "x86_64-unknown-linux-gnu"
822        );
823        assert!(config
824            .resolve(&contract, "1.2.6", "abc", &["nope".into()])
825            .is_err());
826        let mut invalid = config.clone();
827        invalid.targets[0].qualification = Qualification::Emulated;
828        assert!(invalid
829            .resolve(&contract, "1.2.6", "abc", &selected)
830            .is_ok());
831        invalid.targets[0].qualification = Qualification::Native;
832        invalid.targets[0].host_arch = HostArch::Aarch64;
833        assert!(invalid
834            .resolve(&contract, "1.2.6", "abc", &selected)
835            .is_err());
836    }
837    #[test]
838    fn a_native_cargo_glibc_floor_is_recorded_in_the_plan_and_still_resolves() {
839        let contract = DistributionContract::parse_toml_str(include_str!(
840            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
841        ))
842        .unwrap();
843        let config = PackConfig {
844            schema_version: 1,
845            targets: vec![TargetPolicy {
846                target: "x86_64-unknown-linux-gnu".into(),
847                strategy: BuildStrategy::NativeCargo,
848                host_os: HostOs::Linux,
849                host_arch: HostArch::X86_64,
850                qualification_host: None,
851                toolchain: ToolchainRequirement {
852                    rust: "1.89.0".into(),
853                    cargo_zigbuild: None,
854                    zig: None,
855                },
856                floor: CompatibilityFloor::Glibc {
857                    major: 2,
858                    minor: 17,
859                },
860                qualification: Qualification::Native,
861                support: SupportTier::Required,
862            }],
863        };
864        let selected = vec!["linux-x64".into()];
865        // A declared glibc floor under native Cargo is still accepted, and it
866        // is no longer dropped: it survives into the plan with a status.
867        let plan = config
868            .resolve(&contract, "1.2.6", "abc", &selected)
869            .unwrap();
870        assert_eq!(
871            plan.targets[0].policy.floor,
872            CompatibilityFloor::Glibc {
873                major: 2,
874                minor: 17
875            }
876        );
877        assert_eq!(
878            plan.targets[0].floor_status,
879            FloorVerificationStatus::Unverified(FloorUnverifiedReason::PendingInspection)
880        );
881        assert!(plan.validate().is_ok());
882        assert!(plan.to_json().is_ok());
883        // A plan whose declared floor and stated status disagree is refused.
884        let mut contradictory = plan.clone();
885        contradictory.targets[0].floor_status = FloorVerificationStatus::NotDeclared;
886        assert!(contradictory.validate().is_err());
887        assert!(contradictory.to_json().is_err());
888        // A cargo-zigbuild target binds the floor into the toolchain instead.
889        let mut cross_tool = config.clone();
890        cross_tool.targets[0].strategy = BuildStrategy::CargoZigbuild;
891        cross_tool.targets[0].toolchain.cargo_zigbuild = Some("0.23.3".into());
892        cross_tool.targets[0].toolchain.zig = Some("0.14.1".into());
893        let plan = cross_tool
894            .resolve(&contract, "1.2.6", "abc", &selected)
895            .unwrap();
896        assert_eq!(
897            plan.targets[0].floor_status,
898            FloorVerificationStatus::ToolchainBound
899        );
900        assert!(plan.validate().is_ok());
901    }
902    #[test]
903    fn pack_config_toml_is_versioned_bounded_and_rejects_unknown_fields() {
904        let source = r#"schema_version=1
905[[targets]]
906target="x86_64-unknown-linux-gnu"
907strategy="native_cargo"
908host_os="linux"
909host_arch="x86_64"
910toolchain={rust="1.89.0"}
911floor={kind="none"}
912qualification="native"
913support="required"
914"#;
915        assert!(PackConfig::from_toml(source).is_ok());
916        assert!(
917            PackConfig::from_toml(&source.replace("support=", "unexpected=1\nsupport=")).is_err()
918        );
919        assert!(
920            PackConfig::from_toml(&source.replace("schema_version=1", "schema_version=2")).is_err()
921        );
922    }
923    #[test]
924    fn native_qualification_is_admitted_for_cross_tool_builds_on_a_matching_host() {
925        let contract = DistributionContract::parse_toml_str(include_str!(
926            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
927        ))
928        .unwrap();
929        let selected = vec!["linux-x64".into()];
930        let cross = TargetPolicy {
931            target: "x86_64-unknown-linux-gnu".into(),
932            strategy: BuildStrategy::CargoZigbuild,
933            host_os: HostOs::Linux,
934            host_arch: HostArch::X86_64,
935            qualification_host: None,
936            toolchain: ToolchainRequirement {
937                rust: "1.89.0".into(),
938                cargo_zigbuild: Some("0.23.3".into()),
939                zig: Some("0.14.1".into()),
940            },
941            floor: CompatibilityFloor::Glibc {
942                major: 2,
943                minor: 17,
944            },
945            qualification: Qualification::Native,
946            support: SupportTier::Required,
947        };
948        let resolve = |policy: &TargetPolicy| {
949            PackConfig {
950                schema_version: 1,
951                targets: vec![policy.clone()],
952            }
953            .resolve(&contract, "1.2.6", "abc", &selected)
954        };
955        // Cross-tool builder, declared glibc floor, native qualification on the
956        // matching host: admissible, and the plan preserves the exact producer
957        // policy rather than weakening it to a non-executing classification.
958        let release = resolve(&cross).unwrap();
959        let planned = &release.targets[0];
960        assert_eq!(planned.target, "x86_64-unknown-linux-gnu");
961        assert_eq!(planned.policy.strategy, BuildStrategy::CargoZigbuild);
962        assert_eq!(planned.policy.qualification, Qualification::Native);
963        assert_eq!(
964            planned.policy.floor,
965            CompatibilityFloor::Glibc {
966                major: 2,
967                minor: 17
968            }
969        );
970        assert_eq!(
971            planned.policy.toolchain.cargo_zigbuild.as_deref(),
972            Some("0.23.3")
973        );
974        assert_eq!(planned.policy.toolchain.zig.as_deref(), Some("0.14.1"));
975        // An explicit matching qualification host is equally admissible; the
976        // effective host is the same either way, and the plan preserves the
977        // declaration verbatim.
978        let mut explicit = cross.clone();
979        explicit.qualification_host = Some(HostRequirement {
980            os: HostOs::Linux,
981            arch: HostArch::X86_64,
982        });
983        let explicit = resolve(&explicit).unwrap();
984        assert_eq!(
985            explicit.targets[0].policy.qualification_host,
986            Some(HostRequirement {
987                os: HostOs::Linux,
988                arch: HostArch::X86_64,
989            })
990        );
991        assert!(host_matches_target(
992            explicit.targets[0]
993                .policy
994                .qualification_host
995                .expect("explicit qualification host"),
996            &explicit.targets[0].target
997        ));
998        // A non-matching qualification host architecture is still rejected.
999        let mut wrong_arch = cross.clone();
1000        wrong_arch.qualification_host = Some(HostRequirement {
1001            os: HostOs::Linux,
1002            arch: HostArch::Aarch64,
1003        });
1004        assert!(resolve(&wrong_arch).is_err());
1005        let mut wrong_build_arch = cross.clone();
1006        wrong_build_arch.host_arch = HostArch::Aarch64;
1007        assert!(resolve(&wrong_build_arch).is_err());
1008        // A non-matching qualification host OS is still rejected.
1009        let mut wrong_os = cross.clone();
1010        wrong_os.qualification_host = Some(HostRequirement {
1011            os: HostOs::Macos,
1012            arch: HostArch::X86_64,
1013        });
1014        assert!(resolve(&wrong_os).is_err());
1015        // `NativeCargo` still refuses every cross-tool version, including on a
1016        // natively qualified target.
1017        for toolchain in [
1018            ToolchainRequirement {
1019                rust: "1.89.0".into(),
1020                cargo_zigbuild: Some("0.23.3".into()),
1021                zig: None,
1022            },
1023            ToolchainRequirement {
1024                rust: "1.89.0".into(),
1025                cargo_zigbuild: None,
1026                zig: Some("0.14.1".into()),
1027            },
1028            ToolchainRequirement {
1029                rust: "1.89.0".into(),
1030                cargo_zigbuild: Some("0.23.3".into()),
1031                zig: Some("0.14.1".into()),
1032            },
1033        ] {
1034            let mut native = cross.clone();
1035            native.strategy = BuildStrategy::NativeCargo;
1036            native.floor = CompatibilityFloor::None;
1037            native.toolchain = toolchain;
1038            assert!(resolve(&native).is_err());
1039        }
1040        // Floor applicability is unchanged: glibc is GNU/Linux-only and the
1041        // macOS floor is Darwin-only, whatever the strategy.
1042        let mut glibc_on_macos = cross.clone();
1043        glibc_on_macos.target = "aarch64-apple-darwin".into();
1044        glibc_on_macos.host_os = HostOs::Macos;
1045        glibc_on_macos.host_arch = HostArch::Aarch64;
1046        assert!(PackConfig {
1047            schema_version: 1,
1048            targets: vec![glibc_on_macos],
1049        }
1050        .resolve(&contract, "1.2.6", "abc", &["macos-arm64".into()])
1051        .is_err());
1052        let mut macos_floor_on_linux = cross.clone();
1053        macos_floor_on_linux.floor = CompatibilityFloor::Macos {
1054            major: 13,
1055            minor: 0,
1056        };
1057        assert!(resolve(&macos_floor_on_linux).is_err());
1058    }
1059    #[test]
1060    fn zig_version_is_required_for_zigbuild_and_forbidden_for_native() {
1061        let contract = DistributionContract::parse_toml_str(include_str!(
1062            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1063        ))
1064        .unwrap();
1065        let selected = vec!["linux-x64".into()];
1066        let base = TargetPolicy {
1067            target: "x86_64-unknown-linux-gnu".into(),
1068            strategy: BuildStrategy::CargoZigbuild,
1069            host_os: HostOs::Linux,
1070            host_arch: HostArch::X86_64,
1071            qualification_host: None,
1072            toolchain: ToolchainRequirement {
1073                rust: "1.89.0".into(),
1074                cargo_zigbuild: Some("0.23.3".into()),
1075                zig: Some("0.14.1".into()),
1076            },
1077            floor: CompatibilityFloor::Glibc {
1078                major: 2,
1079                minor: 17,
1080            },
1081            qualification: Qualification::Structural,
1082            support: SupportTier::Required,
1083        };
1084        let config = PackConfig {
1085            schema_version: 1,
1086            targets: vec![base.clone()],
1087        };
1088        assert!(config.resolve(&contract, "1.2.6", "abc", &selected).is_ok());
1089        // Historical schema-v1 input without Zig parses but fails resolution
1090        // rather than selecting an ambient Zig.
1091        let historical = r#"schema_version=1
1092[[targets]]
1093target="x86_64-unknown-linux-gnu"
1094strategy="cargo_zigbuild"
1095host_os="linux"
1096host_arch="x86_64"
1097toolchain={rust="1.89.0", cargo_zigbuild="0.23.3"}
1098floor={kind="glibc", major=2, minor=17}
1099qualification="structural"
1100support="required"
1101"#;
1102        let parsed = PackConfig::from_toml(historical).unwrap();
1103        assert!(parsed.targets[0].toolchain.zig.is_none());
1104        assert!(parsed
1105            .resolve(&contract, "1.2.6", "abc", &selected)
1106            .is_err());
1107        // Missing cargo-zigbuild with Zig present also fails closed.
1108        let mut missing_zigbuild = base.clone();
1109        missing_zigbuild.toolchain.cargo_zigbuild = None;
1110        assert!(PackConfig {
1111            schema_version: 1,
1112            targets: vec![missing_zigbuild],
1113        }
1114        .resolve(&contract, "1.2.6", "abc", &selected)
1115        .is_err());
1116        // Missing Zig with cargo-zigbuild present fails closed.
1117        let mut missing_zig = base.clone();
1118        missing_zig.toolchain.zig = None;
1119        assert!(PackConfig {
1120            schema_version: 1,
1121            targets: vec![missing_zig],
1122        }
1123        .resolve(&contract, "1.2.6", "abc", &selected)
1124        .is_err());
1125        // Either cross-tool version on NativeCargo fails.
1126        for toolchain in [
1127            ToolchainRequirement {
1128                rust: "1.89.0".into(),
1129                cargo_zigbuild: Some("0.23.3".into()),
1130                zig: None,
1131            },
1132            ToolchainRequirement {
1133                rust: "1.89.0".into(),
1134                cargo_zigbuild: None,
1135                zig: Some("0.14.1".into()),
1136            },
1137            ToolchainRequirement {
1138                rust: "1.89.0".into(),
1139                cargo_zigbuild: Some("0.23.3".into()),
1140                zig: Some("0.14.1".into()),
1141            },
1142        ] {
1143            let mut native = base.clone();
1144            native.strategy = BuildStrategy::NativeCargo;
1145            native.floor = CompatibilityFloor::None;
1146            native.qualification = Qualification::Native;
1147            native.toolchain = toolchain;
1148            assert!(PackConfig {
1149                schema_version: 1,
1150                targets: vec![native],
1151            }
1152            .resolve(&contract, "1.2.6", "abc", &selected)
1153            .is_err());
1154        }
1155        // Out-of-grammar Zig versions fail.
1156        let mut bad_grammar = base;
1157        bad_grammar.toolchain.zig = Some("0.14.1/../../evil".into());
1158        assert!(PackConfig {
1159            schema_version: 1,
1160            targets: vec![bad_grammar],
1161        }
1162        .resolve(&contract, "1.2.6", "abc", &selected)
1163        .is_err());
1164    }
1165    #[test]
1166    fn manifest_builder_hashes_only_explicit_contract_paths() {
1167        let contract = DistributionContract::parse_toml_str(include_str!(
1168            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1169        ))
1170        .unwrap();
1171        let dir = test_temp_dir("core-test");
1172        let names = [
1173            "eggsact-1.2.6-x86_64-unknown-linux-gnu",
1174            "eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256",
1175        ];
1176        let mut files = BTreeMap::new();
1177        for n in names {
1178            let p = dir.join(n);
1179            fs::write(&p, b"abc").unwrap();
1180            files.insert(n.to_string(), p);
1181        }
1182        let input = FinalizedReleaseInput {
1183            product_id: "eggsact".into(),
1184            release_id: "1.2.6".into(),
1185            source_revision: "a".repeat(40),
1186            targets: vec![FinalizedTargetInput {
1187                target: "linux-x64".into(),
1188                release_files: files,
1189                archive_members: BTreeMap::new(),
1190            }],
1191            evidence_references: vec![],
1192        };
1193        let m = build_manifest(&contract, &input).unwrap();
1194        assert_eq!(m.targets[0].target, "x86_64-unknown-linux-gnu");
1195        assert_eq!(
1196            m.targets[0].form,
1197            ArtifactForm::Direct {
1198                artifact: ArtifactRecord {
1199                    name: names[0].into(),
1200                    size: 3,
1201                    sha256: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1202                        .into()
1203                },
1204                install: "eggsact".into()
1205            }
1206        );
1207        fs::remove_dir_all(dir).unwrap();
1208    }
1209    #[test]
1210    fn manifest_builder_refuses_artifacts_that_are_not_regular_non_empty_files() {
1211        // The manifest path routes through the crate's single file-digest
1212        // authority, so it inherits its fail-closed policy: a non-regular,
1213        // symlinked, empty, or missing artifact is refused rather than
1214        // recorded. The authority's post-read re-check — which refuses a path
1215        // that changes while it is read — cannot be staged deterministically
1216        // on the supported platforms, so it is asserted directly in
1217        // `digest.rs` instead of being raced here.
1218        let contract = DistributionContract::parse_toml_str(include_str!(
1219            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1220        ))
1221        .unwrap();
1222        let dir = test_temp_dir("core-digest-policy");
1223        let names = [
1224            "eggsact-1.2.6-x86_64-unknown-linux-gnu",
1225            "eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256",
1226        ];
1227        let mut files = BTreeMap::new();
1228        for name in names {
1229            let path = dir.join(name);
1230            fs::write(&path, b"abc").unwrap();
1231            files.insert(name.to_string(), path);
1232        }
1233        let input = FinalizedReleaseInput {
1234            product_id: "eggsact".into(),
1235            release_id: "1.2.6".into(),
1236            source_revision: "a".repeat(40),
1237            targets: vec![FinalizedTargetInput {
1238                target: "linux-x64".into(),
1239                release_files: files,
1240                archive_members: BTreeMap::new(),
1241            }],
1242            evidence_references: vec![],
1243        };
1244        assert!(build_manifest(&contract, &input).is_ok());
1245        fs::write(dir.join(names[0]), b"").unwrap();
1246        assert!(build_manifest(&contract, &input).is_err());
1247        fs::remove_file(dir.join(names[0])).unwrap();
1248        assert!(build_manifest(&contract, &input).is_err());
1249        fs::remove_dir_all(dir).unwrap();
1250    }
1251    #[cfg(unix)]
1252    #[test]
1253    fn manifest_builder_refuses_a_symlinked_artifact() {
1254        let contract = DistributionContract::parse_toml_str(include_str!(
1255            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1256        ))
1257        .unwrap();
1258        let dir = test_temp_dir("core-digest-symlink");
1259        let names = [
1260            "eggsact-1.2.6-x86_64-unknown-linux-gnu",
1261            "eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256",
1262        ];
1263        let mut files = BTreeMap::new();
1264        for name in names {
1265            let path = dir.join(name);
1266            fs::write(&path, b"abc").unwrap();
1267            files.insert(name.to_string(), path);
1268        }
1269        let input = FinalizedReleaseInput {
1270            product_id: "eggsact".into(),
1271            release_id: "1.2.6".into(),
1272            source_revision: "a".repeat(40),
1273            targets: vec![FinalizedTargetInput {
1274                target: "linux-x64".into(),
1275                release_files: files,
1276                archive_members: BTreeMap::new(),
1277            }],
1278            evidence_references: vec![],
1279        };
1280        let artifact = dir.join(names[0]);
1281        let real = dir.join("real-artifact");
1282        fs::rename(&artifact, &real).unwrap();
1283        std::os::unix::fs::symlink(&real, &artifact).unwrap();
1284        assert!(build_manifest(&contract, &input).is_err());
1285        fs::remove_dir_all(dir).unwrap();
1286    }
1287    #[test]
1288    fn bundle_and_archive_inputs_preserve_contract_relationships() {
1289        for (fixture, release, product, target) in [
1290            (
1291                include_str!("../../eggpack-contract/tests/fixtures/codegg-bundle.toml"),
1292                "2.4.0",
1293                "codegg",
1294                "linux-x64",
1295            ),
1296            (
1297                include_str!("../../eggpack-contract/tests/fixtures/egress-archive.toml"),
1298                "3.1.0",
1299                "egress",
1300                "linux-x64",
1301            ),
1302        ] {
1303            let contract = DistributionContract::parse_toml_str(fixture).unwrap();
1304            let expected = expected_release_files(&contract, target, release).unwrap();
1305            let dir = test_temp_dir(&format!("layout-test-{product}"));
1306            let mut files = BTreeMap::new();
1307            for item in expected {
1308                let path = dir.join(&item.file_name);
1309                fs::write(&path, b"asset").unwrap();
1310                files.insert(item.file_name, path);
1311            }
1312            let expanded = contract.expand(target, release).unwrap();
1313            let members = match expanded.assets {
1314                ExpandedAssets::Archive(a) => a
1315                    .members
1316                    .into_iter()
1317                    .map(|m| {
1318                        let path = dir.join(format!("member-{}", m.source.replace('/', "_")));
1319                        fs::write(&path, b"member").unwrap();
1320                        (m.source, path)
1321                    })
1322                    .collect(),
1323                _ => BTreeMap::new(),
1324            };
1325            let input = FinalizedReleaseInput {
1326                product_id: product.into(),
1327                release_id: release.into(),
1328                source_revision: "c".repeat(40),
1329                targets: vec![FinalizedTargetInput {
1330                    target: target.into(),
1331                    release_files: files,
1332                    archive_members: members,
1333                }],
1334                evidence_references: vec![],
1335            };
1336            let manifest = build_manifest(&contract, &input).unwrap();
1337            match &manifest.targets[0].form {
1338                ArtifactForm::Bundle { .. } if product == "codegg" => (),
1339                ArtifactForm::Archive { members, .. } if product == "egress" => {
1340                    assert_eq!(members.len(), 2)
1341                }
1342                _ => panic!("contract form was not preserved"),
1343            }
1344            fs::remove_dir_all(dir).unwrap();
1345        }
1346    }
1347    #[test]
1348    fn manifest_builder_rejects_missing_or_extra_contract_inventory() {
1349        let contract = DistributionContract::parse_toml_str(include_str!(
1350            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1351        ))
1352        .unwrap();
1353        let dir = test_temp_dir("core-negative");
1354        let mut files = BTreeMap::new();
1355        for name in [
1356            "eggsact-1.2.6-x86_64-unknown-linux-gnu",
1357            "eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256",
1358        ] {
1359            let p = dir.join(name);
1360            fs::write(&p, b"x").unwrap();
1361            files.insert(name.to_string(), p);
1362        }
1363        let mut input = FinalizedReleaseInput {
1364            product_id: "eggsact".into(),
1365            release_id: "1.2.6".into(),
1366            source_revision: "a".repeat(40),
1367            targets: vec![FinalizedTargetInput {
1368                target: "linux-x64".into(),
1369                release_files: files,
1370                archive_members: BTreeMap::new(),
1371            }],
1372            evidence_references: vec![],
1373        };
1374        input.targets[0]
1375            .release_files
1376            .remove("eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256");
1377        assert!(build_manifest(&contract, &input).is_err());
1378        input.targets[0]
1379            .release_files
1380            .insert("unexpected.file".into(), dir.join("unused"));
1381        assert!(build_manifest(&contract, &input).is_err());
1382        fs::remove_dir_all(dir).unwrap();
1383    }
1384}