Skip to main content

proa_cli/rsjs/
link.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Deterministic linking of the RSJS records in one exact root manifest.
5//!
6//! This module is intentionally downstream of Cargo. It never scans a target
7//! directory or resolves a Rust item from source-path text. The caller gives it
8//! one validated [`LinkUnitManifest`], and every component/helper identity is
9//! selected through the relocation records in the manifest's exact descriptor
10//! objects. Stable semantic namespaces come only from the inline identity
11//! record joined to that exact definition.
12
13use std::collections::{BTreeMap, BTreeSet};
14use std::fs::{self, OpenOptions};
15use std::io::{self, Write};
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicU64, Ordering};
18
19use rayon::prelude::*;
20use rsjs_ir::abi::{
21    CanonicalEncode, CanonicalEncoder, CargoUnitId, LinkUnitId, PlanId, SemanticHash,
22    CLIENT_IR_SCHEMA_VERSION,
23};
24use rsjs_ir::build::{ArtifactRole, BuildIdentityError, LinkPlanMaterial, LinkUnitManifest};
25use rsjs_transport::{
26    canonical_json_bytes, component_field_record_id, component_record_id,
27    shared_state_provider_source_edge_id, ArtifactRecords, ComponentDefinitionAbi,
28    ExtractedTransport, ExtractionError, ResolvedComponentDefinition, ResolvedHelperDefinition,
29    SemanticIdentity, TransportCallbackShape, TransportComponentFieldRole,
30    TransportComponentOriginPermission, TransportComponentRenderKind, TransportRecordId,
31    TransportSharedStateProviderSite, UNASSIGNED_CARGO_UNIT_ID,
32};
33use serde::Deserialize;
34use serde_json::Value;
35use sha2::{Digest, Sha256};
36use thiserror::Error;
37
38use crate::rsjs::build::{ValidatedDescriptorUnit, DESCRIPTOR_OBJECT_HASH_DOMAIN};
39
40const TRANSPORT_LINK_SCHEMA_VERSION: u16 = 5;
41const LINK_ARTIFACT_HASH_DOMAIN: &[u8] = b"proa.rsjs.link-artifact.v1";
42const COMPONENT_PAYLOAD_FORMAT: &str = "rsjs.component_transport_payload";
43const COMPONENT_PAYLOAD_SCHEMA: u16 = 9;
44const COMPONENT_DESCRIPTOR_FORMAT: &str = "rsjs.component_descriptor";
45const COMPONENT_DESCRIPTOR_SCHEMA_VERSION: u64 = 9;
46const HELPER_PAYLOAD_FORMAT: &str = "rsjs.standalone_helper_descriptor";
47const COMPONENT_SEMANTIC_DOMAIN: &[u8] = b"proa.rsjs.component-transport-payload.semantic.v8\0";
48const HELPER_SEMANTIC_DOMAIN: &[u8] = b"proa.rsjs.standalone-helper.semantic.v1\0";
49
50static PLAN_WRITE_NONCE: AtomicU64 = AtomicU64::new(0);
51
52/// Exact build-local identity of one component or helper definition.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct TransportDefinitionId {
55    /// Descriptor-pass Cargo unit that emitted the record.
56    pub unit: CargoUnitId,
57    /// Definition record ID embedded beside its Rust relocation witness.
58    pub record: TransportRecordId,
59}
60
61impl CanonicalEncode for TransportDefinitionId {
62    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
63        encoder.record("TransportDefinitionId", 2);
64        encoder.field(1, &self.unit);
65        encoder.field(2, &self.record);
66    }
67}
68
69/// One direct component edge after rustc relocation resolution.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct LinkedComponentEdge {
72    /// Parent-local source edge record.
73    pub source_edge: TransportRecordId,
74    /// Exact child definition selected by the relocation.
75    pub target: TransportDefinitionId,
76}
77
78impl CanonicalEncode for LinkedComponentEdge {
79    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
80        encoder.record("LinkedComponentEdge", 2);
81        encoder.field(1, &self.source_edge);
82        encoder.field(2, &self.target);
83    }
84}
85
86/// One client-helper call after rustc relocation resolution.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct LinkedHelperEdge {
89    /// Component/helper-local source edge record.
90    pub source_edge: TransportRecordId,
91    /// Exact standalone helper selected by the relocation.
92    pub target: TransportDefinitionId,
93}
94
95impl CanonicalEncode for LinkedHelperEdge {
96    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
97        encoder.record("LinkedHelperEdge", 2);
98        encoder.field(1, &self.source_edge);
99        encoder.field(2, &self.target);
100    }
101}
102
103/// One client-visible component field after its rustc relocation has been
104/// joined to the exact defining component.
105///
106/// The behavior-bearing field/crossing/role/shape claim remains in the
107/// producer payload. `field_record` is independently recomputed from that
108/// claim before this value is constructed.
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct LinkedComponentFieldWitness {
111    /// Deterministic field record selected from the exact object.
112    pub field_record: TransportRecordId,
113    /// Exact component definition reached by the record relocation.
114    pub target: TransportDefinitionId,
115}
116
117impl CanonicalEncode for LinkedComponentFieldWitness {
118    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
119        encoder.record("LinkedComponentFieldWitness", 2);
120        encoder.field(1, &self.field_record);
121        encoder.field(2, &self.target);
122    }
123}
124
125/// One descriptor store owned by a relocation-resolved SharedState
126/// acquisition.
127///
128/// `store_id` is local to the defining component descriptor. `source_edge`
129/// joins that semantic slot to the exact object record; `target` is the
130/// SharedState definition rustc selected through the acquired type's ABI
131/// witness.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct LinkedComponentSharedStateAcquisition {
134    /// Dense component-local SharedStoreId.
135    pub store_id: u32,
136    /// Exact component-local acquisition record.
137    pub source_edge: TransportRecordId,
138    /// Rust-resolved SharedState definition.
139    pub target: TransportDefinitionId,
140}
141
142impl CanonicalEncode for LinkedComponentSharedStateAcquisition {
143    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
144        encoder.record("LinkedComponentSharedStateAcquisition", 3);
145        encoder.field(1, &self.store_id);
146        encoder.field(2, &self.source_edge);
147        encoder.field(3, &self.target);
148    }
149}
150
151/// One static SharedState provider declaration after both of its nominal Rust
152/// edges have been resolved.
153///
154/// `source_edge` selects the provider's exact SharedState witness relocation.
155/// `child_source_edge` selects the already-linked direct child component edge.
156/// The complete server expression and source metadata remain in `payload` for
157/// the later final-child rewrite; this canonical record carries only the
158/// authenticated topology and identities.
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub struct LinkedComponentSharedStateProviderSite {
161    /// Dense component-local provider site ID.
162    pub provider_site_id: u32,
163    /// Exact component-local provider witness record.
164    pub source_edge: TransportRecordId,
165    /// Rust-resolved SharedState definition.
166    pub target: TransportDefinitionId,
167    /// Dense component-local direct child edge ordinal.
168    pub child_edge_local_ordinal: u32,
169    /// Exact direct child source edge committed by the provider claim.
170    pub child_source_edge: TransportRecordId,
171    /// Rust-resolved child component definition.
172    pub child_target: TransportDefinitionId,
173    /// Whole-provider server node retained by the producer descriptor.
174    pub site_node: u32,
175}
176
177impl CanonicalEncode for LinkedComponentSharedStateProviderSite {
178    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
179        encoder.record("LinkedComponentSharedStateProviderSite", 7);
180        encoder.field(1, &self.provider_site_id);
181        encoder.field(2, &self.source_edge);
182        encoder.field(3, &self.target);
183        encoder.field(4, &self.child_edge_local_ordinal);
184        encoder.field(5, &self.child_source_edge);
185        encoder.field(6, &self.child_target);
186        encoder.field(7, &self.site_node);
187    }
188}
189
190/// Stable namespace emitted from `env!` and `module_path!` beside one exact
191/// definition.
192///
193/// This is deliberately separate from [`TransportDefinitionId`]: rebuilds and
194/// relinks change transport identity without changing this declared ABI key.
195#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
196pub struct LinkedSemanticIdentity {
197    /// Declared Cargo package namespace.
198    pub package: String,
199    /// Normalized Rust crate name.
200    pub crate_name: String,
201    /// Defining module segments, excluding the crate prefix.
202    pub module_path: Vec<String>,
203    /// Defining component/helper item name.
204    pub item: String,
205}
206
207impl From<&SemanticIdentity> for LinkedSemanticIdentity {
208    fn from(identity: &SemanticIdentity) -> Self {
209        Self {
210            package: identity.package.clone(),
211            crate_name: identity.crate_name.clone(),
212            module_path: identity.module_path.clone(),
213            item: identity.item.clone(),
214        }
215    }
216}
217
218impl CanonicalEncode for LinkedSemanticIdentity {
219    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
220        encoder.record("LinkedSemanticIdentity", 4);
221        encoder.field(1, &self.package);
222        encoder.field(2, &self.crate_name);
223        encoder.field(3, &self.module_path);
224        encoder.field(4, &self.item);
225    }
226}
227
228/// One component descriptor and all of its relocation-resolved outgoing edges.
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub struct LinkedTransportComponent {
231    /// Exact defining record.
232    pub definition: TransportDefinitionId,
233    /// Stable package/crate/module/item ABI identity emitted beside that exact
234    /// record.
235    pub identity: LinkedSemanticIdentity,
236    /// Producer-validated behavior hash of the complete component payload.
237    pub semantic_hash: SemanticHash,
238    /// Rust-checked server render surface and client-origin permission carried
239    /// by the defining witness record.
240    pub component_abi: ComponentDefinitionAbi,
241    /// Direct component edges in stable source-edge order.
242    pub component_edges: Vec<LinkedComponentEdge>,
243    /// Reachable standalone-helper edges in stable source-edge order.
244    pub helper_edges: Vec<LinkedHelperEdge>,
245    /// Rust-checked client-visible input fields in deterministic record order.
246    pub field_witnesses: Vec<LinkedComponentFieldWitness>,
247    /// Descriptor-local SharedState stores joined to exact rustc-resolved
248    /// acquisition records.
249    pub shared_state_acquisitions: Vec<LinkedComponentSharedStateAcquisition>,
250    /// Static SharedState provider declarations authenticated against both
251    /// their state ABI witness and direct child component edge.
252    pub shared_state_provider_sites: Vec<LinkedComponentSharedStateProviderSite>,
253    /// Complete embedded payload retained for the semantic ABI adapter and
254    /// final-plan diagnostics. Identity comes from `semantic_hash`, not from
255    /// host paths or object offsets.
256    pub payload: Value,
257}
258
259impl CanonicalEncode for LinkedTransportComponent {
260    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
261        encoder.record("LinkedTransportComponent", 9);
262        encoder.field(1, &self.definition);
263        encoder.field(2, &self.identity);
264        encoder.field(3, &self.semantic_hash);
265        encoder.field(4, &self.component_abi.flags());
266        encoder.field(5, &self.component_edges);
267        encoder.field(6, &self.helper_edges);
268        encoder.field(7, &self.field_witnesses);
269        encoder.field(8, &self.shared_state_acquisitions);
270        encoder.field(9, &self.shared_state_provider_sites);
271    }
272}
273
274/// One standalone helper and its relocation-resolved transitive calls.
275#[derive(Clone, Debug, PartialEq, Eq)]
276pub struct LinkedTransportHelper {
277    /// Exact defining record.
278    pub definition: TransportDefinitionId,
279    /// Stable package/crate/module/item ABI identity emitted beside that exact
280    /// record.
281    pub identity: LinkedSemanticIdentity,
282    /// Producer-validated behavior hash of the complete helper descriptor.
283    pub semantic_hash: SemanticHash,
284    /// Direct helper calls in stable source-edge order.
285    pub helper_edges: Vec<LinkedHelperEdge>,
286    /// Complete embedded payload retained for the semantic ABI adapter.
287    pub payload: Value,
288}
289
290impl CanonicalEncode for LinkedTransportHelper {
291    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
292        encoder.record("LinkedTransportHelper", 4);
293        encoder.field(1, &self.definition);
294        encoder.field(2, &self.identity);
295        encoder.field(3, &self.semantic_hash);
296        encoder.field(4, &self.helper_edges);
297    }
298}
299
300/// One exact SharedState definition after its schema payload has been joined
301/// to the rustc-resolved nominal-type witness record.
302///
303/// This transport-level value intentionally does not decide whether two
304/// definitions are schema-compatible or which components acquire them. Those
305/// are semantic-linker responsibilities.
306#[derive(Clone, Debug, PartialEq, Eq)]
307pub struct LinkedSharedStateDefinition {
308    /// Exact defining record selected from one descriptor-pass Cargo unit.
309    pub definition: TransportDefinitionId,
310    /// Domain-separated hash of the complete SharedState schema payload.
311    pub schema_payload_hash: TransportRecordId,
312    /// Explicit public protocol key carried by the definition payload.
313    pub type_key: String,
314    /// Domain-separated hash of the canonical schema ABI bytes.
315    pub schema_abi_hash: TransportRecordId,
316    /// Complete canonical schema ABI, preserved byte-for-byte.
317    pub schema_abi: Vec<u8>,
318}
319
320impl CanonicalEncode for LinkedSharedStateDefinition {
321    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
322        encoder.record("LinkedSharedStateDefinition", 5);
323        encoder.field(1, &self.definition);
324        encoder.field(2, &self.schema_payload_hash);
325        encoder.field(3, &self.type_key);
326        encoder.field(4, &self.schema_abi_hash);
327        encoder.field(5, &self.schema_abi);
328    }
329}
330
331/// One exact component-local `rsjs::shared::<T>()` acquisition after rustc
332/// relocation resolution.
333///
334/// `source_unit` plus `source_edge` is the complete transport identity of the
335/// acquisition. The owning component is deliberately unresolved here: the
336/// transport must not reconstruct ownership from Rust path text.
337#[derive(Clone, Debug, PartialEq, Eq)]
338pub struct LinkedSharedStateAcquisition {
339    /// Descriptor-pass Cargo unit containing the acquisition record.
340    pub source_unit: CargoUnitId,
341    /// Stable component-local source-edge identifier.
342    pub source_edge: TransportRecordId,
343    /// Exact SharedState definition selected by the relocation.
344    pub target: TransportDefinitionId,
345}
346
347impl CanonicalEncode for LinkedSharedStateAcquisition {
348    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
349        encoder.record("LinkedSharedStateAcquisition", 3);
350        encoder.field(1, &self.source_unit);
351        encoder.field(2, &self.source_edge);
352        encoder.field(3, &self.target);
353    }
354}
355
356#[derive(Clone, Debug, PartialEq, Eq)]
357struct ResolvedTransportPayload {
358    schema_version: u16,
359    components: Vec<LinkedTransportComponent>,
360    helpers: Vec<LinkedTransportHelper>,
361    shared_state_definitions: Vec<LinkedSharedStateDefinition>,
362    shared_state_acquisitions: Vec<LinkedSharedStateAcquisition>,
363}
364
365impl CanonicalEncode for ResolvedTransportPayload {
366    fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
367        encoder.record("ResolvedTransportPayload", 5);
368        encoder.field(1, &self.schema_version);
369        encoder.field(2, &self.components);
370        encoder.field(3, &self.helpers);
371        encoder.field(4, &self.shared_state_definitions);
372        encoder.field(5, &self.shared_state_acquisitions);
373    }
374}
375
376/// Root-specific, content-addressed result of exact transport resolution.
377///
378/// This is the deterministic input boundary for conversion into the canonical
379/// component/helper ABI and owner linker. It does not claim that the semantic
380/// component graph has already been composed.
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct TransportLinkPlan {
383    /// Exact pre-link root identity.
384    pub link_unit: LinkUnitId,
385    /// Content identity of this resolved transport graph.
386    pub plan_id: PlanId,
387    /// Hash material used to derive `plan_id`.
388    pub material: LinkPlanMaterial,
389    /// Resolved components in canonical definition order.
390    pub components: Vec<LinkedTransportComponent>,
391    /// Resolved helpers in canonical definition order.
392    pub helpers: Vec<LinkedTransportHelper>,
393    /// SharedState definitions in canonical exact-record order.
394    pub shared_state_definitions: Vec<LinkedSharedStateDefinition>,
395    /// SharedState acquisitions in canonical source-record order.
396    pub shared_state_acquisitions: Vec<LinkedSharedStateAcquisition>,
397}
398
399/// Extract and relocation-link the exact descriptor objects in a root
400/// manifest.
401pub(crate) fn link_transport_manifest(
402    manifest: &LinkUnitManifest,
403    validated_units: &[ValidatedDescriptorUnit],
404) -> Result<TransportLinkPlan, TransportLinkError> {
405    manifest
406        .validate()
407        .map_err(TransportLinkError::InvalidManifest)?;
408    let link_unit = manifest
409        .link_unit_id()
410        .map_err(TransportLinkError::InvalidManifest)?;
411
412    let descriptor_artifacts = descriptor_artifacts(manifest, validated_units)?;
413    let extracted = extract_descriptor_artifacts(&descriptor_artifacts)?;
414
415    let manifest_artifacts = descriptor_artifacts
416        .iter()
417        .map(|evidence| evidence.artifact)
418        .collect::<Vec<_>>();
419    validate_artifact_units(&manifest_artifacts, &extracted)?;
420    resolve_extracted_transport(link_unit, extracted)
421}
422
423#[derive(Clone, Copy)]
424struct DescriptorArtifactEvidence<'a> {
425    artifact: &'a rsjs_ir::build::LinkArtifact,
426    descriptor_hash: [u8; 32],
427}
428
429fn extract_descriptor_artifacts(
430    descriptor_artifacts: &[DescriptorArtifactEvidence<'_>],
431) -> Result<ExtractedTransport, TransportLinkError> {
432    let results = descriptor_artifacts
433        .par_iter()
434        .map(|evidence| {
435            let artifact = evidence.artifact;
436            let path = Path::new(&artifact.path);
437            let bytes =
438                fs::read(path).map_err(|source| TransportLinkError::HashDescriptorObject {
439                    path: path.to_path_buf(),
440                    source,
441                })?;
442            let actual_descriptor = descriptor_object_content_hash_bytes(&bytes);
443            if actual_descriptor != evidence.descriptor_hash {
444                return Err(TransportLinkError::DescriptorObjectIdentityHashMismatch {
445                    path: path.to_path_buf(),
446                    expected: evidence.descriptor_hash,
447                    actual: actual_descriptor,
448                });
449            }
450            let actual = link_artifact_content_hash_bytes(&bytes);
451            if actual != artifact.content {
452                return Err(TransportLinkError::DescriptorObjectHashMismatch {
453                    path: path.to_path_buf(),
454                    expected: artifact.content,
455                    actual,
456                });
457            }
458            ArtifactRecords::extract_exact_bytes(path, &bytes).map_err(Into::into)
459        })
460        .collect::<Vec<Result<_, TransportLinkError>>>();
461    // Indexed parallel iteration preserves input order. Consume the results
462    // sequentially so multiple failures still report the first manifest entry
463    // deterministically.
464    let records = results.into_iter().collect::<Result<Vec<_>, _>>()?;
465    ExtractedTransport::resolve_exact_artifacts(records).map_err(Into::into)
466}
467
468fn descriptor_object_content_hash_bytes(bytes: &[u8]) -> [u8; 32] {
469    let mut hasher = Sha256::new();
470    hasher.update(DESCRIPTOR_OBJECT_HASH_DOMAIN);
471    hasher.update(bytes);
472    hasher.finalize().into()
473}
474
475fn link_artifact_content_hash_bytes(bytes: &[u8]) -> SemanticHash {
476    let mut hasher = Sha256::new();
477    hasher.update(LINK_ARTIFACT_HASH_DOMAIN);
478    hasher.update(bytes);
479    SemanticHash::from_bytes(hasher.finalize().into())
480}
481
482fn descriptor_artifacts<'a>(
483    manifest: &'a LinkUnitManifest,
484    validated_units: &[ValidatedDescriptorUnit],
485) -> Result<Vec<DescriptorArtifactEvidence<'a>>, TransportLinkError> {
486    let mut validated_by_unit = BTreeMap::new();
487    for unit in validated_units {
488        if validated_by_unit
489            .insert(unit.unit.as_abi_id(), unit)
490            .is_some()
491        {
492            return Err(TransportLinkError::DuplicateValidatedDescriptorUnit(
493                unit.unit.as_abi_id(),
494            ));
495        }
496    }
497    let manifest_units = manifest
498        .artifacts
499        .iter()
500        .map(|artifact| artifact.unit)
501        .collect::<BTreeSet<_>>();
502    let mut seen_units = BTreeSet::new();
503    let mut paths = BTreeSet::new();
504    let mut descriptors = Vec::new();
505
506    for artifact in manifest
507        .artifacts
508        .iter()
509        .filter(|artifact| artifact.role == ArtifactRole::DescriptorObject)
510    {
511        let path = Path::new(&artifact.path);
512        if !path.is_absolute() {
513            return Err(TransportLinkError::RelativeDescriptorObject(
514                path.to_path_buf(),
515            ));
516        }
517        if !paths.insert(path.to_path_buf()) {
518            return Err(TransportLinkError::DuplicateDescriptorPath(
519                path.to_path_buf(),
520            ));
521        }
522        if !seen_units.insert(artifact.unit) {
523            return Err(TransportLinkError::DuplicateDescriptorUnit(artifact.unit));
524        }
525        let validated = validated_by_unit.get(&artifact.unit).ok_or(
526            TransportLinkError::MissingValidatedDescriptorUnit(artifact.unit),
527        )?;
528        if validated.descriptor_object != path {
529            return Err(TransportLinkError::ValidatedDescriptorPathMismatch {
530                unit: artifact.unit,
531                manifest: path.to_path_buf(),
532                validated: validated.descriptor_object.clone(),
533            });
534        }
535        let descriptor_hash =
536            parse_hex_32(&validated.sidecar.descriptor_object_hash).map_err(|_| {
537                TransportLinkError::InvalidValidatedDescriptorHash {
538                    unit: artifact.unit,
539                    value: validated.sidecar.descriptor_object_hash.clone(),
540                }
541            })?;
542        descriptors.push(DescriptorArtifactEvidence {
543            artifact,
544            descriptor_hash,
545        });
546    }
547
548    if descriptors.is_empty() {
549        return Err(TransportLinkError::NoDescriptorObjects);
550    }
551    if seen_units != manifest_units {
552        return Err(TransportLinkError::DescriptorUnitSetMismatch {
553            expected: manifest_units,
554            actual: seen_units,
555        });
556    }
557    Ok(descriptors)
558}
559
560fn validate_artifact_units(
561    descriptor_artifacts: &[&rsjs_ir::build::LinkArtifact],
562    extracted: &ExtractedTransport,
563) -> Result<(), TransportLinkError> {
564    if descriptor_artifacts.len() != extracted.artifacts.len() {
565        return Err(TransportLinkError::ExtractionArtifactCount {
566            expected: descriptor_artifacts.len(),
567            actual: extracted.artifacts.len(),
568        });
569    }
570
571    for (artifact, records) in descriptor_artifacts.iter().zip(&extracted.artifacts) {
572        let expected = *artifact.unit.as_bytes();
573        let actual_path = records.artifact_path.as_path();
574        if actual_path != Path::new(&artifact.path) {
575            return Err(TransportLinkError::ExtractionArtifactOrder {
576                expected: PathBuf::from(&artifact.path),
577                actual: records.artifact_path.clone(),
578            });
579        }
580
581        for (kind, unit, location) in
582            records
583                .definitions
584                .iter()
585                .map(|record| {
586                    (
587                        "component definition",
588                        record.cargo_unit_id,
589                        &record.location,
590                    )
591                })
592                .chain(
593                    records
594                        .edges
595                        .iter()
596                        .map(|record| ("component edge", record.cargo_unit_id, &record.location)),
597                )
598                .chain(
599                    records
600                        .component_fields
601                        .iter()
602                        .map(|record| ("component field", record.cargo_unit_id, &record.location)),
603                )
604                .chain(
605                    records.helper_definitions.iter().map(|record| {
606                        ("helper definition", record.cargo_unit_id, &record.location)
607                    }),
608                )
609                .chain(
610                    records
611                        .helper_edges
612                        .iter()
613                        .map(|record| ("helper edge", record.cargo_unit_id, &record.location)),
614                )
615                .chain(records.shared_state_definitions.iter().map(|record| {
616                    (
617                        "SharedState definition",
618                        record.cargo_unit_id,
619                        &record.location,
620                    )
621                }))
622                .chain(records.shared_state_acquisitions.iter().map(|record| {
623                    (
624                        "SharedState acquisition",
625                        record.cargo_unit_id,
626                        &record.location,
627                    )
628                }))
629                .chain(
630                    records.component_payloads.iter().map(|record| {
631                        ("component payload", record.cargo_unit_id, &record.location)
632                    }),
633                )
634                .chain(
635                    records
636                        .helper_payloads
637                        .iter()
638                        .map(|record| ("helper payload", record.cargo_unit_id, &record.location)),
639                )
640                .chain(records.shared_state_payloads.iter().map(|record| {
641                    (
642                        "SharedState schema payload",
643                        record.cargo_unit_id,
644                        &record.location,
645                    )
646                }))
647                .chain(
648                    records.semantic_identities.iter().map(|record| {
649                        ("semantic identity", record.cargo_unit_id, &record.location)
650                    }),
651                )
652        {
653            if unit == UNASSIGNED_CARGO_UNIT_ID {
654                return Err(TransportLinkError::UnassignedCargoUnit {
655                    kind,
656                    location: location.to_string(),
657                });
658            }
659            if unit != expected {
660                return Err(TransportLinkError::CargoUnitMismatch {
661                    kind,
662                    location: location.to_string(),
663                    expected: artifact.unit,
664                    actual: hex_id(&unit),
665                });
666            }
667        }
668    }
669    Ok(())
670}
671
672fn resolve_extracted_transport(
673    link_unit: LinkUnitId,
674    extracted: ExtractedTransport,
675) -> Result<TransportLinkPlan, TransportLinkError> {
676    let (shared_state_definitions, shared_state_acquisitions) =
677        resolve_shared_state_transport(&extracted)?;
678    let shared_state_acquisitions_by_source =
679        unique_shared_state_acquisitions(&shared_state_acquisitions)?;
680    let component_edges = unique_component_edges(&extracted)?;
681    let component_fields = unique_component_fields(&extracted)?;
682    let helper_edges = unique_helper_edges(&extracted)?;
683    let mut claimed_components = BTreeSet::new();
684    let mut claimed_fields = BTreeSet::new();
685    let mut claimed_helpers = BTreeSet::new();
686    let mut claimed_shared_state_acquisitions = BTreeSet::new();
687
688    let mut components = extracted
689        .resolved_definitions
690        .iter()
691        .map(|definition| {
692            resolve_component(
693                definition,
694                &component_edges,
695                &component_fields,
696                &helper_edges,
697                &shared_state_acquisitions_by_source,
698                &mut claimed_components,
699                &mut claimed_fields,
700                &mut claimed_helpers,
701                &mut claimed_shared_state_acquisitions,
702            )
703        })
704        .collect::<Result<Vec<_>, _>>()?;
705    components.sort_by_key(|component| component.definition);
706
707    let mut helpers = extracted
708        .resolved_helper_definitions
709        .iter()
710        .map(|definition| resolve_helper(definition, &helper_edges, &mut claimed_helpers))
711        .collect::<Result<Vec<_>, _>>()?;
712    helpers.sort_by_key(|helper| helper.definition);
713
714    let all_component_edges = component_edges.keys().copied().collect::<BTreeSet<_>>();
715    if claimed_components != all_component_edges {
716        return Err(TransportLinkError::UnclaimedComponentEdges(
717            set_difference_hex(&all_component_edges, &claimed_components),
718        ));
719    }
720    let all_component_fields = component_fields.keys().copied().collect::<BTreeSet<_>>();
721    if claimed_fields != all_component_fields {
722        return Err(TransportLinkError::UnclaimedComponentFields(
723            set_difference_hex(&all_component_fields, &claimed_fields),
724        ));
725    }
726    let all_helper_edges = helper_edges.keys().copied().collect::<BTreeSet<_>>();
727    if claimed_helpers != all_helper_edges {
728        return Err(TransportLinkError::UnclaimedHelperEdges(
729            set_difference_hex(&all_helper_edges, &claimed_helpers),
730        ));
731    }
732    let all_shared_state_acquisitions = shared_state_acquisitions_by_source
733        .keys()
734        .copied()
735        .collect::<BTreeSet<_>>();
736    if claimed_shared_state_acquisitions != all_shared_state_acquisitions {
737        return Err(TransportLinkError::UnclaimedSharedStateAcquisitions(
738            set_difference_hex(
739                &all_shared_state_acquisitions,
740                &claimed_shared_state_acquisitions,
741            ),
742        ));
743    }
744
745    let payload = ResolvedTransportPayload {
746        schema_version: TRANSPORT_LINK_SCHEMA_VERSION,
747        components: components.clone(),
748        helpers: helpers.clone(),
749        shared_state_definitions: shared_state_definitions.clone(),
750        shared_state_acquisitions: shared_state_acquisitions.clone(),
751    };
752    let payload_hash = SemanticHash::derive(&payload);
753    let material = LinkPlanMaterial {
754        link_unit,
755        component_descriptors: components
756            .iter()
757            .map(|component| component.semantic_hash)
758            .collect(),
759        helper_descriptors: helpers.iter().map(|helper| helper.semantic_hash).collect(),
760        payload: payload_hash,
761    };
762    let plan_id = material.plan_id();
763
764    Ok(TransportLinkPlan {
765        link_unit,
766        plan_id,
767        material,
768        components,
769        helpers,
770        shared_state_definitions,
771        shared_state_acquisitions,
772    })
773}
774
775type SourceEdgeKey = (TransportRecordId, TransportRecordId);
776
777fn unique_shared_state_acquisitions(
778    acquisitions: &[LinkedSharedStateAcquisition],
779) -> Result<BTreeMap<SourceEdgeKey, &LinkedSharedStateAcquisition>, TransportLinkError> {
780    let mut by_source = BTreeMap::new();
781    for acquisition in acquisitions {
782        let key = (*acquisition.source_unit.as_bytes(), acquisition.source_edge);
783        if by_source.insert(key, acquisition).is_some() {
784            return Err(TransportLinkError::DuplicateSharedStateAcquisition {
785                unit: hex_id(&key.0),
786                source_edge: hex_id(&key.1),
787            });
788        }
789    }
790    Ok(by_source)
791}
792
793fn resolve_shared_state_transport(
794    extracted: &ExtractedTransport,
795) -> Result<
796    (
797        Vec<LinkedSharedStateDefinition>,
798        Vec<LinkedSharedStateAcquisition>,
799    ),
800    TransportLinkError,
801> {
802    let mut extracted_definition_keys = extracted
803        .shared_state_definitions
804        .iter()
805        .map(|definition| (definition.cargo_unit_id, definition.shared_state_record_id))
806        .collect::<Vec<_>>();
807    let mut resolved_definition_keys = extracted
808        .resolved_shared_state_definitions
809        .iter()
810        .map(|definition| {
811            (
812                definition.definition.cargo_unit_id,
813                definition.definition.shared_state_record_id,
814            )
815        })
816        .collect::<Vec<_>>();
817    extracted_definition_keys.sort_unstable();
818    resolved_definition_keys.sort_unstable();
819    if extracted_definition_keys != resolved_definition_keys {
820        return Err(TransportLinkError::SharedStateResolutionMismatch {
821            kind: "definition",
822            extracted: source_keys_hex(&extracted_definition_keys),
823            resolved: source_keys_hex(&resolved_definition_keys),
824        });
825    }
826
827    let mut definitions = extracted
828        .resolved_shared_state_definitions
829        .iter()
830        .map(|definition| LinkedSharedStateDefinition {
831            definition: TransportDefinitionId {
832                unit: CargoUnitId::from_bytes(definition.definition.cargo_unit_id),
833                record: definition.definition.shared_state_record_id,
834            },
835            schema_payload_hash: definition.payload.semantic_payload_hash,
836            type_key: definition.payload.type_key.clone(),
837            schema_abi_hash: definition.payload.schema_abi_hash,
838            schema_abi: definition.payload.schema_abi.clone(),
839        })
840        .collect::<Vec<_>>();
841    definitions.sort_by_key(|definition| definition.definition);
842    let definition_ids = definitions
843        .iter()
844        .map(|definition| definition.definition)
845        .collect::<BTreeSet<_>>();
846
847    let mut extracted_acquisition_keys = extracted
848        .shared_state_acquisitions
849        .iter()
850        .map(|acquisition| (acquisition.cargo_unit_id, acquisition.source_edge_id))
851        .collect::<Vec<_>>();
852    let mut resolved_acquisition_keys = extracted
853        .resolved_shared_state_acquisitions
854        .iter()
855        .map(|acquisition| {
856            (
857                acquisition.acquisition.cargo_unit_id,
858                acquisition.acquisition.source_edge_id,
859            )
860        })
861        .collect::<Vec<_>>();
862    extracted_acquisition_keys.sort_unstable();
863    resolved_acquisition_keys.sort_unstable();
864    if extracted_acquisition_keys != resolved_acquisition_keys {
865        return Err(TransportLinkError::SharedStateResolutionMismatch {
866            kind: "acquisition",
867            extracted: source_keys_hex(&extracted_acquisition_keys),
868            resolved: source_keys_hex(&resolved_acquisition_keys),
869        });
870    }
871
872    let mut acquisitions = Vec::with_capacity(extracted.resolved_shared_state_acquisitions.len());
873    for acquisition in &extracted.resolved_shared_state_acquisitions {
874        let target = TransportDefinitionId {
875            unit: CargoUnitId::from_bytes(acquisition.definition.cargo_unit_id),
876            record: acquisition.definition.shared_state_record_id,
877        };
878        if !definition_ids.contains(&target) {
879            return Err(TransportLinkError::MissingSharedStateAcquisitionTarget {
880                source_unit: CargoUnitId::from_bytes(acquisition.acquisition.cargo_unit_id),
881                source_edge: hex_id(&acquisition.acquisition.source_edge_id),
882                target,
883            });
884        }
885        acquisitions.push(LinkedSharedStateAcquisition {
886            source_unit: CargoUnitId::from_bytes(acquisition.acquisition.cargo_unit_id),
887            source_edge: acquisition.acquisition.source_edge_id,
888            target,
889        });
890    }
891    acquisitions.sort_by_key(|acquisition| (acquisition.source_unit, acquisition.source_edge));
892
893    Ok((definitions, acquisitions))
894}
895
896fn unique_component_edges(
897    extracted: &ExtractedTransport,
898) -> Result<BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedComponentEdge>, TransportLinkError> {
899    let mut edges = BTreeMap::new();
900    for edge in &extracted.resolved_edges {
901        let key = (edge.edge.cargo_unit_id, edge.edge.source_edge_id);
902        if edges.insert(key, edge).is_some() {
903            return Err(TransportLinkError::DuplicateSourceEdge {
904                kind: "component",
905                unit: hex_id(&key.0),
906                source_edge: hex_id(&key.1),
907            });
908        }
909    }
910    Ok(edges)
911}
912
913fn unique_helper_edges(
914    extracted: &ExtractedTransport,
915) -> Result<BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedHelperEdge>, TransportLinkError> {
916    let mut edges = BTreeMap::new();
917    for edge in &extracted.resolved_helper_edges {
918        let key = (edge.edge.cargo_unit_id, edge.edge.source_edge_id);
919        if edges.insert(key, edge).is_some() {
920            return Err(TransportLinkError::DuplicateSourceEdge {
921                kind: "helper",
922                unit: hex_id(&key.0),
923                source_edge: hex_id(&key.1),
924            });
925        }
926    }
927    Ok(edges)
928}
929
930fn unique_component_fields(
931    extracted: &ExtractedTransport,
932) -> Result<BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedComponentField>, TransportLinkError> {
933    let mut fields = BTreeMap::new();
934    for field in &extracted.resolved_component_fields {
935        let key = (field.field.cargo_unit_id, field.field.field_record_id);
936        if fields.insert(key, field).is_some() {
937            return Err(TransportLinkError::DuplicateComponentField {
938                unit: hex_id(&key.0),
939                field_record: hex_id(&key.1),
940            });
941        }
942    }
943    Ok(fields)
944}
945
946fn resolve_component(
947    definition: &ResolvedComponentDefinition,
948    component_edges: &BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedComponentEdge>,
949    component_fields: &BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedComponentField>,
950    helper_edges: &BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedHelperEdge>,
951    shared_state_acquisitions: &BTreeMap<SourceEdgeKey, &LinkedSharedStateAcquisition>,
952    claimed_components: &mut BTreeSet<SourceEdgeKey>,
953    claimed_fields: &mut BTreeSet<SourceEdgeKey>,
954    claimed_helpers: &mut BTreeSet<SourceEdgeKey>,
955    claimed_shared_state_acquisitions: &mut BTreeSet<SourceEdgeKey>,
956) -> Result<LinkedTransportComponent, TransportLinkError> {
957    let payload_value = parse_payload_json("component", &definition.payload.json)?;
958    validate_embedded_semantic_hash("component", &payload_value, COMPONENT_SEMANTIC_DOMAIN)?;
959    let payload: ComponentPayload =
960        serde_json::from_value(payload_value.clone()).map_err(|source| {
961            TransportLinkError::InvalidPayloadSchema {
962                kind: "component",
963                location: definition.payload.location.to_string(),
964                source,
965            }
966        })?;
967    if payload.format != COMPONENT_PAYLOAD_FORMAT
968        || payload.schema_version != COMPONENT_PAYLOAD_SCHEMA
969    {
970        return Err(TransportLinkError::UnsupportedPayload {
971            kind: "component",
972            format: payload.format,
973            schema_version: payload.schema_version,
974        });
975    }
976    validate_component_descriptor(&payload.component_descriptor)?;
977
978    let expected_record = definition.definition.component_record_id;
979    let payload_record = parse_record_id(
980        "component transport definition_record_id",
981        &payload.transport.definition_record_id,
982    )?;
983    if payload_record != expected_record {
984        return Err(TransportLinkError::PayloadDefinitionMismatch {
985            kind: "component",
986            expected: hex_id(&expected_record),
987            actual: hex_id(&payload_record),
988        });
989    }
990    let fingerprint_record = component_record_id(&payload.transport.component_input_fingerprint);
991    if fingerprint_record != expected_record {
992        return Err(TransportLinkError::PayloadDefinitionMismatch {
993            kind: "component fingerprint-derived",
994            expected: hex_id(&expected_record),
995            actual: hex_id(&fingerprint_record),
996        });
997    }
998    let unit = definition.definition.cargo_unit_id;
999    let definition_id = TransportDefinitionId {
1000        unit: CargoUnitId::from_bytes(unit),
1001        record: expected_record,
1002    };
1003    validate_component_shared_state_claim_shape(
1004        definition_id,
1005        &payload.component_descriptor,
1006        &payload.transport.shared_state_acquisitions,
1007    )?;
1008
1009    let mut linked_fields = Vec::new();
1010    for (ordinal, field) in payload
1011        .transport
1012        .component_field_witnesses
1013        .iter()
1014        .enumerate()
1015    {
1016        let expected_field_id =
1017            u32::try_from(ordinal).map_err(|_| TransportLinkError::ComponentFieldIdOverflow)?;
1018        if field.field_id != expected_field_id {
1019            return Err(TransportLinkError::NonDenseComponentFieldClaims {
1020                component: definition_id,
1021                expected: expected_field_id,
1022                actual: field.field_id,
1023            });
1024        }
1025        let claimed_field_record = validate_component_field_claim_record_id(
1026            &payload.transport.component_input_fingerprint,
1027            definition_id,
1028            field,
1029        )?;
1030        linked_fields.push(link_component_field_record(
1031            unit,
1032            claimed_field_record,
1033            definition_id,
1034            &field.field_name,
1035            component_fields,
1036            claimed_fields,
1037        )?);
1038    }
1039
1040    let mut linked_shared_state_acquisitions = Vec::new();
1041    for (ordinal, acquisition) in payload
1042        .transport
1043        .shared_state_acquisitions
1044        .iter()
1045        .enumerate()
1046    {
1047        let expected_store_id =
1048            u32::try_from(ordinal).map_err(|_| TransportLinkError::SharedStateStoreIdOverflow)?;
1049        if acquisition.store_id != expected_store_id {
1050            return Err(TransportLinkError::NonDenseSharedStateAcquisitionClaims {
1051                component: definition_id,
1052                expected: expected_store_id,
1053                actual: acquisition.store_id,
1054            });
1055        }
1056        let source_edge = validate_shared_state_acquisition_claim_record_id(
1057            &payload.transport.component_input_fingerprint,
1058            definition_id,
1059            acquisition,
1060        )?;
1061        linked_shared_state_acquisitions.push(link_shared_state_acquisition_record(
1062            unit,
1063            definition_id,
1064            acquisition.store_id,
1065            source_edge,
1066            shared_state_acquisitions,
1067            claimed_shared_state_acquisitions,
1068        )?);
1069    }
1070
1071    let mut linked_components = Vec::new();
1072    for edge in &payload.transport.direct_component_edges {
1073        if edge.identity_authority != "rustc_component_witness_relocation" {
1074            return Err(TransportLinkError::InvalidIdentityAuthority {
1075                kind: "component",
1076                authority: edge.identity_authority.clone(),
1077            });
1078        }
1079        let source_edge = parse_record_id("component source_edge_id", &edge.source_edge_id)?;
1080        let key = (unit, source_edge);
1081        if !claimed_components.insert(key) {
1082            return Err(TransportLinkError::SourceEdgeClaimedTwice {
1083                kind: "component",
1084                unit: hex_id(&unit),
1085                source_edge: hex_id(&source_edge),
1086            });
1087        }
1088        let resolved =
1089            component_edges
1090                .get(&key)
1091                .ok_or_else(|| TransportLinkError::MissingSourceEdge {
1092                    kind: "component",
1093                    unit: hex_id(&unit),
1094                    source_edge: hex_id(&source_edge),
1095                })?;
1096        linked_components.push(LinkedComponentEdge {
1097            source_edge,
1098            target: TransportDefinitionId {
1099                unit: CargoUnitId::from_bytes(resolved.definition.cargo_unit_id),
1100                record: resolved.definition.component_record_id,
1101            },
1102        });
1103    }
1104    linked_components.sort_by_key(|edge| edge.source_edge);
1105
1106    let linked_shared_state_provider_sites = validate_and_link_shared_state_provider_sites(
1107        definition_id,
1108        unit,
1109        &payload.transport.component_input_fingerprint,
1110        &payload.component_descriptor,
1111        &payload.transport.shared_state_provider_sites,
1112        &payload.transport.direct_component_edges,
1113        &linked_components,
1114        shared_state_acquisitions,
1115        claimed_shared_state_acquisitions,
1116    )?;
1117
1118    let mut linked_helpers = Vec::new();
1119    for edge in &payload.transport.reachable_helper_edges {
1120        if edge.identity_authority != "rustc_function_relocation" {
1121            return Err(TransportLinkError::InvalidIdentityAuthority {
1122                kind: "helper",
1123                authority: edge.identity_authority.clone(),
1124            });
1125        }
1126        let source_edge = parse_record_id("component helper source_edge_id", &edge.source_edge_id)?;
1127        let key = (unit, source_edge);
1128        if !claimed_helpers.insert(key) {
1129            return Err(TransportLinkError::SourceEdgeClaimedTwice {
1130                kind: "helper",
1131                unit: hex_id(&unit),
1132                source_edge: hex_id(&source_edge),
1133            });
1134        }
1135        let resolved =
1136            helper_edges
1137                .get(&key)
1138                .ok_or_else(|| TransportLinkError::MissingSourceEdge {
1139                    kind: "helper",
1140                    unit: hex_id(&unit),
1141                    source_edge: hex_id(&source_edge),
1142                })?;
1143        linked_helpers.push(LinkedHelperEdge {
1144            source_edge,
1145            target: TransportDefinitionId {
1146                unit: CargoUnitId::from_bytes(resolved.definition.cargo_unit_id),
1147                record: resolved.definition.helper_record_id,
1148            },
1149        });
1150    }
1151    linked_helpers.sort_by_key(|edge| edge.source_edge);
1152
1153    let semantic_hash = parse_semantic_hash(&payload.semantic_hash)?;
1154    Ok(LinkedTransportComponent {
1155        definition: definition_id,
1156        identity: LinkedSemanticIdentity::from(&definition.identity),
1157        semantic_hash,
1158        component_abi: definition.definition.component_abi,
1159        component_edges: linked_components,
1160        helper_edges: linked_helpers,
1161        field_witnesses: linked_fields,
1162        shared_state_acquisitions: linked_shared_state_acquisitions,
1163        shared_state_provider_sites: linked_shared_state_provider_sites,
1164        payload: payload_value,
1165    })
1166}
1167
1168fn validate_component_shared_state_claim_shape(
1169    component: TransportDefinitionId,
1170    descriptor: &Value,
1171    claims: &[ComponentSharedStateAcquisitionClaim],
1172) -> Result<(), TransportLinkError> {
1173    let stores = descriptor
1174        .as_object()
1175        .and_then(|descriptor| descriptor.get("shared_stores"))
1176        .and_then(Value::as_array)
1177        .ok_or(TransportLinkError::InvalidSharedStateDescriptorStores {
1178            component,
1179            reason: "component_descriptor.shared_stores must be an array".to_owned(),
1180        })?;
1181    if stores.len() != claims.len() {
1182        return Err(
1183            TransportLinkError::SharedStateAcquisitionClaimCountMismatch {
1184                component,
1185                stores: stores.len(),
1186                claims: claims.len(),
1187            },
1188        );
1189    }
1190    for (ordinal, store) in stores.iter().enumerate() {
1191        let actual = store
1192            .as_object()
1193            .and_then(|store| store.get("id"))
1194            .and_then(Value::as_u64)
1195            .ok_or_else(|| TransportLinkError::InvalidSharedStateDescriptorStores {
1196                component,
1197                reason: format!("shared_stores[{ordinal}].id must be an unsigned integer"),
1198            })?;
1199        let expected = u64::try_from(ordinal).map_err(|_| {
1200            TransportLinkError::InvalidSharedStateDescriptorStores {
1201                component,
1202                reason: "SharedState descriptor store count exceeds u64".to_owned(),
1203            }
1204        })?;
1205        if actual != expected {
1206            return Err(TransportLinkError::InvalidSharedStateDescriptorStores {
1207                component,
1208                reason: format!(
1209                    "shared_stores[{ordinal}].id is {actual}, expected dense store id {expected}"
1210                ),
1211            });
1212        }
1213    }
1214    Ok(())
1215}
1216
1217pub(crate) fn shared_state_acquisition_source_edge_id(
1218    input_fingerprint: &str,
1219    store_id: u32,
1220) -> TransportRecordId {
1221    let mut hasher = Sha256::new();
1222    hasher.update(b"proa.rsjs.transport.shared-state-acquisition.v1\0");
1223    hasher.update(input_fingerprint.as_bytes());
1224    hasher.update(store_id.to_le_bytes());
1225    hasher.finalize().into()
1226}
1227
1228fn validate_shared_state_acquisition_claim_record_id(
1229    input_fingerprint: &str,
1230    component: TransportDefinitionId,
1231    acquisition: &ComponentSharedStateAcquisitionClaim,
1232) -> Result<TransportRecordId, TransportLinkError> {
1233    let actual = parse_record_id(
1234        "component SharedState acquisition source_edge_id",
1235        &acquisition.source_edge_id,
1236    )?;
1237    let expected = shared_state_acquisition_source_edge_id(input_fingerprint, acquisition.store_id);
1238    if actual != expected {
1239        return Err(TransportLinkError::SharedStateAcquisitionRecordIdMismatch {
1240            component,
1241            store_id: acquisition.store_id,
1242            expected: hex_id(&expected),
1243            actual: hex_id(&actual),
1244        });
1245    }
1246    Ok(actual)
1247}
1248
1249fn link_shared_state_acquisition_record(
1250    unit: TransportRecordId,
1251    component: TransportDefinitionId,
1252    store_id: u32,
1253    source_edge: TransportRecordId,
1254    acquisitions: &BTreeMap<SourceEdgeKey, &LinkedSharedStateAcquisition>,
1255    claimed: &mut BTreeSet<SourceEdgeKey>,
1256) -> Result<LinkedComponentSharedStateAcquisition, TransportLinkError> {
1257    let key = (unit, source_edge);
1258    if !claimed.insert(key) {
1259        return Err(TransportLinkError::SharedStateAcquisitionClaimedTwice {
1260            unit: hex_id(&unit),
1261            source_edge: hex_id(&source_edge),
1262        });
1263    }
1264    let resolved = acquisitions.get(&key).ok_or_else(|| {
1265        TransportLinkError::MissingSharedStateAcquisition {
1266            component,
1267            store_id,
1268            unit: hex_id(&unit),
1269            source_edge: hex_id(&source_edge),
1270        }
1271    })?;
1272    Ok(LinkedComponentSharedStateAcquisition {
1273        store_id,
1274        source_edge,
1275        target: resolved.target,
1276    })
1277}
1278
1279#[allow(clippy::too_many_arguments)]
1280fn validate_and_link_shared_state_provider_sites(
1281    component: TransportDefinitionId,
1282    unit: TransportRecordId,
1283    input_fingerprint: &str,
1284    descriptor: &Value,
1285    claims: &[ComponentSharedStateProviderSiteClaim],
1286    direct_edges: &[ComponentSourceEdge],
1287    linked_component_edges: &[LinkedComponentEdge],
1288    acquisitions: &BTreeMap<SourceEdgeKey, &LinkedSharedStateAcquisition>,
1289    claimed_acquisitions: &mut BTreeSet<SourceEdgeKey>,
1290) -> Result<Vec<LinkedComponentSharedStateProviderSite>, TransportLinkError> {
1291    let descriptor_sites = descriptor
1292        .as_object()
1293        .and_then(|descriptor| descriptor.get("shared_state_provider_sites"))
1294        .and_then(Value::as_array)
1295        .ok_or_else(|| TransportLinkError::InvalidSharedStateProviderSites {
1296            component,
1297            reason: "component_descriptor.shared_state_provider_sites must be an array".to_owned(),
1298        })?
1299        .iter()
1300        .enumerate()
1301        .map(|(ordinal, value)| {
1302            serde_json::from_value::<DescriptorSharedStateProviderSite>(value.clone()).map_err(
1303                |error| TransportLinkError::InvalidSharedStateProviderSites {
1304                    component,
1305                    reason: format!(
1306                        "component_descriptor.shared_state_provider_sites[{ordinal}] is invalid: \
1307                         {error}"
1308                    ),
1309                },
1310            )
1311        })
1312        .collect::<Result<Vec<_>, _>>()?;
1313
1314    if descriptor_sites.len() != claims.len() {
1315        return Err(
1316            TransportLinkError::SharedStateProviderSiteClaimCountMismatch {
1317                component,
1318                descriptor_sites: descriptor_sites.len(),
1319                claims: claims.len(),
1320            },
1321        );
1322    }
1323
1324    let mut claimed_children = BTreeSet::new();
1325    let mut linked_sites = Vec::with_capacity(claims.len());
1326    for (ordinal, (claim, descriptor_site)) in
1327        claims.iter().zip(descriptor_sites.iter()).enumerate()
1328    {
1329        let expected_id = u32::try_from(ordinal)
1330            .map_err(|_| TransportLinkError::SharedStateProviderSiteIdOverflow)?;
1331        if claim.provider_site_id != expected_id {
1332            return Err(TransportLinkError::NonDenseSharedStateProviderSiteClaims {
1333                component,
1334                expected: expected_id,
1335                actual: claim.provider_site_id,
1336            });
1337        }
1338        if descriptor_site.id != expected_id {
1339            return Err(TransportLinkError::InvalidSharedStateProviderSites {
1340                component,
1341                reason: format!(
1342                    "shared_state_provider_sites[{ordinal}].id is {}, expected dense site id \
1343                     {expected_id}",
1344                    descriptor_site.id
1345                ),
1346            });
1347        }
1348        if claim.identity_authority != "rustc_shared_state_witness_relocation" {
1349            return Err(TransportLinkError::InvalidIdentityAuthority {
1350                kind: "SharedState provider",
1351                authority: claim.identity_authority.clone(),
1352            });
1353        }
1354        if claim.topology != "static_single_wrapperless" {
1355            return Err(TransportLinkError::InvalidSharedStateProviderSite {
1356                component,
1357                provider_site_id: claim.provider_site_id,
1358                reason: format!("unsupported topology `{}`", claim.topology),
1359            });
1360        }
1361        if !claimed_children.insert(claim.child_edge_local_ordinal) {
1362            return Err(TransportLinkError::SharedStateProviderChildClaimedTwice {
1363                component,
1364                child_edge: claim.child_edge_local_ordinal,
1365            });
1366        }
1367
1368        let child = direct_edges
1369            .iter()
1370            .find(|edge| edge.local_ordinal == claim.child_edge_local_ordinal)
1371            .ok_or_else(|| TransportLinkError::InvalidSharedStateProviderSite {
1372                component,
1373                provider_site_id: claim.provider_site_id,
1374                reason: format!(
1375                    "child edge {} is absent from direct_component_edges",
1376                    claim.child_edge_local_ordinal
1377                ),
1378            })?;
1379        if child.boundary != "composed"
1380            || !matches!(child.lifecycle, ComponentSourceLifecycle::StaticSingle)
1381            || child.has_rest
1382            || child.site_node != claim.site_node
1383            || child.fields.iter().any(|field| {
1384                !matches!(
1385                    field.binding.kind.as_str(),
1386                    "server_only" | "static_callback"
1387                )
1388            })
1389        {
1390            return Err(TransportLinkError::InvalidSharedStateProviderSite {
1391                component,
1392                provider_site_id: claim.provider_site_id,
1393                reason: "provider child must be one wrapperless static composed edge at the same \
1394                         server node with only server/static-callback fields"
1395                    .to_owned(),
1396            });
1397        }
1398
1399        let child_source_edge = parse_record_id(
1400            "SharedState provider child_source_edge_id",
1401            &claim.child_source_edge_id,
1402        )?;
1403        let direct_child_source_edge =
1404            parse_record_id("component source_edge_id", &child.source_edge_id)?;
1405        if child_source_edge != direct_child_source_edge {
1406            return Err(TransportLinkError::SharedStateProviderChildEdgeMismatch {
1407                component,
1408                provider_site_id: claim.provider_site_id,
1409                expected: hex_id(&direct_child_source_edge),
1410                actual: hex_id(&child_source_edge),
1411            });
1412        }
1413        let linked_child = linked_component_edges
1414            .iter()
1415            .find(|edge| edge.source_edge == child_source_edge)
1416            .ok_or_else(|| TransportLinkError::InvalidSharedStateProviderSite {
1417                component,
1418                provider_site_id: claim.provider_site_id,
1419                reason: format!(
1420                    "child source edge {} did not resolve through the component relocation set",
1421                    hex_id(&child_source_edge)
1422                ),
1423            })?;
1424
1425        if descriptor_site.child_edge != claim.child_edge_local_ordinal
1426            || descriptor_site.site_node != claim.site_node
1427            || descriptor_site.state_rust_type != claim.state_rust_type
1428            || descriptor_site.topology != claim.topology
1429            || descriptor_site.source_anchor.start_line != claim.source_anchor.line
1430            || descriptor_site.source_anchor.start_column != claim.source_anchor.column
1431        {
1432            return Err(
1433                TransportLinkError::SharedStateProviderDescriptorClaimMismatch {
1434                    component,
1435                    provider_site_id: claim.provider_site_id,
1436                },
1437            );
1438        }
1439
1440        let expected_source_edge = shared_state_provider_source_edge_id(
1441            input_fingerprint,
1442            claim.provider_site_id,
1443            &TransportSharedStateProviderSite {
1444                site_node: claim.site_node,
1445                child_edge_ordinal: claim.child_edge_local_ordinal,
1446                child_source_edge_id: child_source_edge,
1447            },
1448        );
1449        let source_edge =
1450            parse_record_id("SharedState provider source_edge_id", &claim.source_edge_id)?;
1451        if source_edge != expected_source_edge {
1452            return Err(TransportLinkError::SharedStateProviderRecordIdMismatch {
1453                component,
1454                provider_site_id: claim.provider_site_id,
1455                expected: hex_id(&expected_source_edge),
1456                actual: hex_id(&source_edge),
1457            });
1458        }
1459
1460        let key = (unit, source_edge);
1461        if !claimed_acquisitions.insert(key) {
1462            return Err(TransportLinkError::SharedStateProviderWitnessClaimedTwice {
1463                unit: hex_id(&unit),
1464                source_edge: hex_id(&source_edge),
1465            });
1466        }
1467        let resolved = acquisitions.get(&key).ok_or_else(|| {
1468            TransportLinkError::MissingSharedStateProviderWitness {
1469                component,
1470                provider_site_id: claim.provider_site_id,
1471                unit: hex_id(&unit),
1472                source_edge: hex_id(&source_edge),
1473            }
1474        })?;
1475        linked_sites.push(LinkedComponentSharedStateProviderSite {
1476            provider_site_id: claim.provider_site_id,
1477            source_edge,
1478            target: resolved.target,
1479            child_edge_local_ordinal: claim.child_edge_local_ordinal,
1480            child_source_edge,
1481            child_target: linked_child.target,
1482            site_node: claim.site_node,
1483        });
1484    }
1485    Ok(linked_sites)
1486}
1487
1488fn validate_component_field_claim_record_id(
1489    input_fingerprint: &str,
1490    component: TransportDefinitionId,
1491    field: &ComponentFieldWitnessClaim,
1492) -> Result<TransportRecordId, TransportLinkError> {
1493    let (role, callback_shape) = parse_component_field_role_shape(field)?;
1494    let expected = component_field_record_id(
1495        input_fingerprint,
1496        field.field_id,
1497        field.crossing_hook_id,
1498        role,
1499        callback_shape,
1500    );
1501    let actual = parse_record_id("component field field_record_id", &field.field_record_id)?;
1502    if actual != expected {
1503        return Err(TransportLinkError::ComponentFieldRecordIdMismatch {
1504            component,
1505            field: field.field_name.clone(),
1506            expected: hex_id(&expected),
1507            actual: hex_id(&actual),
1508        });
1509    }
1510    Ok(actual)
1511}
1512
1513fn link_component_field_record(
1514    unit: TransportRecordId,
1515    field_record: TransportRecordId,
1516    expected_target: TransportDefinitionId,
1517    field_name: &str,
1518    component_fields: &BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedComponentField>,
1519    claimed_fields: &mut BTreeSet<SourceEdgeKey>,
1520) -> Result<LinkedComponentFieldWitness, TransportLinkError> {
1521    let key = (unit, field_record);
1522    if !claimed_fields.insert(key) {
1523        return Err(TransportLinkError::ComponentFieldClaimedTwice {
1524            unit: hex_id(&unit),
1525            field_record: hex_id(&field_record),
1526        });
1527    }
1528    let resolved =
1529        component_fields
1530            .get(&key)
1531            .ok_or_else(|| TransportLinkError::MissingComponentField {
1532                unit: hex_id(&unit),
1533                field_record: hex_id(&field_record),
1534            })?;
1535    let target = TransportDefinitionId {
1536        unit: CargoUnitId::from_bytes(resolved.definition.cargo_unit_id),
1537        record: resolved.definition.component_record_id,
1538    };
1539    if target != expected_target {
1540        return Err(TransportLinkError::ComponentFieldTargetMismatch {
1541            field: field_name.to_owned(),
1542            expected: expected_target,
1543            actual: target,
1544        });
1545    }
1546    Ok(LinkedComponentFieldWitness {
1547        field_record,
1548        target,
1549    })
1550}
1551
1552fn parse_component_field_role_shape(
1553    field: &ComponentFieldWitnessClaim,
1554) -> Result<(TransportComponentFieldRole, TransportCallbackShape), TransportLinkError> {
1555    match (field.role.as_str(), field.callback_shape.as_str()) {
1556        ("value", "not_callback") => Ok((
1557            TransportComponentFieldRole::Value,
1558            TransportCallbackShape::NotCallback,
1559        )),
1560        ("callback", "required") => Ok((
1561            TransportComponentFieldRole::Callback,
1562            TransportCallbackShape::Required,
1563        )),
1564        ("callback", "optional") => Ok((
1565            TransportComponentFieldRole::Callback,
1566            TransportCallbackShape::Optional,
1567        )),
1568        ("node_ref", "not_callback") => Ok((
1569            TransportComponentFieldRole::NodeRef,
1570            TransportCallbackShape::NotCallback,
1571        )),
1572        ("deferred_projection", "not_callback") => Ok((
1573            TransportComponentFieldRole::DeferredProjection,
1574            TransportCallbackShape::NotCallback,
1575        )),
1576        _ => Err(TransportLinkError::InvalidComponentFieldRoleShape {
1577            field: field.field_name.clone(),
1578            role: field.role.clone(),
1579            callback_shape: field.callback_shape.clone(),
1580        }),
1581    }
1582}
1583
1584fn resolve_helper(
1585    definition: &ResolvedHelperDefinition,
1586    helper_edges: &BTreeMap<SourceEdgeKey, &rsjs_transport::ResolvedHelperEdge>,
1587    claimed_helpers: &mut BTreeSet<SourceEdgeKey>,
1588) -> Result<LinkedTransportHelper, TransportLinkError> {
1589    let payload_value = parse_payload_json("helper", &definition.payload.json)?;
1590    validate_embedded_semantic_hash("helper", &payload_value, HELPER_SEMANTIC_DOMAIN)?;
1591    let payload: HelperPayload =
1592        serde_json::from_value(payload_value.clone()).map_err(|source| {
1593            TransportLinkError::InvalidPayloadSchema {
1594                kind: "helper",
1595                location: definition.payload.location.to_string(),
1596                source,
1597            }
1598        })?;
1599    if payload.format != HELPER_PAYLOAD_FORMAT || payload.schema_version != 1 {
1600        return Err(TransportLinkError::UnsupportedPayload {
1601            kind: "helper",
1602            format: payload.format,
1603            schema_version: payload.schema_version,
1604        });
1605    }
1606    if payload.body_hir_version != 1
1607        || u32::from(payload.body_ir_version) != CLIENT_IR_SCHEMA_VERSION
1608        || payload.codec_abi_version != 1
1609        || payload.effect_class != "origin_free"
1610    {
1611        return Err(TransportLinkError::UnsupportedHelperAbi {
1612            body_hir: payload.body_hir_version,
1613            body_ir: payload.body_ir_version,
1614            codec: payload.codec_abi_version,
1615            effect_class: payload.effect_class,
1616        });
1617    }
1618
1619    let expected_record = definition.definition.helper_record_id;
1620    let payload_record = parse_record_id("helper defining_record_id", &payload.defining_record_id)?;
1621    if payload_record != expected_record {
1622        return Err(TransportLinkError::PayloadDefinitionMismatch {
1623            kind: "helper",
1624            expected: hex_id(&expected_record),
1625            actual: hex_id(&payload_record),
1626        });
1627    }
1628    let unit = definition.definition.cargo_unit_id;
1629    let mut linked_helpers = Vec::new();
1630    for edge in payload.direct_calls {
1631        let source_edge = parse_record_id("helper source_edge_id", &edge.source_edge_id)?;
1632        let key = (unit, source_edge);
1633        if !claimed_helpers.insert(key) {
1634            return Err(TransportLinkError::SourceEdgeClaimedTwice {
1635                kind: "helper",
1636                unit: hex_id(&unit),
1637                source_edge: hex_id(&source_edge),
1638            });
1639        }
1640        let resolved =
1641            helper_edges
1642                .get(&key)
1643                .ok_or_else(|| TransportLinkError::MissingSourceEdge {
1644                    kind: "helper",
1645                    unit: hex_id(&unit),
1646                    source_edge: hex_id(&source_edge),
1647                })?;
1648        linked_helpers.push(LinkedHelperEdge {
1649            source_edge,
1650            target: TransportDefinitionId {
1651                unit: CargoUnitId::from_bytes(resolved.definition.cargo_unit_id),
1652                record: resolved.definition.helper_record_id,
1653            },
1654        });
1655    }
1656    linked_helpers.sort_by_key(|edge| edge.source_edge);
1657
1658    Ok(LinkedTransportHelper {
1659        definition: TransportDefinitionId {
1660            unit: CargoUnitId::from_bytes(unit),
1661            record: expected_record,
1662        },
1663        identity: LinkedSemanticIdentity::from(&definition.identity),
1664        semantic_hash: parse_semantic_hash(&payload.semantic_hash)?,
1665        helper_edges: linked_helpers,
1666        payload: payload_value,
1667    })
1668}
1669
1670fn parse_payload_json(kind: &'static str, bytes: &[u8]) -> Result<Value, TransportLinkError> {
1671    serde_json::from_slice(bytes)
1672        .map_err(|source| TransportLinkError::ParsePayload { kind, source })
1673}
1674
1675fn validate_component_descriptor(descriptor: &Value) -> Result<(), TransportLinkError> {
1676    let format = descriptor
1677        .get("format")
1678        .and_then(Value::as_str)
1679        .unwrap_or_default();
1680    let schema_version = descriptor
1681        .get("schema_version")
1682        .and_then(Value::as_u64)
1683        .unwrap_or_default();
1684    if format != COMPONENT_DESCRIPTOR_FORMAT
1685        || schema_version != COMPONENT_DESCRIPTOR_SCHEMA_VERSION
1686    {
1687        return Err(TransportLinkError::UnsupportedComponentDescriptor {
1688            format: format.to_string(),
1689            schema_version,
1690        });
1691    }
1692    let descriptor_hash = descriptor
1693        .get("descriptor_hash")
1694        .and_then(Value::as_str)
1695        .ok_or(TransportLinkError::MissingComponentDescriptorHash)?;
1696    parse_semantic_hash(descriptor_hash)?;
1697    Ok(())
1698}
1699
1700fn validate_embedded_semantic_hash(
1701    kind: &'static str,
1702    value: &Value,
1703    domain: &[u8],
1704) -> Result<(), TransportLinkError> {
1705    let recorded = value
1706        .get("semantic_hash")
1707        .and_then(Value::as_str)
1708        .ok_or(TransportLinkError::MissingSemanticHash(kind))?;
1709    let recorded = parse_semantic_hash(recorded)?;
1710    let mut semantic_value = value.clone();
1711    semantic_value
1712        .as_object_mut()
1713        .ok_or(TransportLinkError::PayloadMustBeObject(kind))?
1714        .remove("semantic_hash");
1715    let bytes = canonical_json_bytes(&semantic_value)
1716        .map_err(|source| TransportLinkError::SerializePayload { kind, source })?;
1717    let mut hasher = Sha256::new();
1718    hasher.update(domain);
1719    hasher.update(bytes);
1720    let expected = SemanticHash::from_bytes(hasher.finalize().into());
1721    if expected != recorded {
1722        return Err(TransportLinkError::EmbeddedSemanticHashMismatch {
1723            kind,
1724            expected,
1725            actual: recorded,
1726        });
1727    }
1728    Ok(())
1729}
1730
1731fn parse_semantic_hash(value: &str) -> Result<SemanticHash, TransportLinkError> {
1732    let hex = value
1733        .strip_prefix("sha256:")
1734        .ok_or_else(|| TransportLinkError::InvalidHash(value.to_string()))?;
1735    parse_hex_32(hex)
1736        .map(SemanticHash::from_bytes)
1737        .map_err(|_| TransportLinkError::InvalidHash(value.to_string()))
1738}
1739
1740fn parse_record_id(
1741    field: &'static str,
1742    value: &str,
1743) -> Result<TransportRecordId, TransportLinkError> {
1744    parse_hex_32(value).map_err(|_| TransportLinkError::InvalidRecordId {
1745        field,
1746        value: value.to_string(),
1747    })
1748}
1749
1750fn parse_hex_32(value: &str) -> Result<[u8; 32], ()> {
1751    if value.len() != 64
1752        || !value
1753            .as_bytes()
1754            .iter()
1755            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
1756    {
1757        return Err(());
1758    }
1759    let mut out = [0_u8; 32];
1760    for (index, byte) in out.iter_mut().enumerate() {
1761        let high = hex_nibble(value.as_bytes()[index * 2])?;
1762        let low = hex_nibble(value.as_bytes()[index * 2 + 1])?;
1763        *byte = (high << 4) | low;
1764    }
1765    Ok(out)
1766}
1767
1768fn hex_nibble(byte: u8) -> Result<u8, ()> {
1769    match byte {
1770        b'0'..=b'9' => Ok(byte - b'0'),
1771        b'a'..=b'f' => Ok(byte - b'a' + 10),
1772        _ => Err(()),
1773    }
1774}
1775
1776fn hex_id(id: &[u8; 32]) -> String {
1777    let mut out = String::with_capacity(64);
1778    for byte in id {
1779        use std::fmt::Write as _;
1780        let _ = write!(out, "{byte:02x}");
1781    }
1782    out
1783}
1784
1785fn set_difference_hex(
1786    all: &BTreeSet<SourceEdgeKey>,
1787    claimed: &BTreeSet<SourceEdgeKey>,
1788) -> Vec<String> {
1789    all.difference(claimed)
1790        .map(|(unit, edge)| format!("{}:{}", hex_id(unit), hex_id(edge)))
1791        .collect()
1792}
1793
1794fn source_keys_hex(keys: &[SourceEdgeKey]) -> Vec<String> {
1795    keys.iter()
1796        .map(|(unit, record)| format!("{}:{}", hex_id(unit), hex_id(record)))
1797        .collect()
1798}
1799
1800/// Atomically persist a resolved transport plan under its content `PlanId`.
1801///
1802/// Existing identical content is reused. Existing different content at the
1803/// same strong ID is treated as a fatal collision.
1804pub fn write_content_addressed_transport_plan(
1805    directory: &Path,
1806    plan: &TransportLinkPlan,
1807) -> Result<PathBuf, TransportPlanWriteError> {
1808    if !directory.is_absolute() {
1809        return Err(TransportPlanWriteError::RelativeDirectory(
1810            directory.to_path_buf(),
1811        ));
1812    }
1813    fs::create_dir_all(directory).map_err(|source| TransportPlanWriteError::CreateDirectory {
1814        path: directory.to_path_buf(),
1815        source,
1816    })?;
1817
1818    let value = transport_plan_json(plan);
1819    let bytes = serde_json::to_vec_pretty(&value).map_err(TransportPlanWriteError::Serialize)?;
1820    let path = directory.join(format!("{}.transport-plan.json", plan.plan_id));
1821    if path.exists() {
1822        let existing = fs::read(&path).map_err(|source| TransportPlanWriteError::ReadExisting {
1823            path: path.clone(),
1824            source,
1825        })?;
1826        if existing == bytes {
1827            return Ok(path);
1828        }
1829        return Err(TransportPlanWriteError::ContentCollision {
1830            plan_id: plan.plan_id,
1831            path,
1832        });
1833    }
1834
1835    let nonce = PLAN_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
1836    let temporary = directory.join(format!(
1837        ".{}.{}.{}.tmp",
1838        plan.plan_id,
1839        std::process::id(),
1840        nonce
1841    ));
1842    let mut file = OpenOptions::new()
1843        .write(true)
1844        .create_new(true)
1845        .open(&temporary)
1846        .map_err(|source| TransportPlanWriteError::CreateTemporary {
1847            path: temporary.clone(),
1848            source,
1849        })?;
1850    if let Err(source) = file.write_all(&bytes).and_then(|()| file.sync_all()) {
1851        let _ = fs::remove_file(&temporary);
1852        return Err(TransportPlanWriteError::WriteTemporary {
1853            path: temporary,
1854            source,
1855        });
1856    }
1857    drop(file);
1858    match fs::rename(&temporary, &path) {
1859        Ok(()) => Ok(path),
1860        Err(_source) if path.exists() => {
1861            let _ = fs::remove_file(&temporary);
1862            let existing =
1863                fs::read(&path).map_err(|read_source| TransportPlanWriteError::ReadExisting {
1864                    path: path.clone(),
1865                    source: read_source,
1866                })?;
1867            if existing == bytes {
1868                Ok(path)
1869            } else {
1870                Err(TransportPlanWriteError::ContentCollision {
1871                    plan_id: plan.plan_id,
1872                    path,
1873                })
1874            }
1875        }
1876        Err(source) => {
1877            let _ = fs::remove_file(&temporary);
1878            Err(TransportPlanWriteError::Commit {
1879                from: temporary,
1880                to: path,
1881                source,
1882            })
1883        }
1884    }
1885}
1886
1887pub(crate) fn transport_plan_json(plan: &TransportLinkPlan) -> Value {
1888    let components = plan
1889        .components
1890        .iter()
1891        .map(|component| {
1892            serde_json::json!({
1893                "definition": definition_json(component.definition),
1894                "semantic_identity": semantic_identity_json(&component.identity),
1895                "semantic_hash": format!("sha256:{}", component.semantic_hash),
1896                "component_abi": component_definition_abi_json(component.component_abi),
1897                "component_edges": component.component_edges.iter().map(|edge| {
1898                    serde_json::json!({
1899                        "source_edge_id": hex_id(&edge.source_edge),
1900                        "target": definition_json(edge.target),
1901                    })
1902                }).collect::<Vec<_>>(),
1903                "helper_edges": component.helper_edges.iter().map(|edge| {
1904                    serde_json::json!({
1905                        "source_edge_id": hex_id(&edge.source_edge),
1906                        "target": definition_json(edge.target),
1907                    })
1908                }).collect::<Vec<_>>(),
1909                "field_witnesses": component.field_witnesses.iter().map(|field| {
1910                    serde_json::json!({
1911                        "field_record_id": hex_id(&field.field_record),
1912                        "target": definition_json(field.target),
1913                    })
1914                }).collect::<Vec<_>>(),
1915                "shared_state_acquisitions": component.shared_state_acquisitions.iter().map(|acquisition| {
1916                    serde_json::json!({
1917                        "store_id": acquisition.store_id,
1918                        "source_edge_id": hex_id(&acquisition.source_edge),
1919                        "target": definition_json(acquisition.target),
1920                    })
1921                }).collect::<Vec<_>>(),
1922                "shared_state_provider_sites": component.shared_state_provider_sites.iter().map(|site| {
1923                    serde_json::json!({
1924                        "provider_site_id": site.provider_site_id,
1925                        "source_edge_id": hex_id(&site.source_edge),
1926                        "target": definition_json(site.target),
1927                        "child_edge_local_ordinal": site.child_edge_local_ordinal,
1928                        "child_source_edge_id": hex_id(&site.child_source_edge),
1929                        "child_target": definition_json(site.child_target),
1930                        "site_node": site.site_node,
1931                    })
1932                }).collect::<Vec<_>>(),
1933                "payload": component.payload,
1934            })
1935        })
1936        .collect::<Vec<_>>();
1937    let helpers = plan
1938        .helpers
1939        .iter()
1940        .map(|helper| {
1941            serde_json::json!({
1942                "definition": definition_json(helper.definition),
1943                "semantic_identity": semantic_identity_json(&helper.identity),
1944                "semantic_hash": format!("sha256:{}", helper.semantic_hash),
1945                "helper_edges": helper.helper_edges.iter().map(|edge| {
1946                    serde_json::json!({
1947                        "source_edge_id": hex_id(&edge.source_edge),
1948                        "target": definition_json(edge.target),
1949                    })
1950                }).collect::<Vec<_>>(),
1951                "payload": helper.payload,
1952            })
1953        })
1954        .collect::<Vec<_>>();
1955    let shared_state_definitions = plan
1956        .shared_state_definitions
1957        .iter()
1958        .map(|definition| {
1959            serde_json::json!({
1960                "definition": definition_json(definition.definition),
1961                "schema_payload_hash": format!("sha256:{}", hex_id(&definition.schema_payload_hash)),
1962                "type_key": definition.type_key,
1963                "schema_abi_hash": format!("sha256:{}", hex_id(&definition.schema_abi_hash)),
1964                "schema_abi_hex": hex_bytes(&definition.schema_abi),
1965            })
1966        })
1967        .collect::<Vec<_>>();
1968    let shared_state_acquisitions = plan
1969        .shared_state_acquisitions
1970        .iter()
1971        .map(|acquisition| {
1972            serde_json::json!({
1973                "source": {
1974                    "cargo_unit_id": acquisition.source_unit.to_string(),
1975                    "source_edge_id": hex_id(&acquisition.source_edge),
1976                },
1977                "target": definition_json(acquisition.target),
1978            })
1979        })
1980        .collect::<Vec<_>>();
1981    serde_json::json!({
1982        "format": "proa.rsjs.resolved_transport_plan",
1983        "schema_version": TRANSPORT_LINK_SCHEMA_VERSION,
1984        "link_unit_id": plan.link_unit.to_string(),
1985        "plan_id": plan.plan_id.to_string(),
1986        "payload_hash": format!("sha256:{}", plan.material.payload),
1987        "component_descriptor_hashes": plan.material.component_descriptors.iter()
1988            .map(|hash| format!("sha256:{hash}"))
1989            .collect::<Vec<_>>(),
1990        "helper_descriptor_hashes": plan.material.helper_descriptors.iter()
1991            .map(|hash| format!("sha256:{hash}"))
1992            .collect::<Vec<_>>(),
1993        "components": components,
1994        "helpers": helpers,
1995        "shared_state_definitions": shared_state_definitions,
1996        "shared_state_acquisitions": shared_state_acquisitions,
1997    })
1998}
1999
2000fn definition_json(definition: TransportDefinitionId) -> Value {
2001    serde_json::json!({
2002        "cargo_unit_id": definition.unit.to_string(),
2003        "record_id": hex_id(&definition.record),
2004    })
2005}
2006
2007fn hex_bytes(bytes: &[u8]) -> String {
2008    let mut out = String::with_capacity(bytes.len() * 2);
2009    for byte in bytes {
2010        use std::fmt::Write as _;
2011        let _ = write!(out, "{byte:02x}");
2012    }
2013    out
2014}
2015
2016fn semantic_identity_json(identity: &LinkedSemanticIdentity) -> Value {
2017    serde_json::json!({
2018        "package": identity.package,
2019        "crate": identity.crate_name,
2020        "module_path": identity.module_path,
2021        "item": identity.item,
2022    })
2023}
2024
2025fn component_definition_abi_json(component_abi: ComponentDefinitionAbi) -> Value {
2026    let render_kind = match component_abi.render_kind {
2027        TransportComponentRenderKind::Sync => "sync",
2028        TransportComponentRenderKind::Async => "async",
2029    };
2030    let origin_permission = match component_abi.origin_permission {
2031        TransportComponentOriginPermission::ParticipantOnly => "participant_only",
2032        TransportComponentOriginPermission::OriginCapable => "origin_capable",
2033    };
2034    serde_json::json!({
2035        "flags": component_abi.flags(),
2036        "render_kind": render_kind,
2037        "origin_permission": origin_permission,
2038    })
2039}
2040
2041#[allow(dead_code)]
2042#[derive(Debug, Deserialize)]
2043#[serde(deny_unknown_fields)]
2044struct ComponentPayload {
2045    component_descriptor: Value,
2046    format: String,
2047    schema_version: u16,
2048    semantic_hash: String,
2049    transport: ComponentTransport,
2050}
2051
2052#[allow(dead_code)]
2053#[derive(Debug, Deserialize)]
2054#[serde(deny_unknown_fields)]
2055struct ComponentTransport {
2056    client_value_sources: Value,
2057    component_input_fingerprint: String,
2058    component_field_witnesses: Vec<ComponentFieldWitnessClaim>,
2059    definition_record_id: String,
2060    direct_component_edges: Vec<ComponentSourceEdge>,
2061    hydration_constraint: Value,
2062    reachable_helper_edges: Vec<ComponentHelperSourceEdge>,
2063    shared_state_acquisitions: Vec<ComponentSharedStateAcquisitionClaim>,
2064    shared_state_provider_sites: Vec<ComponentSharedStateProviderSiteClaim>,
2065}
2066
2067#[allow(dead_code)]
2068#[derive(Debug, Deserialize)]
2069#[serde(deny_unknown_fields)]
2070struct ComponentFieldWitnessClaim {
2071    callback_shape: String,
2072    crossing_hook_id: u32,
2073    field_id: u32,
2074    field_name: String,
2075    field_record_id: String,
2076    role: String,
2077}
2078
2079#[allow(dead_code)]
2080#[derive(Debug, Deserialize)]
2081#[serde(deny_unknown_fields)]
2082struct ComponentSourceEdge {
2083    authored_path: String,
2084    boundary: String,
2085    fields: Vec<ComponentSourceField>,
2086    has_rest: bool,
2087    identity_authority: String,
2088    lifecycle: ComponentSourceLifecycle,
2089    local_ordinal: u32,
2090    site_node: u32,
2091    source_anchor: SourceAnchor,
2092    source_edge_id: String,
2093}
2094
2095#[allow(dead_code)]
2096#[derive(Debug, Deserialize)]
2097#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
2098enum ComponentSourceLifecycle {
2099    StaticSingle,
2100    ConditionalSingle {
2101        control: u32,
2102        predicate_expression: u32,
2103        branch: ComponentSourceConditionalBranch,
2104    },
2105    Repeated,
2106    Unknown {
2107        reason: ComponentSourceUnknownLifecycleReason,
2108    },
2109}
2110
2111#[allow(dead_code)]
2112#[derive(Debug, Deserialize)]
2113#[serde(rename_all = "snake_case")]
2114enum ComponentSourceConditionalBranch {
2115    Then,
2116    Else,
2117}
2118
2119#[allow(dead_code)]
2120#[derive(Debug, Deserialize)]
2121#[serde(rename_all = "snake_case")]
2122enum ComponentSourceUnknownLifecycleReason {
2123    NestedConditionals,
2124}
2125
2126#[allow(dead_code)]
2127#[derive(Debug, Deserialize)]
2128#[serde(deny_unknown_fields)]
2129struct ComponentSourceField {
2130    binding: ComponentSourceFieldBinding,
2131    field_ordinal: u32,
2132    name: String,
2133}
2134
2135#[allow(dead_code)]
2136#[derive(Debug, Deserialize)]
2137#[serde(deny_unknown_fields)]
2138struct ComponentSourceFieldBinding {
2139    callback_shape: Option<String>,
2140    handle_kind: Option<String>,
2141    kind: String,
2142    latent_node_ref_id: Option<u32>,
2143    latent_signal_id: Option<u32>,
2144    parent_field_id: Option<u32>,
2145    parent_source: Option<Value>,
2146    proof: String,
2147    source_form: Option<String>,
2148}
2149
2150#[allow(dead_code)]
2151#[derive(Clone, Debug, Deserialize)]
2152#[serde(deny_unknown_fields)]
2153struct SourceAnchor {
2154    column: usize,
2155    line: usize,
2156}
2157
2158#[allow(dead_code)]
2159#[derive(Debug, Deserialize)]
2160#[serde(deny_unknown_fields)]
2161struct ComponentHelperSourceEdge {
2162    authored_path: String,
2163    identity_authority: String,
2164    local_ordinal: u32,
2165    source_edge_id: String,
2166}
2167
2168#[allow(dead_code)]
2169#[derive(Debug, Deserialize)]
2170#[serde(deny_unknown_fields)]
2171struct ComponentSharedStateAcquisitionClaim {
2172    source_edge_id: String,
2173    store_id: u32,
2174}
2175
2176#[allow(dead_code)]
2177#[derive(Clone, Debug, Deserialize)]
2178#[serde(deny_unknown_fields)]
2179struct ComponentSharedStateProviderSiteClaim {
2180    child_edge_local_ordinal: u32,
2181    child_source_edge_id: String,
2182    identity_authority: String,
2183    provider_site_id: u32,
2184    site_node: u32,
2185    source_anchor: SourceAnchor,
2186    source_edge_id: String,
2187    state_rust_type: String,
2188    topology: String,
2189}
2190
2191#[allow(dead_code)]
2192#[derive(Debug, Deserialize)]
2193#[serde(deny_unknown_fields)]
2194struct DescriptorSharedStateProviderSite {
2195    child_edge: u32,
2196    id: u32,
2197    site_node: u32,
2198    source_anchor: DescriptorSourceAnchor,
2199    state_rust_type: String,
2200    topology: String,
2201}
2202
2203#[allow(dead_code)]
2204#[derive(Debug, Deserialize)]
2205#[serde(deny_unknown_fields)]
2206struct DescriptorSourceAnchor {
2207    start_column: usize,
2208    start_line: usize,
2209}
2210
2211#[allow(dead_code)]
2212#[derive(Debug, Deserialize)]
2213#[serde(deny_unknown_fields)]
2214struct HelperPayload {
2215    body_hir: Value,
2216    body_hir_version: u16,
2217    body_ir: Value,
2218    body_ir_version: u16,
2219    codec_abi_version: u16,
2220    defining_record_id: String,
2221    direct_calls: Vec<HelperSourceEdge>,
2222    effect_class: String,
2223    format: String,
2224    provisional_identity: Value,
2225    schema_version: u16,
2226    semantic_hash: String,
2227    signature: Value,
2228}
2229
2230#[allow(dead_code)]
2231#[derive(Debug, Deserialize)]
2232#[serde(deny_unknown_fields)]
2233struct HelperSourceEdge {
2234    authored_path: String,
2235    ordinal: usize,
2236    source_edge_id: String,
2237}
2238
2239/// Exact-artifact extraction or transport-link validation failure.
2240#[derive(Debug, Error)]
2241pub enum TransportLinkError {
2242    /// Root manifest failed canonical validation.
2243    #[error("invalid root link manifest: {0}")]
2244    InvalidManifest(BuildIdentityError),
2245    /// No exact descriptor objects were supplied.
2246    #[error("root link manifest contains no descriptor objects")]
2247    NoDescriptorObjects,
2248    /// Descriptor object path must be exact and absolute.
2249    #[error("descriptor object path must be absolute: `{0}`")]
2250    RelativeDescriptorObject(PathBuf),
2251    /// One exact path appeared more than once.
2252    #[error("descriptor object path appears more than once: `{0}`")]
2253    DuplicateDescriptorPath(PathBuf),
2254    /// Every reachable unit must have exactly one descriptor object.
2255    #[error("Cargo unit {0} has more than one descriptor object")]
2256    DuplicateDescriptorUnit(CargoUnitId),
2257    /// Validated descriptor evidence must be unique by Cargo unit.
2258    #[error("validated descriptor evidence contains Cargo unit {0} more than once")]
2259    DuplicateValidatedDescriptorUnit(CargoUnitId),
2260    /// Every manifest descriptor must retain its authoritative wrapper unit.
2261    #[error("Cargo unit {0} has no validated descriptor evidence")]
2262    MissingValidatedDescriptorUnit(CargoUnitId),
2263    /// Manifest and wrapper evidence must name the same exact object path.
2264    #[error(
2265        "Cargo unit {unit} uses descriptor object `{manifest}` in the manifest but `{validated}` in validated wrapper evidence"
2266    )]
2267    ValidatedDescriptorPathMismatch {
2268        /// Exact Cargo unit.
2269        unit: CargoUnitId,
2270        /// Manifest path.
2271        manifest: PathBuf,
2272        /// Validated wrapper/cache path.
2273        validated: PathBuf,
2274    },
2275    /// Wrapper-validated descriptor hashes are exact lowercase SHA-256 values.
2276    #[error("Cargo unit {unit} has invalid validated descriptor hash `{value}`")]
2277    InvalidValidatedDescriptorHash {
2278        /// Exact Cargo unit.
2279        unit: CargoUnitId,
2280        /// Rejected hash.
2281        value: String,
2282    },
2283    /// Descriptor objects must cover the exact manifest unit set.
2284    #[error("descriptor object unit set differs from the root manifest")]
2285    DescriptorUnitSetMismatch {
2286        /// All units represented by the manifest.
2287        expected: BTreeSet<CargoUnitId>,
2288        /// Units represented by descriptor objects.
2289        actual: BTreeSet<CargoUnitId>,
2290    },
2291    /// Exact artifact could not be hashed.
2292    #[error("failed to hash descriptor object `{path}`: {source}")]
2293    HashDescriptorObject {
2294        /// Exact path.
2295        path: PathBuf,
2296        /// I/O error.
2297        #[source]
2298        source: io::Error,
2299    },
2300    /// Exact bytes changed after manifest construction.
2301    #[error(
2302        "descriptor object `{path}` changed after manifest construction: expected {expected}, actual {actual}"
2303    )]
2304    DescriptorObjectHashMismatch {
2305        /// Exact path.
2306        path: PathBuf,
2307        /// Manifest hash.
2308        expected: SemanticHash,
2309        /// Fresh hash.
2310        actual: SemanticHash,
2311    },
2312    /// Exact extraction bytes must still match the wrapper-authoritative
2313    /// descriptor-domain hash, not only the freshly assembled link manifest.
2314    #[error(
2315        "descriptor object `{path}` no longer matches validated wrapper evidence: expected {expected:?}, actual {actual:?}"
2316    )]
2317    DescriptorObjectIdentityHashMismatch {
2318        /// Exact path.
2319        path: PathBuf,
2320        /// Wrapper/cache descriptor-domain hash.
2321        expected: [u8; 32],
2322        /// Hash of the exact bytes passed to the extractor.
2323        actual: [u8; 32],
2324    },
2325    /// Object/rlib transport extraction failed.
2326    #[error(transparent)]
2327    Extraction(#[from] ExtractionError),
2328    /// Extractor returned a different number of exact inputs.
2329    #[error("extractor returned {actual} artifacts for {expected} descriptor objects")]
2330    ExtractionArtifactCount {
2331        /// Manifest count.
2332        expected: usize,
2333        /// Extracted count.
2334        actual: usize,
2335    },
2336    /// Extractor did not preserve the exact caller order.
2337    #[error("extractor returned `{actual}` where `{expected}` was requested")]
2338    ExtractionArtifactOrder {
2339        /// Exact requested path.
2340        expected: PathBuf,
2341        /// Actual extracted path.
2342        actual: PathBuf,
2343    },
2344    /// Placeholder unit IDs are forbidden after descriptor orchestration.
2345    #[error("unassigned Cargo unit on {kind} record at {location}")]
2346    UnassignedCargoUnit {
2347        /// Record kind.
2348        kind: &'static str,
2349        /// Exact object location.
2350        location: String,
2351    },
2352    /// A record's embedded unit disagreed with the manifest-listed object.
2353    #[error(
2354        "{kind} record at {location} embeds Cargo unit {actual}, expected manifest unit {expected}"
2355    )]
2356    CargoUnitMismatch {
2357        /// Record kind.
2358        kind: &'static str,
2359        /// Exact object location.
2360        location: String,
2361        /// Manifest unit.
2362        expected: CargoUnitId,
2363        /// Embedded lower-case hexadecimal unit.
2364        actual: String,
2365    },
2366    /// Duplicate source-edge ID in one unit.
2367    #[error("duplicate {kind} source edge {unit}:{source_edge}")]
2368    DuplicateSourceEdge {
2369        /// Edge kind.
2370        kind: &'static str,
2371        /// Unit ID.
2372        unit: String,
2373        /// Source edge ID.
2374        source_edge: String,
2375    },
2376    /// Duplicate component-field record in one unit.
2377    #[error("duplicate component field record {unit}:{field_record}")]
2378    DuplicateComponentField {
2379        /// Descriptor-pass Cargo unit.
2380        unit: String,
2381        /// Field record ID.
2382        field_record: String,
2383    },
2384    /// Two extracted SharedState acquisition records reused one source edge.
2385    #[error("duplicate SharedState acquisition record {unit}:{source_edge}")]
2386    DuplicateSharedStateAcquisition {
2387        /// Descriptor-pass Cargo unit.
2388        unit: String,
2389        /// Component-local source-edge ID.
2390        source_edge: String,
2391    },
2392    /// Embedded descriptor bytes are not JSON.
2393    #[error("invalid embedded {kind} descriptor JSON: {source}")]
2394    ParsePayload {
2395        /// Payload kind.
2396        kind: &'static str,
2397        /// JSON error.
2398        #[source]
2399        source: serde_json::Error,
2400    },
2401    /// Payload wrapper schema does not match its fixed contract.
2402    #[error("invalid embedded {kind} payload schema at {location}: {source}")]
2403    InvalidPayloadSchema {
2404        /// Payload kind.
2405        kind: &'static str,
2406        /// Exact object location.
2407        location: String,
2408        /// JSON schema error.
2409        #[source]
2410        source: serde_json::Error,
2411    },
2412    /// Payload format/version unsupported by this linker.
2413    #[error("unsupported {kind} payload `{format}` schema version {schema_version}")]
2414    UnsupportedPayload {
2415        /// Payload kind.
2416        kind: &'static str,
2417        /// Format tag.
2418        format: String,
2419        /// Schema version.
2420        schema_version: u16,
2421    },
2422    /// Current component descriptor schema is not the expected v9 bridge.
2423    #[error(
2424        "unsupported component descriptor `{format}` schema version {schema_version}; expected rsjs.component_descriptor v9"
2425    )]
2426    UnsupportedComponentDescriptor {
2427        /// Descriptor format.
2428        format: String,
2429        /// Descriptor schema.
2430        schema_version: u64,
2431    },
2432    /// Component bridge descriptor omitted its stored content hash.
2433    #[error("component descriptor omitted descriptor_hash")]
2434    MissingComponentDescriptorHash,
2435    /// Standalone helper ABI is unsupported.
2436    #[error(
2437        "unsupported helper ABI: HIR v{body_hir}, Client IR v{body_ir}, codec v{codec}, effect `{effect_class}`"
2438    )]
2439    UnsupportedHelperAbi {
2440        /// Helper HIR version.
2441        body_hir: u16,
2442        /// Client IR version.
2443        body_ir: u16,
2444        /// Codec ABI version.
2445        codec: u16,
2446        /// Effect class.
2447        effect_class: String,
2448    },
2449    /// Required semantic hash is absent.
2450    #[error("{0} payload omitted semantic_hash")]
2451    MissingSemanticHash(&'static str),
2452    /// Semantic payload must be a JSON object.
2453    #[error("{0} payload must be a JSON object")]
2454    PayloadMustBeObject(&'static str),
2455    /// Hash has the wrong prefix, length, or alphabet.
2456    #[error("invalid lowercase SHA-256 value `{0}`")]
2457    InvalidHash(String),
2458    /// Record ID has the wrong length or alphabet.
2459    #[error("invalid {field} `{value}`; expected 64 lowercase hexadecimal digits")]
2460    InvalidRecordId {
2461        /// Field name.
2462        field: &'static str,
2463        /// Rejected value.
2464        value: String,
2465    },
2466    /// Re-encoding a parsed payload failed.
2467    #[error("failed to canonicalize embedded {kind} payload: {source}")]
2468    SerializePayload {
2469        /// Payload kind.
2470        kind: &'static str,
2471        /// JSON error.
2472        #[source]
2473        source: serde_json::Error,
2474    },
2475    /// Stored producer semantic hash did not match the payload.
2476    #[error("embedded {kind} semantic hash mismatch: expected {expected}, actual {actual}")]
2477    EmbeddedSemanticHashMismatch {
2478        /// Payload kind.
2479        kind: &'static str,
2480        /// Recomputed hash.
2481        expected: SemanticHash,
2482        /// Stored hash.
2483        actual: SemanticHash,
2484    },
2485    /// Payload and defining record disagree.
2486    #[error("{kind} payload belongs to record {actual}, expected {expected}")]
2487    PayloadDefinitionMismatch {
2488        /// Definition kind.
2489        kind: &'static str,
2490        /// Extracted definition record.
2491        expected: String,
2492        /// Payload metadata.
2493        actual: String,
2494    },
2495    /// Producer claimed token identity rather than Rust relocation identity.
2496    #[error("invalid {kind} identity authority `{authority}`")]
2497    InvalidIdentityAuthority {
2498        /// Edge kind.
2499        kind: &'static str,
2500        /// Producer authority tag.
2501        authority: String,
2502    },
2503    /// Payload listed no matching relocation edge.
2504    #[error("missing relocation-backed {kind} source edge {unit}:{source_edge}")]
2505    MissingSourceEdge {
2506        /// Edge kind.
2507        kind: &'static str,
2508        /// Source unit.
2509        unit: String,
2510        /// Source edge ID.
2511        source_edge: String,
2512    },
2513    /// Two payloads claimed one source edge.
2514    #[error("{kind} source edge {unit}:{source_edge} was claimed twice")]
2515    SourceEdgeClaimedTwice {
2516        /// Edge kind.
2517        kind: &'static str,
2518        /// Source unit.
2519        unit: String,
2520        /// Source edge ID.
2521        source_edge: String,
2522    },
2523    /// Component field claim count exceeded the canonical u32 ID space.
2524    #[error("component field claim count exceeds the canonical u32 ID space")]
2525    ComponentFieldIdOverflow,
2526    /// Component field claims were not in dense field-ID order.
2527    #[error(
2528        "component {component:?} field claims are not dense: expected field {expected}, found {actual}"
2529    )]
2530    NonDenseComponentFieldClaims {
2531        /// Defining component.
2532        component: TransportDefinitionId,
2533        /// Expected dense field ID.
2534        expected: u32,
2535        /// Claimed field ID.
2536        actual: u32,
2537    },
2538    /// A field role and callback shape formed an impossible contract.
2539    #[error(
2540        "component field `{field}` has invalid role/callback shape `{role}`/`{callback_shape}`"
2541    )]
2542    InvalidComponentFieldRoleShape {
2543        /// Source field name.
2544        field: String,
2545        /// Claimed role.
2546        role: String,
2547        /// Claimed callback shape.
2548        callback_shape: String,
2549    },
2550    /// The payload's field record ID was not the deterministic ID for its
2551    /// fingerprint and behavior claim.
2552    #[error("component {component:?} field `{field}` has record ID {actual}, expected {expected}")]
2553    ComponentFieldRecordIdMismatch {
2554        /// Defining component.
2555        component: TransportDefinitionId,
2556        /// Source field name.
2557        field: String,
2558        /// Independently recomputed record ID.
2559        expected: String,
2560        /// Payload claim.
2561        actual: String,
2562    },
2563    /// A payload listed no matching exact object record.
2564    #[error("missing rustc-backed component field record {unit}:{field_record}")]
2565    MissingComponentField {
2566        /// Descriptor-pass Cargo unit.
2567        unit: String,
2568        /// Field record ID.
2569        field_record: String,
2570    },
2571    /// Two payload claims selected one component-field object record.
2572    #[error("component field record {unit}:{field_record} was claimed twice")]
2573    ComponentFieldClaimedTwice {
2574        /// Descriptor-pass Cargo unit.
2575        unit: String,
2576        /// Field record ID.
2577        field_record: String,
2578    },
2579    /// A field record relocated to a component other than the payload that
2580    /// claimed it.
2581    #[error(
2582        "component field `{field}` relocated to {actual:?}, expected its defining component {expected:?}"
2583    )]
2584    ComponentFieldTargetMismatch {
2585        /// Source field name.
2586        field: String,
2587        /// Payload's defining component.
2588        expected: TransportDefinitionId,
2589        /// Relocation-selected component.
2590        actual: TransportDefinitionId,
2591    },
2592    /// SharedState acquisition claim count exceeded the canonical u32 ID
2593    /// space.
2594    #[error("SharedState acquisition claim count exceeds the canonical u32 store-ID space")]
2595    SharedStateStoreIdOverflow,
2596    /// Component SharedState acquisition claims were not in dense store-ID
2597    /// order.
2598    #[error(
2599        "component {component:?} SharedState acquisition claims are not dense: expected store {expected}, found {actual}"
2600    )]
2601    NonDenseSharedStateAcquisitionClaims {
2602        /// Defining component.
2603        component: TransportDefinitionId,
2604        /// Expected dense store ID.
2605        expected: u32,
2606        /// Claimed store ID.
2607        actual: u32,
2608    },
2609    /// Descriptor SharedState stores and payload ownership claims were not
2610    /// one-to-one.
2611    #[error(
2612        "component {component:?} has {stores} descriptor SharedState stores but {claims} acquisition ownership claims"
2613    )]
2614    SharedStateAcquisitionClaimCountMismatch {
2615        /// Defining component.
2616        component: TransportDefinitionId,
2617        /// Number of descriptor stores.
2618        stores: usize,
2619        /// Number of payload ownership claims.
2620        claims: usize,
2621    },
2622    /// The embedded descriptor's SharedState store table was malformed.
2623    #[error("component {component:?} has invalid SharedState store metadata: {reason}")]
2624    InvalidSharedStateDescriptorStores {
2625        /// Defining component.
2626        component: TransportDefinitionId,
2627        /// Focused validation failure.
2628        reason: String,
2629    },
2630    /// A payload claim did not use the deterministic source-edge ID for its
2631    /// component fingerprint and store ID.
2632    #[error(
2633        "component {component:?} SharedState store {store_id} has acquisition record ID {actual}, expected {expected}"
2634    )]
2635    SharedStateAcquisitionRecordIdMismatch {
2636        /// Defining component.
2637        component: TransportDefinitionId,
2638        /// Component-local SharedStoreId.
2639        store_id: u32,
2640        /// Independently recomputed source-edge ID.
2641        expected: String,
2642        /// Payload claim.
2643        actual: String,
2644    },
2645    /// A component payload listed no matching acquisition object record.
2646    #[error(
2647        "component {component:?} store {store_id} is missing relocation-backed SharedState acquisition {unit}:{source_edge}"
2648    )]
2649    MissingSharedStateAcquisition {
2650        /// Defining component.
2651        component: TransportDefinitionId,
2652        /// Component-local SharedStoreId.
2653        store_id: u32,
2654        /// Descriptor-pass Cargo unit.
2655        unit: String,
2656        /// Claimed source-edge ID.
2657        source_edge: String,
2658    },
2659    /// Two component payload claims selected one acquisition object record.
2660    #[error("SharedState acquisition record {unit}:{source_edge} was claimed twice")]
2661    SharedStateAcquisitionClaimedTwice {
2662        /// Descriptor-pass Cargo unit.
2663        unit: String,
2664        /// Reused source-edge ID.
2665        source_edge: String,
2666    },
2667    /// SharedState provider claim count exceeded the canonical u32 ID space.
2668    #[error("SharedState provider-site claim count exceeds the canonical u32 site-ID space")]
2669    SharedStateProviderSiteIdOverflow,
2670    /// Component provider-site claims were not in dense site-ID order.
2671    #[error(
2672        "component {component:?} SharedState provider claims are not dense: expected site {expected}, found {actual}"
2673    )]
2674    NonDenseSharedStateProviderSiteClaims {
2675        /// Defining component.
2676        component: TransportDefinitionId,
2677        /// Expected dense provider site ID.
2678        expected: u32,
2679        /// Claimed provider site ID.
2680        actual: u32,
2681    },
2682    /// Debug descriptor provider sites and transport claims were not one-to-one.
2683    #[error(
2684        "component {component:?} has {descriptor_sites} descriptor SharedState provider sites but {claims} transport claims"
2685    )]
2686    SharedStateProviderSiteClaimCountMismatch {
2687        /// Defining component.
2688        component: TransportDefinitionId,
2689        /// Number of descriptor provider sites.
2690        descriptor_sites: usize,
2691        /// Number of transport claims.
2692        claims: usize,
2693    },
2694    /// The embedded descriptor's provider topology was malformed.
2695    #[error("component {component:?} has invalid SharedState provider metadata: {reason}")]
2696    InvalidSharedStateProviderSites {
2697        /// Defining component.
2698        component: TransportDefinitionId,
2699        /// Focused validation failure.
2700        reason: String,
2701    },
2702    /// One provider claim did not describe the supported static topology.
2703    #[error(
2704        "component {component:?} SharedState provider site {provider_site_id} is invalid: {reason}"
2705    )]
2706    InvalidSharedStateProviderSite {
2707        /// Defining component.
2708        component: TransportDefinitionId,
2709        /// Dense provider site ID.
2710        provider_site_id: u32,
2711        /// Focused validation failure.
2712        reason: String,
2713    },
2714    /// More than one provider attempted to own the same direct child edge.
2715    #[error(
2716        "component {component:?} direct child edge {child_edge} is claimed by more than one SharedState provider"
2717    )]
2718    SharedStateProviderChildClaimedTwice {
2719        /// Defining component.
2720        component: TransportDefinitionId,
2721        /// Reused child edge ordinal.
2722        child_edge: u32,
2723    },
2724    /// Provider transport and debug-descriptor metadata disagreed.
2725    #[error(
2726        "component {component:?} SharedState provider site {provider_site_id} disagrees with its descriptor metadata"
2727    )]
2728    SharedStateProviderDescriptorClaimMismatch {
2729        /// Defining component.
2730        component: TransportDefinitionId,
2731        /// Dense provider site ID.
2732        provider_site_id: u32,
2733    },
2734    /// Provider claim selected a different direct component source edge.
2735    #[error(
2736        "component {component:?} SharedState provider site {provider_site_id} claims child edge {actual}, expected {expected}"
2737    )]
2738    SharedStateProviderChildEdgeMismatch {
2739        /// Defining component.
2740        component: TransportDefinitionId,
2741        /// Dense provider site ID.
2742        provider_site_id: u32,
2743        /// Direct component claim.
2744        expected: String,
2745        /// Provider claim.
2746        actual: String,
2747    },
2748    /// Provider claim did not use its deterministic topology-bound source ID.
2749    #[error(
2750        "component {component:?} SharedState provider site {provider_site_id} has witness record ID {actual}, expected {expected}"
2751    )]
2752    SharedStateProviderRecordIdMismatch {
2753        /// Defining component.
2754        component: TransportDefinitionId,
2755        /// Dense provider site ID.
2756        provider_site_id: u32,
2757        /// Independently recomputed source-edge ID.
2758        expected: String,
2759        /// Payload claim.
2760        actual: String,
2761    },
2762    /// Provider claim listed no exact SharedState witness relocation.
2763    #[error(
2764        "component {component:?} SharedState provider site {provider_site_id} is missing relocation-backed witness {unit}:{source_edge}"
2765    )]
2766    MissingSharedStateProviderWitness {
2767        /// Defining component.
2768        component: TransportDefinitionId,
2769        /// Dense provider site ID.
2770        provider_site_id: u32,
2771        /// Descriptor-pass Cargo unit.
2772        unit: String,
2773        /// Claimed provider source-edge ID.
2774        source_edge: String,
2775    },
2776    /// More than one payload claim selected the provider's witness record.
2777    #[error("SharedState provider witness record {unit}:{source_edge} was claimed twice")]
2778    SharedStateProviderWitnessClaimedTwice {
2779        /// Descriptor-pass Cargo unit.
2780        unit: String,
2781        /// Reused source-edge ID.
2782        source_edge: String,
2783    },
2784    /// Extracted component edges absent from every defining payload.
2785    #[error("unclaimed component relocation edges: {0:?}")]
2786    UnclaimedComponentEdges(Vec<String>),
2787    /// Extracted component-field records absent from every defining payload.
2788    #[error("unclaimed component field records: {0:?}")]
2789    UnclaimedComponentFields(Vec<String>),
2790    /// Extracted helper edges absent from every component/helper payload.
2791    #[error("unclaimed helper relocation edges: {0:?}")]
2792    UnclaimedHelperEdges(Vec<String>),
2793    /// Extracted SharedState acquisitions absent from every defining component
2794    /// payload.
2795    #[error("unclaimed SharedState acquisition records: {0:?}")]
2796    UnclaimedSharedStateAcquisitions(Vec<String>),
2797    /// Exact SharedState records returned by extraction were not preserved
2798    /// one-for-one in the corresponding resolved join.
2799    #[error(
2800        "SharedState {kind} resolution did not preserve the exact extracted record set: extracted {extracted:?}, resolved {resolved:?}"
2801    )]
2802    SharedStateResolutionMismatch {
2803        /// SharedState record kind.
2804        kind: &'static str,
2805        /// Exact extracted `(CargoUnitId, record/source-edge)` keys.
2806        extracted: Vec<String>,
2807        /// Exact relocation/payload-resolved keys.
2808        resolved: Vec<String>,
2809    },
2810    /// A resolved acquisition selected a definition absent from the exact
2811    /// definition/payload join.
2812    #[error(
2813        "SharedState acquisition {source_unit}:{source_edge} targets missing definition {target:?}"
2814    )]
2815    MissingSharedStateAcquisitionTarget {
2816        /// Cargo unit containing the acquisition.
2817        source_unit: CargoUnitId,
2818        /// Lower-case source-edge record ID.
2819        source_edge: String,
2820        /// Relocation-selected definition.
2821        target: TransportDefinitionId,
2822    },
2823}
2824
2825/// Failure while publishing a content-addressed transport plan.
2826#[derive(Debug, Error)]
2827pub enum TransportPlanWriteError {
2828    /// Output directory must be resolved before writing.
2829    #[error("transport plan directory must be absolute: `{0}`")]
2830    RelativeDirectory(PathBuf),
2831    /// Directory creation failed.
2832    #[error("failed to create transport plan directory `{path}`: {source}")]
2833    CreateDirectory {
2834        /// Output directory.
2835        path: PathBuf,
2836        /// I/O error.
2837        #[source]
2838        source: io::Error,
2839    },
2840    /// Plan JSON serialization failed.
2841    #[error("failed to serialize transport plan: {0}")]
2842    Serialize(serde_json::Error),
2843    /// Existing plan could not be read.
2844    #[error("failed to read existing transport plan `{path}`: {source}")]
2845    ReadExisting {
2846        /// Existing path.
2847        path: PathBuf,
2848        /// I/O error.
2849        #[source]
2850        source: io::Error,
2851    },
2852    /// A strong ID unexpectedly named different bytes.
2853    #[error("content collision for PlanId {plan_id} at `{path}`")]
2854    ContentCollision {
2855        /// Strong plan identity.
2856        plan_id: PlanId,
2857        /// Existing path.
2858        path: PathBuf,
2859    },
2860    /// Atomic temporary creation failed.
2861    #[error("failed to create temporary transport plan `{path}`: {source}")]
2862    CreateTemporary {
2863        /// Temporary path.
2864        path: PathBuf,
2865        /// I/O error.
2866        #[source]
2867        source: io::Error,
2868    },
2869    /// Atomic temporary write failed.
2870    #[error("failed to write temporary transport plan `{path}`: {source}")]
2871    WriteTemporary {
2872        /// Temporary path.
2873        path: PathBuf,
2874        /// I/O error.
2875        #[source]
2876        source: io::Error,
2877    },
2878    /// Atomic rename failed.
2879    #[error("failed to publish transport plan from `{from}` to `{to}`: {source}")]
2880    Commit {
2881        /// Temporary path.
2882        from: PathBuf,
2883        /// Final path.
2884        to: PathBuf,
2885        /// I/O error.
2886        #[source]
2887        source: io::Error,
2888    },
2889}
2890
2891#[cfg(test)]
2892mod tests;