Skip to main content

varve_core/
compose.rs

1//! Layer composition (REQ-COMPOSE-001).
2//!
3//! A pin names one realm and one layer. That was fine while a layer held one
4//! organisation's tools, and it broke the first time a consumer needed two: the
5//! PulseEngine tools that CHECK their work and the upstream tools that BUILD it
6//! (varve#52). Putting both in one layer would place releases we do not control
7//! under a qualification claim covering tools we do — so instead a layer may
8//! COMPOSE another.
9//!
10//! An include is a manifest entry of payload kind `layer`, whose digest is the
11//! included layer's manifest digest and whose annotations name its realm. It
12//! lives in the signed payload, so the composition is signed; and because the
13//! digest is the identity, an include cannot silently drift.
14//!
15//! Everything here fails closed. A cycle is refused rather than followed, depth
16//! is bounded, and a tool exposed by two layers is an ERROR naming both — varve
17//! does not pick a winner, for the same reason a pin that does not resolve
18//! uniquely is an error and not a fallback.
19//!
20//! What v0.29.0 adds (REQ-REALM2-001 clause 4) is the way THROUGH that refusal.
21//! Two realms shipping one name stopped being hypothetical the moment a fork
22//! existed beside its upstream — which is the whole reason the fork exists,
23//! upstream not attesting every tool. The escape is a realm QUALIFIER in the
24//! pin, decided here and nowhere else: `select_tools` is the single place that
25//! says what a bare name dispatches to, it consults only the pin's choice, and
26//! it never consults install order. Realm PRECEDENCE was considered and
27//! rejected for exactly that reason — it would let adding a tool to a
28//! high-priority realm silently change which binary a build runs.
29
30use std::collections::{BTreeMap, BTreeSet};
31
32/// A lenient view of a layer manifest — just what composition needs.
33///
34/// Deliberately NOT `LayerManifest`: that parse enforces the full install
35/// contract (counter, issued-at), and requiring it merely to discover whether a
36/// layer composes another would make `which` fail on layers that resolve fine
37/// today. Reading less is what lets this be additive.
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
39pub struct LayerView {
40    pub includes: Vec<Include>,
41    /// Dispatchable tool names this layer exposes.
42    pub tools: Vec<String>,
43}
44
45/// Read the composition-relevant parts of a manifest. An unparseable manifest
46/// is an error, never an empty view — silently reporting "no includes" for a
47/// layer we could not read is the failure mode that hides a composition.
48pub fn view(bytes: &[u8]) -> Result<LayerView, ComposeError> {
49    let json: serde_json::Value =
50        serde_json::from_slice(bytes).map_err(|e| ComposeError::Unreadable(e.to_string()))?;
51    let mut v = LayerView::default();
52    let Some(entries) = json["manifests"].as_array() else {
53        return Ok(v);
54    };
55    for e in entries {
56        let ann = &e["annotations"];
57        let digest = e["digest"].as_str().unwrap_or_default().to_string();
58        match ann[crate::kind::ANN_KIND].as_str() {
59            // An EMPTY realm annotation is read as absent, not as a realm
60            // named "". Absent means "the including layer's realm", and a
61            // producer that writes the key with no value plainly means the
62            // same thing — reading it literally would leave the included
63            // layer with no realm and so no qualified form for its tools.
64            Some("layer") => v.includes.push(Include {
65                digest,
66                realm: ann[ANN_INCLUDE_REALM]
67                    .as_str()
68                    .filter(|s| !s.is_empty())
69                    .map(|s| s.to_string()),
70                layer: ann[ANN_INCLUDE_LAYER].as_str().map(|s| s.to_string()),
71            }),
72            // Absent kind = tool (back-compat, as everywhere else).
73            None => {
74                if let Some(t) = ann["eu.pulseengine.tool"].as_str() {
75                    v.tools.push(t.to_string());
76                }
77            }
78            // Any other kind is not dispatchable and not an include.
79            Some(_) => {}
80        }
81    }
82    Ok(v)
83}
84
85/// Annotation naming the realm an included layer belongs to. Absent means the
86/// including layer's own realm.
87pub const ANN_INCLUDE_REALM: &str = "eu.pulseengine.varve.include.realm";
88/// Annotation carrying the included layer's identity, for error messages that
89/// can name it before it has been fetched.
90pub const ANN_INCLUDE_LAYER: &str = "eu.pulseengine.varve.include.layer";
91
92/// How deep a composition graph may go. Generous for real use (a layer
93/// including a layer including a base), small enough that a malicious or
94/// mistaken graph cannot spend the client's time.
95pub const MAX_DEPTH: usize = 8;
96
97/// One layer this manifest composes.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct Include {
100    /// `sha256:<hex>` of the included layer's signed manifest — its identity.
101    pub digest: String,
102    /// The realm whose trust root verifies it. `None` = the including realm.
103    pub realm: Option<String>,
104    /// The included layer's identifier, for messages before it is resolved.
105    pub layer: Option<String>,
106}
107
108#[derive(Debug, thiserror::Error)]
109pub enum ComposeError {
110    #[error(
111        "composition cycle: layer {digest} includes itself, directly or through \
112         {via} — refusing to follow it"
113    )]
114    Cycle { digest: String, via: String },
115    #[error(
116        "composition is more than {MAX_DEPTH} layers deep — refusing to walk further \
117         (a layer graph this deep is a mistake, not a design)"
118    )]
119    TooDeep,
120    #[error("layer manifest could not be read for composition: {0}")]
121    Unreadable(String),
122    /// A layer the composition names is not in any store the caller can see.
123    #[error(
124        "layer {layer} composes {missing}, which is not installed — anything reading this \
125         composition would silently omit that layer's payloads. `varve install` it, then \
126         run this again (REQ-COMPOSEEXPORT-001 clause 3)"
127    )]
128    NotInstalled { layer: String, missing: String },
129    /// An include names a realm the caller has no trust root for.
130    #[error(
131        "layer {layer} composes a layer from realm '{realm}', but that realm is not defined \
132         here — add it to varve-realms.toml so its trust root can verify what it vouches for"
133    )]
134    UnknownRealm { layer: String, realm: String },
135    /// An included layer did not verify against the root of the realm its
136    /// include names.
137    #[error(
138        "composed layer {layer} failed verification against realm '{realm}': {detail}. If the \
139         included layer comes from a DIFFERENT realm, this is the expected result of an \
140         `[[include]]` with no `realm =`"
141    )]
142    IncludeUnverified {
143        layer: String,
144        realm: String,
145        detail: String,
146    },
147    #[error("{0}")]
148    Io(String),
149    /// A name two layers of one composition both provide, which the pin has
150    /// not chosen between (REQ-REALM2-001 clause 4d).
151    ///
152    /// The old message named two layer DIGESTS and then said "Restrict the
153    /// pin's `tools`" — advice structurally incapable of working, because
154    /// `tools` filtered by NAME and the collision is one name. It must instead
155    /// name both providers WITH their realms and show the qualified form to
156    /// copy, which is a fix the reader can actually apply.
157    #[error(
158        "tool '{tool}' is provided by more than one layer of this composition — {first} \
159         and {second} — and the pin has not chosen between them. varve does not pick a \
160         winner: what a bare name runs is decided by the pin, never by install order. \
161         {fix}"
162    )]
163    AmbiguousTool {
164        tool: String,
165        first: String,
166        second: String,
167        fix: String,
168    },
169    /// The pin qualified a name with a realm that provides no such tool.
170    /// Failing closed matters here: silently falling back to the other realm
171    /// would run bytes the pin explicitly did not choose.
172    #[error(
173        "this project's pin selects '{selector}', but no layer of this composition from \
174         realm '{realm}' provides '{tool}' — it is provided by: {providers}. Fix the \
175         qualifier in varve.toml; varve will not substitute another realm's binary for \
176         the one the pin named."
177    )]
178    RealmProvidesNoSuchTool {
179        selector: String,
180        realm: String,
181        tool: String,
182        providers: String,
183    },
184    /// Boxed: six strings inline would make every `ComposeError` — and so
185    /// every `ResolveError` — large enough to move on the happy path.
186    #[error(transparent)]
187    ConflictingPayload(#[from] Box<PayloadConflict>),
188}
189
190/// Two layers of one composition offering the same (name, version) as
191/// different bytes (REQ-COMPOSEEXPORT-001 clause 2).
192#[derive(Debug, thiserror::Error, PartialEq, Eq)]
193#[error(
194    "{name} {version} is offered by two layers in this composition with DIFFERENT bytes: \
195     {first} has {first_digest}, {second} has {second_digest} — refusing to choose. \
196     Two realms disagreeing about what one name-and-version IS cannot both be exported; \
197     a name at different VERSIONS is legal and both export, but one (name, version) must \
198     be one artifact. Re-deposit one of the layers against the other's bytes, or drop the \
199     duplicate from the composition."
200)]
201pub struct PayloadConflict {
202    pub name: String,
203    pub version: String,
204    pub first: String,
205    pub first_digest: String,
206    pub second: String,
207    pub second_digest: String,
208}
209
210/// Where one payload of a composition came from and what it claims to be. The
211/// identity the collision rule is stated over (REQ-COMPOSEEXPORT-001 clause 2).
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct PayloadOrigin {
214    pub name: String,
215    pub version: String,
216    /// `sha256:<hex>` of the bytes, as the signed manifest records it.
217    pub digest: String,
218    /// The realm whose trust root vouched for the layer offering it, and the
219    /// layer itself — both, because the error must name the realms that
220    /// disagree, not merely the layers.
221    pub realm: String,
222    pub layer: String,
223}
224
225impl PayloadOrigin {
226    /// How this payload is named in an error: realm first, since the realms
227    /// are what disagree.
228    fn describe(&self) -> String {
229        format!("realm '{}' layer {}", self.realm, self.layer)
230    }
231}
232
233/// Union the payloads every layer of a composition offers, applying the rule
234/// that is NOT the tool rule (REQ-COMPOSEEXPORT-001 clause 2).
235///
236/// A tool name in two layers is ambiguous because dispatch must pick ONE
237/// binary for a bare name — so `union_tools` refuses it. A payload is not
238/// dispatched: it is placed in a registry keyed by (name, version), and two
239/// versions of one crate are the ordinary case a lockfile requires. So:
240///
241/// * the same name at DIFFERENT versions — both export;
242/// * the same name AND version with the SAME digest — one copy (a diamond
243///   offers a shared base twice; that is agreement, not conflict);
244/// * the same name AND version with DIFFERENT digests — an ERROR naming both
245///   realms, because two realms then disagree about what those bytes are and
246///   varve does not pick a winner.
247///
248/// Order is preserved (root layer first), so the export is a function of the
249/// composition rather than of a map's iteration order.
250pub fn union_payloads<T>(
251    items: Vec<(PayloadOrigin, T)>,
252) -> Result<Vec<(PayloadOrigin, T)>, ComposeError> {
253    let mut first_seen: BTreeMap<(String, String), PayloadOrigin> = BTreeMap::new();
254    let mut out = Vec::new();
255    for (origin, payload) in items {
256        let key = (origin.name.clone(), origin.version.clone());
257        match first_seen.get(&key) {
258            Some(first) if first.digest != origin.digest => {
259                return Err(ComposeError::ConflictingPayload(Box::new(
260                    PayloadConflict {
261                        name: origin.name.clone(),
262                        version: origin.version.clone(),
263                        first: first.describe(),
264                        first_digest: first.digest.clone(),
265                        second: origin.describe(),
266                        second_digest: origin.digest,
267                    },
268                )));
269            }
270            // Same bytes, offered twice: export one copy, not an error.
271            Some(_) => continue,
272            None => {
273                first_seen.insert(key, origin.clone());
274                out.push((origin, payload));
275            }
276        }
277    }
278    Ok(out)
279}
280
281/// The layers a view directly composes, in manifest order.
282pub fn includes(v: &LayerView) -> Vec<Include> {
283    v.includes.clone()
284}
285
286/// One layer of a walked composition, with the realm whose root vouches for it.
287///
288/// The realm is carried through the walk rather than looked up afterwards
289/// because it is a property of the EDGE — an `[[include]]` names the realm that
290/// verifies the layer it points at — and because a refusal that cannot name the
291/// realms is the refusal clause 4d exists to replace.
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub struct Walked {
294    pub digest: String,
295    /// The realm naming this layer's trust root. Empty where the composition
296    /// names none (a pin with no `realm`), in which case there is no qualified
297    /// form for its tools and the refusal must say so.
298    pub realm: String,
299    pub view: LayerView,
300}
301
302/// Walk a composition graph from a root manifest, refusing cycles and excessive
303/// depth. `fetch` supplies a manifest for a digest, or `None` if that layer is
304/// not installed — a missing layer is the caller's error to report (with its
305/// corrective `varve install`), not this walker's to invent.
306///
307/// `root_realm` labels the root; each include labels its child, inheriting the
308/// including layer's realm where it names none (the annotation's documented
309/// meaning).
310///
311/// Returns the visit order, root first, so callers can select tools predictably.
312pub fn walk<F>(
313    root_digest: &str,
314    root_realm: &str,
315    root: &LayerView,
316    mut fetch: F,
317) -> Result<Vec<Walked>, ComposeError>
318where
319    F: FnMut(&str) -> Option<LayerView>,
320{
321    let mut out = vec![Walked {
322        digest: root_digest.to_string(),
323        realm: root_realm.to_string(),
324        view: root.clone(),
325    }];
326    let mut emitted: BTreeSet<String> = BTreeSet::new();
327    emitted.insert(root_digest.to_string());
328    // (digest, realm, view, ancestors-on-this-path). A CYCLE is a digest
329    // reappearing on its OWN path — not merely one seen before. An earlier
330    // version used a global `seen`, which reported a DIAMOND (two layers
331    // sharing a base) as a cycle, with a message falsely claiming the layer
332    // included itself. A shared base is the most ordinary composition there is.
333    let mut stack: Vec<(String, String, LayerView, BTreeSet<String>)> = vec![(
334        root_digest.to_string(),
335        root_realm.to_string(),
336        root.clone(),
337        BTreeSet::from([root_digest.to_string()]),
338    )];
339    while let Some((from, realm, view, path)) = stack.pop() {
340        if path.len() > MAX_DEPTH {
341            return Err(ComposeError::TooDeep);
342        }
343        for inc in includes(&view) {
344            if path.contains(&inc.digest) {
345                return Err(ComposeError::Cycle {
346                    digest: inc.digest.clone(),
347                    via: from.clone(),
348                });
349            }
350            let Some(child) = fetch(&inc.digest) else {
351                // Not installed. The caller names it and how to fix it.
352                continue;
353            };
354            let child_realm = inc.realm.clone().unwrap_or_else(|| realm.clone());
355            // A layer reachable by two paths is walked once, not refused.
356            if emitted.insert(inc.digest.clone()) {
357                out.push(Walked {
358                    digest: inc.digest.clone(),
359                    realm: child_realm.clone(),
360                    view: child.clone(),
361                });
362            }
363            let mut child_path = path.clone();
364            child_path.insert(inc.digest.clone());
365            stack.push((inc.digest.clone(), child_realm, child, child_path));
366        }
367    }
368    Ok(out)
369}
370
371/// One layer's claim to a dispatchable name.
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub struct ToolProvider {
374    pub tool: String,
375    /// The realm whose root vouches for the providing layer. Empty where the
376    /// composition names none.
377    pub realm: String,
378    /// The providing layer's identity, for messages a human reads.
379    pub layer: String,
380    /// The providing layer's manifest digest — the store key.
381    pub digest: String,
382}
383
384impl ToolProvider {
385    /// How a pin names this provider: `realm/tool`. `None` where the layer
386    /// belongs to no named realm — there is then no qualified form, and a
387    /// refusal must say that rather than print one that cannot work.
388    pub fn qualified(&self) -> Option<String> {
389        (!self.realm.is_empty()).then(|| format!("{}/{}", self.realm, self.tool))
390    }
391
392    /// How this provider is named in an error: realm first, since the realms
393    /// are what a reader must tell apart.
394    fn describe(&self) -> String {
395        if self.realm.is_empty() {
396            format!("layer {} (no realm named)", self.layer)
397        } else {
398            format!("realm '{}' layer {}", self.realm, self.layer)
399        }
400    }
401}
402
403/// Decide, for every dispatchable name a composition exposes, the ONE provider
404/// a bare name resolves to (REQ-REALM2-001 clauses 4c and 4d).
405///
406/// `chosen` is the pin's realm-qualified selection, tool name → realm. A name
407/// with a single provider needs no entry and is unaffected — every pin written
408/// before this existed keeps resolving byte for byte. A name with several
409/// providers resolves only where the pin chose, and the choice is the pin's
410/// alone: nothing here reads install order, partition order or a precedence
411/// list, because any of those would let adding a tool to one realm silently
412/// change which binary a build runs.
413///
414/// Providers are given root-layer-first; that order decides only which one an
415/// error names first, never which one wins.
416pub fn select_tools(
417    providers: &[ToolProvider],
418    chosen: &BTreeMap<String, String>,
419) -> Result<BTreeMap<String, ToolProvider>, ComposeError> {
420    let mut by_name: BTreeMap<&str, Vec<&ToolProvider>> = BTreeMap::new();
421    for p in providers {
422        let slot = by_name.entry(p.tool.as_str()).or_default();
423        // One layer offering a name twice (manifest and `bin/` both say so) is
424        // one provider, not a collision with itself.
425        if !slot.iter().any(|q| q.digest == p.digest) {
426            slot.push(p);
427        }
428    }
429    let mut out = BTreeMap::new();
430    for (tool, offers) in by_name {
431        let picked: Vec<&ToolProvider> = match chosen.get(tool) {
432            Some(realm) => offers
433                .iter()
434                .copied()
435                .filter(|p| &p.realm == realm)
436                .collect(),
437            None => offers.clone(),
438        };
439        match picked.as_slice() {
440            [only] => {
441                out.insert(tool.to_string(), (*only).clone());
442            }
443            [] => {
444                // The pin qualified with a realm that provides nothing here.
445                let realm = chosen.get(tool).cloned().unwrap_or_default();
446                return Err(ComposeError::RealmProvidesNoSuchTool {
447                    selector: format!("{realm}/{tool}"),
448                    realm,
449                    tool: tool.to_string(),
450                    providers: offers
451                        .iter()
452                        .map(|p| p.describe())
453                        .collect::<Vec<_>>()
454                        .join(", "),
455                });
456            }
457            [first, second, ..] => {
458                return Err(ComposeError::AmbiguousTool {
459                    tool: tool.to_string(),
460                    first: first.describe(),
461                    second: second.describe(),
462                    fix: fix_for(tool, first, second, chosen.contains_key(tool)),
463                });
464            }
465        }
466    }
467    Ok(out)
468}
469
470/// The corrective half of clause 4d: a line the reader can paste, or a plain
471/// statement of why no such line exists for this pair.
472fn fix_for(
473    tool: &str,
474    first: &ToolProvider,
475    second: &ToolProvider,
476    already_qualified: bool,
477) -> String {
478    match (first.qualified(), second.qualified()) {
479        (Some(a), Some(b)) if first.realm != second.realm => format!(
480            "Choose one in varve.toml: tools = [\"{a}\"] — or tools = [\"{b}\"]. The layer you \
481             do not choose stays installed and verified, and `varve run {a}` / `varve run {b}` \
482             still reach either one."
483        ),
484        // Two layers of ONE realm, or a layer with no realm at all: a realm
485        // qualifier cannot separate these, and saying so is the honest answer.
486        _ if already_qualified || first.realm == second.realm => format!(
487            "Both are in realm '{}', so a realm qualifier cannot separate them — one of those \
488             two layers must stop exposing '{tool}', or pin the layer that provides the one \
489             you want directly.",
490            first.realm
491        ),
492        _ => format!(
493            "One of these layers belongs to no named realm, so there is no qualified form for \
494             it: define its realm in varve-realms.toml and name it in the pin's `realm`, then \
495             choose with tools = [\"<realm>/{tool}\"]."
496        ),
497    }
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    /// A manifest with the given tools and includes.
505    fn manifest(layer: &str, tools: &[&str], includes: &[(&str, &str)]) -> LayerView {
506        let mut entries: Vec<String> = tools
507            .iter()
508            .map(|t| {
509                format!(
510                    r#"{{"digest":"sha256:{t}","annotations":{{"eu.pulseengine.tool":"{t}"}}}}"#
511                )
512            })
513            .collect();
514        for (digest, realm) in includes {
515            entries.push(format!(
516                r#"{{"digest":"{digest}","annotations":{{"eu.pulseengine.varve.kind":"layer","{ANN_INCLUDE_REALM}":"{realm}"}}}}"#
517            ));
518        }
519        let json = format!(
520            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json",
521"artifactType":"application/vnd.pulseengine.varve.layer.v1+json",
522"annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.channel":"qualified",
523"eu.pulseengine.varve.counter":"1","org.opencontainers.image.created":"2026-08-01T00:00:00Z"}},
524"manifests":[{}]}}"#,
525            entries.join(",")
526        );
527        let _ = layer;
528        view(json.as_bytes()).unwrap()
529    }
530
531    /// Every provider a walk exposes, in walk order — the shape `resolve`
532    /// hands `select_tools`, built here from views so the compose tests reason
533    /// about the same data the binary does.
534    fn providers(walked: &[Walked]) -> Vec<ToolProvider> {
535        walked
536            .iter()
537            .flat_map(|w| {
538                w.view.tools.iter().map(|t| ToolProvider {
539                    tool: t.clone(),
540                    realm: w.realm.clone(),
541                    layer: "2026.08.0".into(),
542                    digest: w.digest.clone(),
543                })
544            })
545            .collect()
546    }
547
548    /// `select_tools` with nothing chosen — the pre-v0.29.0 behaviour, and
549    /// still what an unrestricted pin gets.
550    fn unchosen(walked: &[Walked]) -> Result<BTreeMap<String, ToolProvider>, ComposeError> {
551        select_tools(&providers(walked), &BTreeMap::new())
552    }
553
554    // rivet: verifies REQ-COMPOSE-001
555    #[test]
556    fn a_composition_exposes_both_layers_tools() {
557        let upstream = manifest("2026.08.0", &["wasm-tools", "cargo-component"], &[]);
558        let root = manifest(
559            "2026.08.0",
560            &["rivet", "meld"],
561            &[("sha256:up", "bytecodealliance")],
562        );
563        let inc = includes(&root);
564        assert_eq!(inc.len(), 1);
565        assert_eq!(inc[0].digest, "sha256:up");
566        assert_eq!(inc[0].realm.as_deref(), Some("bytecodealliance"));
567
568        let layers = walk("sha256:root", "pulseengine", &root, |d| {
569            (d == "sha256:up").then(|| upstream.clone())
570        })
571        .unwrap();
572        assert_eq!(layers.len(), 2, "root plus the included layer");
573        // The include's realm labels the layer it points at; the root keeps
574        // the pin's own.
575        assert_eq!(layers[0].realm, "pulseengine");
576        assert_eq!(layers[1].realm, "bytecodealliance");
577        let tools = unchosen(&layers).unwrap();
578        // The producing half is now answerable alongside the checking half.
579        for t in ["rivet", "meld", "wasm-tools", "cargo-component"] {
580            assert!(tools.contains_key(t), "{t} missing from the composition");
581        }
582        assert_eq!(tools["wasm-tools"].digest, "sha256:up");
583        assert_eq!(tools["rivet"].digest, "sha256:root");
584    }
585
586    // rivet: verifies REQ-COMPOSE-001
587    #[test]
588    fn a_tool_in_two_layers_is_an_error_not_a_silent_choice() {
589        // Both layers ship `wasm-tools`. varve must not pick one.
590        let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
591        let root = manifest(
592            "2026.08.0",
593            &["wasm-tools"],
594            &[("sha256:up", "bytecodealliance")],
595        );
596        let layers = walk("sha256:root", "pulseengine", &root, |d| {
597            (d == "sha256:up").then(|| upstream.clone())
598        })
599        .unwrap();
600        match unchosen(&layers) {
601            Err(ComposeError::AmbiguousTool { tool, .. }) => assert_eq!(tool, "wasm-tools"),
602            other => panic!("expected AmbiguousTool, got {other:?}"),
603        }
604    }
605
606    // rivet: verifies REQ-REALM2-001
607    #[test]
608    fn a_realm_qualifier_settles_a_collision_the_tools_filter_never_could() {
609        // Clause 4a. `tools = ["rivet", "synth"]` filters by NAME, and the
610        // collision is two layers exposing the SAME name — so no value of the
611        // old filter could ever disambiguate. A realm can.
612        let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
613        let root = manifest(
614            "2026.09.0",
615            &["wasm-tools", "rivet"],
616            &[("sha256:up", "bytecodealliance")],
617        );
618        let layers = walk("sha256:root", "pulseengine", &root, |d| {
619            (d == "sha256:up").then(|| upstream.clone())
620        })
621        .unwrap();
622        let all = providers(&layers);
623
624        for (realm, digest) in [
625            ("bytecodealliance", "sha256:up"),
626            ("pulseengine", "sha256:root"),
627        ] {
628            let chosen = BTreeMap::from([("wasm-tools".to_string(), realm.to_string())]);
629            let picked = select_tools(&all, &chosen).unwrap();
630            assert_eq!(
631                picked["wasm-tools"].digest, digest,
632                "the pin chose realm '{realm}'"
633            );
634            assert_eq!(picked["wasm-tools"].realm, realm);
635            // A bare name where nothing collides is untouched by any of this.
636            assert_eq!(picked["rivet"].digest, "sha256:root");
637        }
638    }
639
640    // rivet: verifies REQ-REALM2-001
641    #[test]
642    fn a_qualifier_naming_a_realm_that_provides_nothing_is_refused_not_ignored() {
643        // Failing closed is the whole point: quietly falling back to the other
644        // realm would run bytes the pin explicitly did not choose, which is the
645        // silent substitution the qualifier exists to prevent.
646        let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
647        let root = manifest(
648            "2026.09.0",
649            &["wasm-tools"],
650            &[("sha256:up", "bytecodealliance")],
651        );
652        let layers = walk("sha256:root", "pulseengine", &root, |d| {
653            (d == "sha256:up").then(|| upstream.clone())
654        })
655        .unwrap();
656        let chosen = BTreeMap::from([("wasm-tools".to_string(), "acme".to_string())]);
657        let err = select_tools(&providers(&layers), &chosen).unwrap_err();
658        let msg = err.to_string();
659        assert!(
660            matches!(err, ComposeError::RealmProvidesNoSuchTool { .. }),
661            "{msg}"
662        );
663        assert!(msg.contains("acme/wasm-tools"), "{msg}");
664        // …and it names who DOES provide it, or the reader cannot fix the typo.
665        assert!(
666            msg.contains("pulseengine") && msg.contains("bytecodealliance"),
667            "{msg}"
668        );
669    }
670
671    // rivet: verifies REQ-REALM2-001
672    #[test]
673    fn the_refusal_names_both_realms_and_shows_a_qualified_form_that_works() {
674        // Clause 4d. The message it replaces named two layer DIGESTS and then
675        // advised "Restrict the pin's `tools`" — a fix that cannot work, and a
676        // persona who tried it twice reported it doing nothing.
677        let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
678        let root = manifest(
679            "2026.09.0",
680            &["wasm-tools"],
681            &[("sha256:up", "bytecodealliance")],
682        );
683        let layers = walk("sha256:root", "pulseengine", &root, |d| {
684            (d == "sha256:up").then(|| upstream.clone())
685        })
686        .unwrap();
687        let msg = unchosen(&layers).unwrap_err().to_string();
688        assert!(
689            msg.contains("realm 'pulseengine'") && msg.contains("realm 'bytecodealliance'"),
690            "both providers must be named WITH their realms: {msg}"
691        );
692        assert!(
693            msg.contains("tools = [\"pulseengine/wasm-tools\"]")
694                && msg.contains("tools = [\"bytecodealliance/wasm-tools\"]"),
695            "both qualified forms must be there to copy: {msg}"
696        );
697        assert!(
698            !msg.contains("Restrict the pin's `tools`"),
699            "the advice that cannot work must be gone: {msg}"
700        );
701    }
702
703    // rivet: verifies REQ-REALM2-001
704    #[test]
705    fn two_layers_of_one_realm_are_told_a_qualifier_cannot_help_them() {
706        // The honest edge of clause 4d. A realm qualifier separates realms; it
707        // cannot separate two layers inside one. Printing a form that would not
708        // work is exactly the failure this requirement exists to end, so the
709        // refusal says so instead.
710        let base = manifest("2026.08.0", &["wasm-tools"], &[]);
711        let root = manifest("2026.09.0", &["wasm-tools"], &[("sha256:base", "")]);
712        let layers = walk("sha256:root", "pulseengine", &root, |d| {
713            (d == "sha256:base").then(|| base.clone())
714        })
715        .unwrap();
716        let msg = unchosen(&layers).unwrap_err().to_string();
717        assert!(
718            msg.contains("a realm qualifier cannot separate them"),
719            "an unusable qualified form must not be offered: {msg}"
720        );
721    }
722
723    // rivet: verifies REQ-REALM2-001
724    #[test]
725    fn one_layer_declaring_a_name_twice_is_not_a_collision_with_itself() {
726        // `resolve` offers a name from the signed manifest AND from `bin/`, so
727        // the ordinary layer produces two offers for one tool. Treating that as
728        // ambiguity would refuse every single-realm pin varve has ever had.
729        let twice = vec![
730            ToolProvider {
731                tool: "rivet".into(),
732                realm: "pulseengine".into(),
733                layer: "2026.09.0".into(),
734                digest: "sha256:root".into(),
735            },
736            ToolProvider {
737                tool: "rivet".into(),
738                realm: "pulseengine".into(),
739                layer: "2026.09.0".into(),
740                digest: "sha256:root".into(),
741            },
742        ];
743        let picked = select_tools(&twice, &BTreeMap::new()).unwrap();
744        assert_eq!(picked["rivet"].digest, "sha256:root");
745    }
746
747    // rivet: verifies REQ-REALM2-001
748    #[test]
749    fn an_include_inherits_the_including_realm_where_it_names_none() {
750        // The annotation's documented meaning ("absent means the including
751        // layer's own realm"), which is also what keeps every single-realm
752        // composition addressable: without inheritance the included layer would
753        // have no qualified form at all.
754        let base = manifest("2026.08.0", &["base"], &[]);
755        let root = manifest("2026.09.0", &["rivet"], &[("sha256:base", "")]);
756        let layers = walk("sha256:root", "pulseengine", &root, |d| {
757            (d == "sha256:base").then(|| base.clone())
758        })
759        .unwrap();
760        assert_eq!(layers[1].realm, "pulseengine");
761        let picked = unchosen(&layers).unwrap();
762        assert_eq!(
763            picked["base"].qualified().as_deref(),
764            Some("pulseengine/base")
765        );
766    }
767
768    // rivet: verifies REQ-COMPOSE-001
769    #[test]
770    fn depth_is_bounded_so_a_long_chain_cannot_exhaust_the_walker() {
771        // The bound is what keeps "refused" from meaning "followed until the
772        // process aborts". Re-verification found `verify` recursing without it
773        // and stack-overflowing on a self-referencing store entry; both walkers
774        // are now bounded.
775        let leaf = manifest("2026.08.0", &["leaf"], &[]);
776        // A chain longer than MAX_DEPTH, each link including the next.
777        let chain: Vec<LayerView> = (0..=MAX_DEPTH + 2)
778            .map(|i| manifest("2026.08.0", &["t"], &[(&format!("sha256:{}", i + 1), "r")]))
779            .collect();
780        let err = walk("sha256:0", "r", &chain[0], |d: &str| {
781            let n: usize = d.trim_start_matches("sha256:").parse().ok()?;
782            chain.get(n).cloned().or_else(|| Some(leaf.clone()))
783        })
784        .unwrap_err();
785        assert!(matches!(err, ComposeError::TooDeep), "got {err:?}");
786    }
787
788    // rivet: verifies REQ-COMPOSE-001
789    #[test]
790    fn a_chain_exactly_at_the_bound_is_walked_not_refused() {
791        // The other side of the same `>`. `MAX_DEPTH` is documented as how deep
792        // a composition MAY go, so a graph exactly that deep is legal — an
793        // off-by-one here would refuse the deepest permitted composition while
794        // the message said graphs of this depth are a mistake.
795        let chain: Vec<LayerView> = (0..MAX_DEPTH)
796            .map(|i| {
797                let tool = format!("t{i}");
798                if i + 1 == MAX_DEPTH {
799                    manifest("2026.08.0", &[&tool], &[])
800                } else {
801                    manifest(
802                        "2026.08.0",
803                        &[&tool],
804                        &[(&format!("sha256:{}", i + 1), "r")],
805                    )
806                }
807            })
808            .collect();
809        let walked = walk("sha256:0", "r", &chain[0], |d: &str| {
810            let n: usize = d.trim_start_matches("sha256:").parse().ok()?;
811            chain.get(n).cloned()
812        })
813        .expect("a chain exactly MAX_DEPTH long is within the bound");
814        assert_eq!(walked.len(), MAX_DEPTH);
815    }
816
817    // rivet: verifies REQ-REALM2-001
818    #[test]
819    fn a_collision_involving_a_layer_with_no_realm_says_there_is_no_qualified_form() {
820        // A pin that names no realm gives its own layer no realm name, so
821        // there IS no `realm/tool` for it. Printing one anyway would be the
822        // same failure clause 4d exists to end — advice that cannot work — so
823        // the refusal points at the thing that WOULD make a qualifier possible.
824        let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
825        let root = manifest(
826            "2026.09.0",
827            &["wasm-tools"],
828            &[("sha256:up", "bytecodealliance")],
829        );
830        let layers = walk("sha256:root", "", &root, |d| {
831            (d == "sha256:up").then(|| upstream.clone())
832        })
833        .unwrap();
834        let msg = unchosen(&layers).unwrap_err().to_string();
835        assert!(
836            msg.contains("belongs to no named realm") && msg.contains("varve-realms.toml"),
837            "the refusal must name the fix that exists, not a qualified form that does not: {msg}"
838        );
839        assert!(
840            !msg.contains("Both are in realm"),
841            "these two are NOT in one realm; one has none: {msg}"
842        );
843    }
844
845    // rivet: verifies REQ-COMPOSE-001
846    #[test]
847    fn a_diamond_is_walked_once_not_refused_as_a_cycle() {
848        // A includes B and C; both include D. This terminates and is the most
849        // ordinary composition shape there is — two layers sharing a base.
850        // The first version reported it as a cycle, with a message claiming D
851        // "includes itself". Found by clean-room review.
852        let d = manifest("2026.08.0", &["base"], &[]);
853        let b = manifest("2026.08.0", &["b"], &[("sha256:d", "r")]);
854        let c = manifest("2026.08.0", &["c"], &[("sha256:d", "r")]);
855        let a = manifest("2026.08.0", &["a"], &[("sha256:b", "r"), ("sha256:c", "r")]);
856        let walked = walk("sha256:a", "r", &a, |q| match q {
857            "sha256:b" => Some(b.clone()),
858            "sha256:c" => Some(c.clone()),
859            "sha256:d" => Some(d.clone()),
860            _ => None,
861        })
862        .unwrap();
863        assert_eq!(walked.len(), 4, "A, B, C and D each once: {walked:?}");
864        // …and the shared base's tool resolves exactly once, not ambiguously.
865        let tools = unchosen(&walked).unwrap();
866        assert_eq!(tools["base"].digest, "sha256:d");
867    }
868
869    // rivet: verifies REQ-COMPOSE-001
870    #[test]
871    fn a_cycle_is_refused_not_followed() {
872        // A includes B; B includes A. Following it would not terminate.
873        let a = manifest("2026.08.0", &["x"], &[("sha256:b", "r")]);
874        let b = manifest("2026.08.0", &["y"], &[("sha256:a", "r")]);
875        let (ac, bc) = (a.clone(), b.clone());
876        let err = walk("sha256:a", "r", &a, move |d| match d {
877            "sha256:b" => Some(bc.clone()),
878            "sha256:a" => Some(ac.clone()),
879            _ => None,
880        })
881        .unwrap_err();
882        assert!(matches!(err, ComposeError::Cycle { .. }), "got {err:?}");
883    }
884
885    // rivet: verifies REQ-COMPOSE-001
886    #[test]
887    fn an_uninstalled_include_is_skipped_for_the_caller_to_report() {
888        // walk() does not invent a fetch. A missing layer is the caller's
889        // error to report, with its corrective `varve install`.
890        let root = manifest("2026.08.0", &["rivet"], &[("sha256:missing", "other")]);
891        let layers = walk("sha256:root", "r", &root, |_| None).unwrap();
892        assert_eq!(layers.len(), 1, "only the root resolved");
893        assert_eq!(
894            includes(&root).len(),
895            1,
896            "but the include is still declared"
897        );
898    }
899
900    /// One payload offered by a named realm.
901    fn offered(realm: &str, name: &str, version: &str, digest: &str) -> (PayloadOrigin, ()) {
902        (
903            PayloadOrigin {
904                name: name.into(),
905                version: version.into(),
906                digest: format!("sha256:{digest}"),
907                realm: realm.into(),
908                layer: "2026.08.0".into(),
909            },
910            (),
911        )
912    }
913
914    // rivet: verifies REQ-COMPOSEEXPORT-001
915    #[test]
916    fn two_versions_of_one_crate_both_export() {
917        // Clause 2: the collision rule is NOT the tool rule. `serde 1.0.200`
918        // and `serde 1.0.210` are not ambiguous — a lockfile that names two
919        // majors of one crate NEEDS both present to build offline, and varve's
920        // own lockfile has 14 such names.
921        let kept = union_payloads(vec![
922            offered("pulseengine", "serde", "1.0.200", "aa"),
923            offered("bytecodealliance", "serde", "1.0.210", "bb"),
924        ])
925        .unwrap();
926        assert_eq!(kept.len(), 2);
927        let mut vers: Vec<&str> = kept.iter().map(|(o, _)| o.version.as_str()).collect();
928        vers.sort();
929        assert_eq!(vers, ["1.0.200", "1.0.210"]);
930    }
931
932    // rivet: verifies REQ-COMPOSEEXPORT-001
933    #[test]
934    fn the_same_name_and_version_with_the_same_bytes_exports_once() {
935        // A diamond: two layers each including the same base. Both offer the
936        // same crate at the same digest — that is two realms AGREEING, and
937        // exporting the bytes twice or refusing them both would be wrong.
938        let kept = union_payloads(vec![
939            offered("pulseengine", "cfg-if", "1.0.0", "aa"),
940            offered("bytecodealliance", "cfg-if", "1.0.0", "aa"),
941        ])
942        .unwrap();
943        assert_eq!(kept.len(), 1, "one copy of agreed bytes: {kept:?}");
944        assert_eq!(kept[0].0.realm, "pulseengine", "the first offer wins");
945    }
946
947    // rivet: verifies REQ-COMPOSEEXPORT-001
948    #[test]
949    fn the_same_name_and_version_with_different_bytes_names_both_realms() {
950        // Clause 2's error case. Two realms disagree about what `cfg-if 1.0.0`
951        // IS; picking either would put bytes one realm never vouched for into
952        // an export the consumer believes is verified. The message must name
953        // BOTH realms, or the reader cannot tell which side to fix.
954        let err = union_payloads(vec![
955            offered("pulseengine", "cfg-if", "1.0.0", "aa"),
956            offered("bytecodealliance", "cfg-if", "1.0.0", "bb"),
957        ])
958        .unwrap_err();
959        let msg = err.to_string();
960        assert!(matches!(err, ComposeError::ConflictingPayload(_)), "{msg}");
961        assert!(msg.contains("cfg-if") && msg.contains("1.0.0"), "{msg}");
962        assert!(
963            msg.contains("pulseengine") && msg.contains("bytecodealliance"),
964            "both realms must be named: {msg}"
965        );
966        assert!(
967            msg.contains("sha256:aa") && msg.contains("sha256:bb"),
968            "both digests must be named: {msg}"
969        );
970    }
971
972    // rivet: verifies REQ-COMPOSE-001
973    #[test]
974    fn a_layer_without_includes_composes_to_itself() {
975        // Back-compat: every existing layer has no `layer` entries and must
976        // behave exactly as before.
977        let plain = manifest("2026.08.0", &["rivet", "meld"], &[]);
978        assert!(includes(&plain).is_empty());
979        let layers = walk("sha256:root", "r", &plain, |_| None).unwrap();
980        assert_eq!(layers.len(), 1);
981        assert_eq!(unchosen(&layers).unwrap().len(), 2);
982    }
983}
984
985/// One layer of a composition, with the store holding it and the realm whose
986/// root vouched for it.
987#[derive(Debug, Clone)]
988pub struct ComposedLayer {
989    pub store: crate::store::Store,
990    pub entry: crate::store::InstalledLayer,
991    pub realm: String,
992}
993
994/// One payload of a composition, re-checked against its signed digest.
995#[derive(Debug, Clone)]
996pub struct VerifiedPayload {
997    pub name: String,
998    pub version: String,
999    /// The SIGNED digest, `sha256:<hex>`, re-checked against these bytes.
1000    pub digest: String,
1001    pub bytes: Vec<u8>,
1002    /// The entry's signed annotations, so an adapter reads the producer's
1003    /// declarations rather than guessing them.
1004    pub annotations: std::collections::BTreeMap<String, String>,
1005    /// The realm whose root vouched for the layer this came from, and that
1006    /// layer's id. Carried because in a composition "which version" is not
1007    /// enough to say where a tool came from — two realms can ship one name.
1008    pub realm: String,
1009    pub layer: String,
1010}
1011
1012/// Every installed layer of a composition, the pinned one first.
1013///
1014/// THE walk. `varve export-docs`, `export-cargo`, `export-sdk` and the rest
1015/// went through a copy of this in the `varve` binary; `varve-serve` could not
1016/// reach it, so it read the pinned layer's manifest alone and answered "layer
1017/// … carries no documentation" for a four-layer composition whose docs were in
1018/// one of the other three. One walk, in the crate both binaries depend on.
1019///
1020/// `trusts` maps a realm name to its trust: an included layer is verified
1021/// against the trust of the realm its include NAMES, never the composing
1022/// realm's, because that is the boundary realms exist to draw. A roles realm's
1023/// layer is judged under its LAYER keys (REQ-KEYROLES-001) and one of a realm
1024/// declaring no roles under its root. Resolving those trusts is the caller's
1025/// job (`Realm::trust`) — varve-core does not read varve-realms.toml.
1026///
1027/// Bounded and cycle-guarded: a digest reappearing on its own path is a cycle,
1028/// while a digest reachable by two paths is a DIAMOND — two layers sharing a
1029/// base, the most ordinary composition there is — and is walked once.
1030pub fn walk_installed(
1031    store: &crate::store::Store,
1032    entry: &crate::store::InstalledLayer,
1033    own_verifier: &crate::verify::PinnedKeyVerifier,
1034    own_realm: &str,
1035    trusts: &std::collections::BTreeMap<String, crate::keyroles::RealmTrust>,
1036    platform: &str,
1037) -> Result<Vec<ComposedLayer>, ComposeError> {
1038    let verifier_for = |name: &str| {
1039        trusts
1040            .get(name)
1041            .map(|t| Ok(crate::verify::PinnedKeyVerifier::from_trust(t.clone())))
1042    };
1043    walk_with(
1044        store,
1045        entry,
1046        own_verifier,
1047        own_realm,
1048        &verifier_for,
1049        platform,
1050    )
1051}
1052
1053/// How a named realm's verifier is found: `None` is an unknown realm, and
1054/// `Some(Err)` is trust material that does not build.
1055type VerifierFor<'a> = dyn Fn(&str) -> Option<Result<crate::verify::PinnedKeyVerifier, crate::install::VerifyError>>
1056    + 'a;
1057
1058fn walk_with(
1059    store: &crate::store::Store,
1060    entry: &crate::store::InstalledLayer,
1061    own_verifier: &crate::verify::PinnedKeyVerifier,
1062    own_realm: &str,
1063    verifier_for: &VerifierFor<'_>,
1064    platform: &str,
1065) -> Result<Vec<ComposedLayer>, ComposeError> {
1066    let mut out = vec![ComposedLayer {
1067        store: store.clone(),
1068        entry: entry.clone(),
1069        realm: own_realm.to_string(),
1070    }];
1071    let mut ancestors = vec![entry.digest.clone()];
1072    walk_one(
1073        store,
1074        entry,
1075        own_verifier,
1076        own_realm,
1077        verifier_for,
1078        platform,
1079        &mut ancestors,
1080        &mut out,
1081    )?;
1082    Ok(out)
1083}
1084
1085#[allow(clippy::too_many_arguments)]
1086fn walk_one(
1087    store: &crate::store::Store,
1088    layer: &crate::store::InstalledLayer,
1089    own_verifier: &crate::verify::PinnedKeyVerifier,
1090    own_realm: &str,
1091    verifier_for: &VerifierFor<'_>,
1092    platform: &str,
1093    ancestors: &mut Vec<String>,
1094    out: &mut Vec<ComposedLayer>,
1095) -> Result<(), ComposeError> {
1096    if ancestors.len() > MAX_DEPTH {
1097        return Err(ComposeError::TooDeep);
1098    }
1099    let Ok(bytes) = std::fs::read(layer.root.join("layer.json")) else {
1100        return Ok(());
1101    };
1102    let view = view(&bytes)?;
1103    for inc in &view.includes {
1104        if ancestors.contains(&inc.digest) {
1105            return Err(ComposeError::Cycle {
1106                digest: layer.digest.clone(),
1107                via: inc.digest.clone(),
1108            });
1109        }
1110        let Some((owner, entry)) = store
1111            .find_anywhere(&inc.digest)
1112            .map_err(|e| ComposeError::Io(e.to_string()))?
1113        else {
1114            return Err(ComposeError::NotInstalled {
1115                layer: layer.layer.to_string(),
1116                missing: inc.layer.clone().unwrap_or_else(|| inc.digest.clone()),
1117            });
1118        };
1119        // A layer reachable by two paths is walked once, not refused.
1120        if out.iter().any(|c| c.entry.digest == entry.digest) {
1121            continue;
1122        }
1123        // Whose root vouches for this layer? The include names a realm, and
1124        // that realm's root is authoritative for it — not ours.
1125        let named = match &inc.realm {
1126            Some(name) => {
1127                let v = verifier_for(name)
1128                    .ok_or_else(|| ComposeError::UnknownRealm {
1129                        layer: layer.layer.to_string(),
1130                        realm: name.clone(),
1131                    })?
1132                    .map_err(|e| ComposeError::Io(e.to_string()))?;
1133                Some((v, name.clone()))
1134            }
1135            None => None,
1136        };
1137        let (verifier, realm): (&crate::verify::PinnedKeyVerifier, &str) = match &named {
1138            Some((v, name)) => (v, name.as_str()),
1139            None => (own_verifier, own_realm),
1140        };
1141        crate::reverify::verify_installed(&owner, &entry, verifier, platform).map_err(|e| {
1142            ComposeError::IncludeUnverified {
1143                layer: entry.layer.to_string(),
1144                realm: realm.to_string(),
1145                detail: e.to_string(),
1146            }
1147        })?;
1148        out.push(ComposedLayer {
1149            store: owner.clone(),
1150            entry: entry.clone(),
1151            realm: realm.to_string(),
1152        });
1153        ancestors.push(entry.digest.clone());
1154        walk_one(
1155            &owner,
1156            &entry,
1157            verifier,
1158            realm,
1159            verifier_for,
1160            platform,
1161            ancestors,
1162            out,
1163        )?;
1164        ancestors.pop();
1165    }
1166    Ok(())
1167}
1168
1169/// Every payload of one kind across a whole composition, deduplicated.
1170///
1171/// The bytes are re-read from the store and re-checked against the digest the
1172/// signed manifest records, so a payload altered on disk after install is
1173/// caught here rather than handed to an adapter.
1174pub fn payloads_of(
1175    layers: &[ComposedLayer],
1176    want: crate::kind::PayloadKind,
1177    platform: &str,
1178) -> Result<Vec<VerifiedPayload>, ComposeError> {
1179    let mut offered = Vec::new();
1180    for l in layers {
1181        let bytes = std::fs::read(l.entry.root.join("layer.json"))
1182            .map_err(|e| ComposeError::Io(e.to_string()))?;
1183        let manifest = crate::manifest::LayerManifest::parse(&bytes)
1184            .map_err(|e| ComposeError::Unreadable(e.to_string()))?;
1185        for e in &manifest.entries {
1186            if e.kind()
1187                .map_err(|err| ComposeError::Unreadable(err.to_string()))?
1188                != want
1189            {
1190                continue;
1191            }
1192            // Only the payloads THIS host has: install platform-filters what
1193            // it lays down, so walking another platform's entry would compare
1194            // this machine's bytes against that entry's signed digest and
1195            // report tampering for a payload built for another machine.
1196            if !crate::platform::entry_matches(
1197                e.annotations
1198                    .get(crate::platform::ANN_PLATFORM)
1199                    .map(String::as_str),
1200                platform,
1201            ) {
1202                continue;
1203            }
1204            let Some(name) = e.annotations.get("eu.pulseengine.tool") else {
1205                continue;
1206            };
1207            let Some(path) = l.store.entry_path(&l.entry, e) else {
1208                continue;
1209            };
1210            let bytes = std::fs::read(&path).map_err(|err| ComposeError::Io(err.to_string()))?;
1211            let found = crate::store::manifest_digest(&bytes);
1212            if found != e.digest {
1213                return Err(ComposeError::Io(format!(
1214                    "payload '{name}' of layer {} does not match its signed digest {} — its                      bytes were altered after install",
1215                    l.entry.layer, e.digest
1216                )));
1217            }
1218            let version = crate::store::entry_version(e)
1219                .unwrap_or_default()
1220                .to_string();
1221            offered.push((
1222                PayloadOrigin {
1223                    name: name.clone(),
1224                    version: version.clone(),
1225                    digest: e.digest.clone(),
1226                    realm: l.realm.clone(),
1227                    layer: l.entry.layer.to_string(),
1228                },
1229                VerifiedPayload {
1230                    name: name.clone(),
1231                    version,
1232                    digest: e.digest.clone(),
1233                    bytes,
1234                    annotations: e.annotations.clone(),
1235                    realm: l.realm.clone(),
1236                    layer: l.entry.layer.to_string(),
1237                },
1238            ));
1239        }
1240    }
1241    Ok(union_payloads(offered)?
1242        .into_iter()
1243        .map(|(_, p)| p)
1244        .collect())
1245}