Skip to main content

varve_core/
resolve.rs

1//! Resolution — pin + core → exactly one layer, or a loud failure.
2//!
3//! The load-bearing rule (REQ-PIN-001): a pinned layer resolves *exactly*, or
4//! the command fails with the corrective install command. There is no fallback
5//! layer, no PATH fall-through, no "close enough" — the error type has no
6//! variant for any of those, so the fallback cannot be written.
7//!
8//! And the constraint behind it (REQ-NOUPDATE-001): resolution is a pure
9//! function of (pin, store). Nothing here consults "latest", the network, or
10//! the environment; laying a newer layer down cannot change what an existing
11//! pin resolves to.
12
13use std::path::PathBuf;
14
15use crate::pin::Pin;
16use crate::store::{InstalledLayer, Store, StoreError};
17
18/// A successful resolution: the one layer this pin selects.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Resolved {
21    pub layer: InstalledLayer,
22    /// The tools this pin exposes (the pin's `tools` subset, or every tool in
23    /// the layer), each with its resolved binary path. Exactly one entry per
24    /// NAME — that is what keeps one shim per name (REQ-REALM2-001 clause 4c).
25    pub tools: Vec<(String, PathBuf)>,
26    /// Every provider of every exposed name, including the ones a bare name
27    /// does NOT dispatch to (REQ-REALM2-001 clause 4b). Addressable as
28    /// `realm/tool`, so "compare our fork against upstream" keeps working
29    /// instead of the unselected binary disappearing.
30    pub qualified: Vec<(crate::compose::ToolProvider, PathBuf)>,
31    /// Runner contracts (REQ-RUNNER-001): tool → (runner tool, prefix args,
32    /// optional per-user-arg flag), from the signed manifest annotations.
33    pub runners: std::collections::BTreeMap<String, RunnerContract>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RunnerContract {
38    pub tool: String,
39    pub args: Vec<String>,
40    pub arg_prefix: Option<String>,
41}
42
43/// Resolution failures. Every variant carries what the user must do next.
44#[derive(Debug, thiserror::Error)]
45pub enum ResolveError {
46    #[error("layer {layer} is not installed — run `varve install` in this project to lay it down")]
47    NotInstalled { layer: String },
48    #[error(
49        "pin digest {pinned} is not installed — run `varve install` in this project to lay it down"
50    )]
51    DigestNotInstalled { pinned: String },
52    #[error(
53        "pin names layer {named} but pins digest {pinned}, which is layer {found} — the name is a label, the digest is the artifact; refusing to guess. Fix the pin."
54    )]
55    NameDigestMismatch {
56        named: String,
57        pinned: String,
58        found: String,
59    },
60    #[error(
61        "layer {layer} is installed more than once under different digests ({count} entries) and the pin carries no digest to disambiguate — add `digest = \"sha256:…\"` to the pin"
62    )]
63    Ambiguous { layer: String, count: usize },
64    #[error(
65        "layer {layer} is installed but incomplete: missing {missing:?} — run `varve install` to repair it; refusing to fall back to PATH"
66    )]
67    PartialLayer { layer: String, missing: Vec<String> },
68    #[error(
69        "this project's pin restricts `tools` to {missing:?}, which layer {layer} does not \
70         contain. It exposes: {available}. Re-installing cannot help — the layer is complete, \
71         the pin asks for something that was never in it. Fix the `tools` list in varve.toml, \
72         or drop it to expose everything the layer carries."
73    )]
74    PinNamesUnknownTool {
75        layer: String,
76        missing: Vec<String>,
77        available: String,
78    },
79    #[error(transparent)]
80    Store(#[from] StoreError),
81    #[error(
82        "layer {layer} is installed on channel '{installed}', but this project's pin selects \
83         '{pinned}' — refusing. A qualified line carries a support window and qualification \
84         evidence; a rolling one carries neither. Install the {pinned} layer, or change the \
85         pin deliberately."
86    )]
87    ChannelMismatch {
88        layer: String,
89        installed: String,
90        pinned: String,
91    },
92    #[error(transparent)]
93    Compose(#[from] crate::compose::ComposeError),
94    #[error(
95        "layer {layer} composes layer {missing}{realm}, which is not installed — \
96         `varve install` it, then retry"
97    )]
98    IncludeNotInstalled {
99        layer: String,
100        missing: String,
101        realm: String,
102    },
103}
104
105/// Resolve a pin against the local core. Pure: consults nothing but its
106/// arguments.
107pub fn resolve(pin: &Pin, store: &Store) -> Result<Resolved, ResolveError> {
108    let layer = match &pin.digest {
109        Some(digest) => {
110            let entry = store
111                .get(digest)?
112                .ok_or_else(|| ResolveError::DigestNotInstalled {
113                    pinned: digest.clone(),
114                })?;
115            if entry.layer != pin.layer {
116                return Err(ResolveError::NameDigestMismatch {
117                    named: pin.layer.to_string(),
118                    pinned: digest.clone(),
119                    found: entry.layer.to_string(),
120                });
121            }
122            entry
123        }
124        None => {
125            let matching: Vec<InstalledLayer> = store
126                .list()?
127                .into_iter()
128                .filter(|entry| entry.layer == pin.layer)
129                .collect();
130            match matching.len() {
131                0 => {
132                    return Err(ResolveError::NotInstalled {
133                        layer: pin.layer.to_string(),
134                    });
135                }
136                1 => matching.into_iter().next().expect("len checked"),
137                count => {
138                    return Err(ResolveError::Ambiguous {
139                        layer: pin.layer.to_string(),
140                        count,
141                    });
142                }
143            }
144        }
145    };
146
147    // The pin's channel is part of the pin. `install` refuses a mismatched
148    // fetch, but nothing re-checked an ALREADY-INSTALLED layer, so editing a
149    // pin from `rolling` to `qualified` left `which`, `verify` and `run`
150    // happily resolving the rolling layer — a silent fallback in the one
151    // distinction varve exists to make, and the opposite of what the docs
152    // promise ("a pin resolves exactly or the command fails").
153    if !layer.channel.is_empty() && layer.channel != pin.channel.as_str() {
154        return Err(ResolveError::ChannelMismatch {
155            layer: layer.layer.to_string(),
156            installed: layer.channel.clone(),
157            pinned: pin.channel.as_str().to_string(),
158        });
159    }
160
161    // Composition first (REQ-COMPOSE-001): a pin restricting `tools` may name a
162    // tool that lives in an INCLUDED layer, so the composed set has to be known
163    // before deciding what is missing. Resolving the root first reported
164    // `PartialLayer` for a perfectly resolvable composed tool.
165    let offers: Vec<Offer> = composition_offers(pin, &layer, store)?;
166
167    // What the pin exposes, and where it has CHOSEN a realm for a name
168    // (REQ-REALM2-001 clause 4a).
169    let (tool_names, chosen) = exposed_and_chosen(pin, &offers);
170
171    // The one decision: which provider a BARE name dispatches to. It is made
172    // over every provider the composition has, then narrowed to what the pin
173    // exposes — so a collision the pin never asked about cannot refuse a
174    // command that does not touch it.
175    let exposed: Vec<crate::compose::ToolProvider> = offers
176        .iter()
177        .filter(|o| tool_names.contains(&o.provider.tool))
178        .map(|o| o.provider.clone())
179        .collect();
180    let dispatch = crate::compose::select_tools(&exposed, &chosen)?;
181
182    let mut tools = Vec::new();
183    let mut missing = Vec::new();
184    for name in &tool_names {
185        match dispatch
186            .get(name)
187            .and_then(|p| offers.iter().find(|o| o.provider == *p))
188            .and_then(|o| o.path.clone())
189        {
190            Some(path) => tools.push((name.clone(), path)),
191            None => missing.push(name.clone()),
192        }
193    }
194    if !missing.is_empty() {
195        // A pin restricting `tools` to a name the layer never carried is NOT an
196        // incomplete install, and telling the user to re-install is a fix that
197        // cannot work: install succeeds, changes nothing, and the same error
198        // returns. A ten-persona audit graded this the one true dead end in the
199        // tool — the only error whose stated remedy provably fails.
200        if pin.tools.is_some() {
201            let mut available: Vec<String> = store
202                .manifest_tool_names(&layer)
203                .unwrap_or_default()
204                .into_iter()
205                .chain(offers.iter().map(|o| o.provider.tool.clone()))
206                .collect();
207            available.sort();
208            available.dedup();
209            let unknown: Vec<String> = missing
210                .iter()
211                .filter(|m| !available.contains(m))
212                .cloned()
213                .collect();
214            if !unknown.is_empty() {
215                return Err(ResolveError::PinNamesUnknownTool {
216                    layer: layer.layer.to_string(),
217                    missing: unknown,
218                    available: if available.is_empty() {
219                        "(nothing)".into()
220                    } else {
221                        available.join(", ")
222                    },
223                });
224            }
225        }
226        return Err(ResolveError::PartialLayer {
227            layer: layer.layer.to_string(),
228            missing,
229        });
230    }
231
232    // Clause 4b: every provider of an exposed name stays addressable, chosen
233    // or not. Losing the binary the pin did not pick would be a worse answer
234    // than the refusal this feature replaces.
235    let qualified: Vec<(crate::compose::ToolProvider, PathBuf)> = offers
236        .iter()
237        .filter(|o| tool_names.contains(&o.provider.tool))
238        .filter_map(|o| o.path.clone().map(|p| (o.provider.clone(), p)))
239        .collect();
240
241    // Runner contracts from the stored manifest's entry annotations —
242    // lenient read: legacy layers without them simply have none.
243    let mut runners = std::collections::BTreeMap::new();
244    if let Ok(bytes) = std::fs::read(layer.root.join("layer.json"))
245        && let Ok(json) = serde_json::from_slice::<serde_json::Value>(&bytes)
246        && let Some(entries) = json["manifests"].as_array()
247    {
248        for entry in entries {
249            let ann = &entry["annotations"];
250            if let (Some(tool), Some(runner)) = (
251                ann["eu.pulseengine.tool"].as_str(),
252                ann[crate::bazel::ANN_RUNNER].as_str(),
253            ) {
254                runners.insert(
255                    tool.to_string(),
256                    RunnerContract {
257                        tool: runner.to_string(),
258                        args: ann[crate::bazel::ANN_RUNNER_ARGS]
259                            .as_str()
260                            .map(|a| a.split_whitespace().map(str::to_string).collect())
261                            .unwrap_or_default(),
262                        arg_prefix: ann[crate::bazel::ANN_RUNNER_ARG_PREFIX]
263                            .as_str()
264                            .map(str::to_string),
265                    },
266                );
267            }
268        }
269    }
270    Ok(Resolved {
271        layer,
272        tools,
273        qualified,
274        runners,
275    })
276}
277
278/// Every tool name the pinned layer CARRIES: its signed manifest's tools, the
279/// files in its `bin/`, and the same for every layer it includes or composes —
280/// whether or not the pin's `tools` subset selects them (REQ-PASSTHROUGH-001
281/// clause 2). `Resolved::qualified` holds only what the pin EXPOSES, so a guard
282/// built on it lets a carried-but-unexposed tool through to an ambient binary.
283///
284/// Names are folded to ASCII lower case: on a case-insensitive filesystem the
285/// shim `PROBE` IS `probe`, so the comparison must not depend on the spelling.
286/// A carried name that is not ASCII is an `Err` too (no sound comparison
287/// exists), as is an unreadable `bin/`.
288///
289/// FAILS CLOSED: a manifest in the composition that cannot be read, or an
290/// included layer that cannot be found, is an `Err` — "we could not tell what
291/// the layer carries" must never read as "it carries nothing".
292pub fn carried_tool_names(
293    pin: &Pin,
294    layer: &InstalledLayer,
295    store: &Store,
296) -> Result<std::collections::BTreeSet<String>, String> {
297    let read = |entry: &InstalledLayer| -> Result<Vec<u8>, String> {
298        let path = entry.root.join("layer.json");
299        std::fs::read(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))
300    };
301    let root_view = crate::compose::view(&read(layer)?).map_err(|e| e.to_string())?;
302    let mut unreadable: Vec<String> = Vec::new();
303    let walked = crate::compose::walk(
304        &layer.digest,
305        &pin.realm.clone().unwrap_or_default(),
306        &root_view,
307        |digest| {
308            let view = store
309                .find_anywhere(digest)
310                .ok()
311                .flatten()
312                .and_then(|(_, entry)| std::fs::read(entry.root.join("layer.json")).ok())
313                .and_then(|bytes| crate::compose::view(&bytes).ok());
314            if view.is_none() {
315                unreadable.push(digest.to_string());
316            }
317            view
318        },
319    )
320    .map_err(|e| e.to_string())?;
321    if let Some(digest) = unreadable.first() {
322        return Err(format!(
323            "an included layer ({digest}) is not installed or its manifest cannot be read"
324        ));
325    }
326    let mut names = std::collections::BTreeSet::new();
327    for step in &walked {
328        let entry = if step.digest == layer.digest {
329            layer.clone()
330        } else {
331            match store
332                .find_anywhere(&step.digest)
333                .map_err(|e| e.to_string())?
334            {
335                Some((_, entry)) => entry,
336                None => return Err(format!("layer {} is not installed", step.digest)),
337            }
338        };
339        // The signed manifest, re-read strictly even for the root.
340        read(&entry)?;
341        names.extend(step.view.tools.iter().map(|t| t.to_ascii_lowercase()));
342        names.extend(
343            store
344                .manifest_tool_names(&entry)
345                .map_err(|e| e.to_string())?
346                .into_iter()
347                .map(|t| t.to_ascii_lowercase()),
348        );
349        // A layer with no `bin/` carries nothing there; one that cannot be
350        // listed (or an entry that cannot be read) is "we could not tell".
351        let bin = entry.root.join("bin");
352        match std::fs::read_dir(&bin) {
353            Ok(rd) => {
354                for e in rd {
355                    let e = e.map_err(|e| format!("cannot list {}: {e}", bin.display()))?;
356                    names.insert(e.file_name().to_string_lossy().to_ascii_lowercase());
357                }
358            }
359            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
360            Err(e) => return Err(format!("cannot list {}: {e}", bin.display())),
361        }
362    }
363    // Folding is ASCII only, and a filesystem may fold more (APFS: `ñ` is `Ñ`;
364    // NFC is NFD; the Kelvin sign is `k`). A non-ASCII name cannot be compared
365    // soundly, so it is "we could not tell", never "not carried".
366    if let Some(odd) = names.iter().find(|n| !n.is_ascii()) {
367        return Err(format!(
368            "the layer carries a tool name that is not ASCII ({}), which cannot be \
369             compared safely with the name requested",
370            odd.escape_default()
371        ));
372    }
373    Ok(names)
374}
375
376/// The names a pin exposes, and the realm it CHOSE for each name it qualified
377/// (REQ-REALM2-001 clause 4a).
378///
379/// A pin with no `tools` exposes the whole composition and chooses nothing —
380/// which is why an unchosen collision still refuses. A pin with `tools`
381/// exposes exactly those names, in the order written, and every qualified
382/// entry records its realm.
383fn exposed_and_chosen(
384    pin: &Pin,
385    offers: &[Offer],
386) -> (Vec<String>, std::collections::BTreeMap<String, String>) {
387    let Some(subset) = &pin.tools else {
388        let mut names: Vec<String> = offers.iter().map(|o| o.provider.tool.clone()).collect();
389        names.sort();
390        names.dedup();
391        return (names, std::collections::BTreeMap::new());
392    };
393    let mut names = Vec::with_capacity(subset.len());
394    let mut chosen = std::collections::BTreeMap::new();
395    for selector in subset {
396        names.push(selector.name.clone());
397        if let Some(realm) = &selector.realm {
398            chosen.insert(selector.name.clone(), realm.clone());
399        }
400    }
401    (names, chosen)
402}
403
404/// One layer of a composition offering one dispatchable name, and where that
405/// name's bytes are — `None` when the manifest declares a tool whose file is
406/// not on disk, which is an incomplete install rather than a missing tool.
407#[derive(Debug, Clone)]
408struct Offer {
409    provider: crate::compose::ToolProvider,
410    path: Option<PathBuf>,
411}
412
413/// Every dispatchable name the pinned layer's COMPOSITION offers — the root's
414/// own and every included layer's — each labelled with the realm whose root
415/// vouches for it. Included layers must already be installed; fetching them
416/// transitively is deliberately out of scope for v0.23.0 (REQ-COMPOSE-001), so
417/// a missing one is an error naming it and its corrective install.
418///
419/// A name is offered if the SIGNED manifest declares it or a file of that name
420/// sits in the layer's `bin/` — but only if SOME layer of the composition has
421/// it on disk. All three parts earn their place:
422///
423/// * `bin/` alone would let a corrupt install decide dispatch: a root whose
424///   declared `wasm-tools` failed to land would silently hand the bare name to
425///   an included layer, which is exactly the install-state-dependent choice
426///   clause 4c forbids. Reading the signed manifest keeps that a refusal.
427/// * the manifest alone over-reports: a layer's manifest declares a tool for
428///   EVERY platform it ships, and a tool absent for this host (loom ships no
429///   aarch64-apple-darwin) would become an exposed name nothing can resolve.
430/// * so a name no layer has on disk is dropped: on this host it is not a
431///   collision and not a dispatchable name, it is simply not here.
432fn composition_offers(
433    pin: &Pin,
434    layer: &InstalledLayer,
435    store: &Store,
436) -> Result<Vec<Offer>, ResolveError> {
437    let root_realm = pin.realm.clone().unwrap_or_default();
438    let path = layer.root.join("layer.json");
439    let root_view = match std::fs::read(&path) {
440        // A manifest we cannot read is an ERROR, not an empty composition —
441        // an earlier version returned Ok(empty) here and silently resolved a
442        // composed layer to none of its included tools.
443        Ok(bytes) => crate::compose::view(&bytes)?,
444        // No stored manifest at all: a pre-composition layer laid down by an
445        // older varve. Nothing to compose, and nothing hidden.
446        Err(_) => crate::compose::LayerView::default(),
447    };
448    // Every declared include must already be installed. Fetching transitively
449    // is deliberately out of scope (REQ-COMPOSE-001), so name it and its fix.
450    for inc in &root_view.includes {
451        // Look across partitions: a cross-realm include lives under the
452        // INCLUDED realm's fingerprint (REQ-STORE-001).
453        if store.find_anywhere(&inc.digest)?.is_none() {
454            return Err(ResolveError::IncludeNotInstalled {
455                layer: layer.layer.to_string(),
456                missing: inc.layer.clone().unwrap_or_else(|| inc.digest.clone()),
457                realm: inc
458                    .realm
459                    .as_ref()
460                    .map(|r| format!(" from realm '{r}'"))
461                    .unwrap_or_default(),
462            });
463        }
464    }
465    let walked = crate::compose::walk(&layer.digest, &root_realm, &root_view, |digest| {
466        let (_, entry) = store.find_anywhere(digest).ok().flatten()?;
467        let bytes = std::fs::read(entry.root.join("layer.json")).ok()?;
468        crate::compose::view(&bytes).ok()
469    })?;
470
471    let mut out = Vec::new();
472    for step in &walked {
473        // The root is already in hand; an included layer is looked up wherever
474        // its realm partitioned it.
475        let (owner, entry) = if step.digest == layer.digest {
476            (store.clone(), layer.clone())
477        } else {
478            match store.find_anywhere(&step.digest)? {
479                Some(found) => found,
480                None => continue,
481            }
482        };
483        let mut names: Vec<String> = step.view.tools.clone();
484        if let Ok(rd) = std::fs::read_dir(entry.root.join("bin")) {
485            names.extend(
486                rd.filter_map(|e| e.ok())
487                    .filter(|e| e.path().is_file())
488                    .map(|e| e.file_name().to_string_lossy().into_owned()),
489            );
490        }
491        names.sort();
492        names.dedup();
493        for name in names {
494            out.push(Offer {
495                path: owner.tool_path(&entry, &name),
496                provider: crate::compose::ToolProvider {
497                    tool: name,
498                    realm: step.realm.clone(),
499                    layer: entry.layer.to_string(),
500                    digest: step.digest.clone(),
501                },
502            });
503        }
504    }
505    // Drop names no layer of this composition actually has on this host. A
506    // manifest declares a tool for every platform the layer ships, so without
507    // this an unrestricted pin would expose `loom` on a machine whose platform
508    // that release skipped and then refuse to resolve it.
509    let on_disk: std::collections::BTreeSet<String> = out
510        .iter()
511        .filter(|o| o.path.is_some())
512        .map(|o| o.provider.tool.clone())
513        .collect();
514    out.retain(|o| on_disk.contains(&o.provider.tool));
515    Ok(out)
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    use crate::pin::Pin;
522    use crate::store::{Store, fixtures, manifest_digest};
523
524    fn pin(toml: &str) -> Pin {
525        Pin::parse(toml, "varve.toml").unwrap()
526    }
527
528    fn qualified_pin(layer: &str) -> Pin {
529        pin(&format!(
530            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
531        ))
532    }
533
534    fn store() -> (tempfile::TempDir, Store) {
535        let tmp = tempfile::tempdir().unwrap();
536        let store = Store::at(tmp.path().join("varve-root"));
537        (tmp, store)
538    }
539
540    /// A manifest that composes another layer by digest.
541    fn manifest_composing(layer: &str, tools: &[&str], include: &str) -> Vec<u8> {
542        let mut entries: Vec<String> = tools
543            .iter()
544            .map(|t| {
545                format!(
546                    r#"{{"digest":"sha256:{t}","annotations":{{"eu.pulseengine.tool":"{t}"}}}}"#
547                )
548            })
549            .collect();
550        entries.push(format!(
551            r#"{{"digest":"{include}","annotations":{{"eu.pulseengine.varve.kind":"layer"}}}}"#
552        ));
553        format!(
554            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","artifactType":"application/vnd.pulseengine.varve.layer.v1+json","annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.channel":"qualified"}},"manifests":[{}]}}"#,
555            entries.join(",")
556        )
557        .into_bytes()
558    }
559
560    // rivet: verifies REQ-CHANNEL-001
561    #[test]
562    fn a_pin_selecting_qualified_refuses_an_installed_rolling_layer() {
563        // THE distinction varve exists to make. `install` refused a mismatched
564        // FETCH, but nothing re-checked an already-installed layer — so editing
565        // a pin from rolling to qualified left which/verify/run resolving the
566        // rolling layer and reporting success. A safety-critical consumer would
567        // have pinned `qualified` and silently received an unqualified
568        // toolchain, with verify saying OK.
569        let (_tmp, store) = store();
570        store
571            .lay_down(
572                &fixtures::manifest("2026.07.0", "rolling"),
573                &[("synth", b"s")],
574            )
575            .unwrap();
576        let err = resolve(&qualified_pin("2026.07.0"), &store).unwrap_err();
577        match err {
578            ResolveError::ChannelMismatch {
579                installed, pinned, ..
580            } => {
581                assert_eq!(installed, "rolling");
582                assert_eq!(pinned, "qualified");
583            }
584            other => panic!("expected ChannelMismatch, got {other}"),
585        }
586    }
587
588    // rivet: verifies REQ-CHANNEL-001
589    #[test]
590    fn a_matching_channel_still_resolves() {
591        // The guard must not break the ordinary case.
592        let (_tmp, store) = store();
593        store
594            .lay_down(
595                &fixtures::manifest("2026.07.0", "qualified"),
596                &[("synth", b"s")],
597            )
598            .unwrap();
599        assert!(resolve(&qualified_pin("2026.07.0"), &store).is_ok());
600    }
601
602    // rivet: verifies REQ-CHANNEL-001
603    #[test]
604    fn the_channel_refusal_names_both_channels_and_what_they_cost() {
605        // An independent review replaced the whole #[error(...)] with the text
606        // "channel mismatch" and the entire workspace suite stayed GREEN: the
607        // existing tests assert the struct's FIELDS and never render the
608        // message a user actually reads. The clause is that the error names
609        // both channels AND what each means, so the test renders it.
610        let (_tmp, store) = store();
611        store
612            .lay_down(
613                &fixtures::manifest("2026.07.0", "rolling"),
614                &[("synth", b"s")],
615            )
616            .unwrap();
617        let msg = resolve(&qualified_pin("2026.07.0"), &store)
618            .unwrap_err()
619            .to_string();
620        assert!(msg.contains("rolling"), "names what is installed: {msg}");
621        assert!(msg.contains("qualified"), "names what is pinned: {msg}");
622        // …and why the difference is the point, not a label mismatch.
623        assert!(
624            msg.contains("support window"),
625            "says what qualified carries: {msg}"
626        );
627        assert!(
628            msg.contains("qualification evidence"),
629            "says what rolling lacks: {msg}"
630        );
631    }
632
633    // rivet: verifies REQ-CHANNEL-001
634    #[test]
635    fn a_layer_predating_channel_annotations_is_not_refused() {
636        // Deleting `!layer.channel.is_empty() &&` from the guard left the whole
637        // suite green, because every fixture in the workspace writes a channel.
638        // Without the exemption, every layer deposited before channels existed
639        // becomes unresolvable — a silent break of installed toolchains.
640        let (_tmp, store) = store();
641        store
642            .lay_down(
643                &fixtures::manifest_without_channel("2026.07.0"),
644                &[("synth", b"s")],
645            )
646            .unwrap();
647        let resolved = resolve(&qualified_pin("2026.07.0"), &store);
648        assert!(
649            resolved.is_ok(),
650            "a layer that states no channel contradicts no pin: {:?}",
651            resolved.err()
652        );
653    }
654
655    // rivet: verifies REQ-COMPOSE-001
656    #[test]
657    fn resolve_returns_the_composed_layers_tools() {
658        // The unit-level guard on composition. Mutation testing kills with
659        // `--workspace --lib`, so the CLI integration tests cannot protect this
660        // — `compose_tools -> Ok(vec![])` survived until this existed, meaning
661        // nothing noticed a composition silently resolving to nothing.
662        let (_tmp, store) = store();
663        let up = store
664            .lay_down(
665                &fixtures::manifest("2026.08.0", "qualified"),
666                &[("wasm-tools", b"w")],
667            )
668            .unwrap();
669        store
670            .lay_down(
671                &manifest_composing("2026.07.0", &["rivet"], &up),
672                &[("rivet", b"r")],
673            )
674            .unwrap();
675        let resolved = resolve(&qualified_pin("2026.07.0"), &store).unwrap();
676        let names: Vec<&str> = resolved.tools.iter().map(|(n, _)| n.as_str()).collect();
677        assert!(names.contains(&"rivet"), "own tool missing: {names:?}");
678        assert!(
679            names.contains(&"wasm-tools"),
680            "composed tool missing — the composition resolved to nothing: {names:?}"
681        );
682    }
683
684    // rivet: verifies REQ-COMPOSE-001
685    #[test]
686    fn resolve_refuses_a_tool_exposed_by_both_layers() {
687        // Kills the `n == &name` -> `!=` mutant: with the comparison inverted,
688        // the duplicate would slip through instead of being refused.
689        let (_tmp, store) = store();
690        let up = store
691            .lay_down(
692                &fixtures::manifest("2026.08.0", "qualified"),
693                &[("wasm-tools", b"u")],
694            )
695            .unwrap();
696        store
697            .lay_down(
698                &manifest_composing("2026.07.0", &["wasm-tools"], &up),
699                &[("wasm-tools", b"r")],
700            )
701            .unwrap();
702        let err = resolve(&qualified_pin("2026.07.0"), &store).unwrap_err();
703        assert!(
704            matches!(err, ResolveError::Compose(_)),
705            "a tool in two layers must be refused, got {err}"
706        );
707    }
708
709    // rivet: verifies REQ-COMPOSE-001
710    #[test]
711    fn a_pin_restricting_tools_also_restricts_the_composition() {
712        // Kills the `!subset.contains(..)` -> `subset.contains(..)` mutant:
713        // inverted, the pin would admit exactly the tools it excluded.
714        let (_tmp, store) = store();
715        let up = store
716            .lay_down(
717                &fixtures::manifest("2026.08.0", "qualified"),
718                &[("wasm-tools", b"w"), ("wkg", b"k")],
719            )
720            .unwrap();
721        store
722            .lay_down(
723                &manifest_composing("2026.07.0", &["rivet"], &up),
724                &[("rivet", b"r")],
725            )
726            .unwrap();
727        let pinned = pin(
728            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ntools = [\"rivet\", \"wasm-tools\"]\n",
729        );
730        let resolved = resolve(&pinned, &store).unwrap();
731        let names: Vec<&str> = resolved.tools.iter().map(|(n, _)| n.as_str()).collect();
732        assert!(
733            names.contains(&"wasm-tools"),
734            "selected composed tool: {names:?}"
735        );
736        assert!(
737            !names.contains(&"wkg"),
738            "the pin did not select wkg, so the composition must not add it: {names:?}"
739        );
740    }
741
742    // rivet: verifies REQ-PIN-001
743    #[test]
744    fn resolves_the_pinned_layer_by_name() {
745        let (_tmp, store) = store();
746        store
747            .lay_down(
748                &fixtures::manifest("2026.07.0", "qualified"),
749                &[("synth", b"s"), ("rivet", b"r")],
750            )
751            .unwrap();
752        let resolved = resolve(&qualified_pin("2026.07.0"), &store).unwrap();
753        assert_eq!(resolved.layer.layer.to_string(), "2026.07.0");
754        let names: Vec<&str> = resolved.tools.iter().map(|(n, _)| n.as_str()).collect();
755        assert_eq!(names, ["rivet", "synth"], "all tools, stable order");
756    }
757
758    // rivet: verifies REQ-PIN-001
759    #[test]
760    fn missing_layer_fails_with_the_corrective_command() {
761        let (_tmp, store) = store();
762        let err = resolve(&qualified_pin("2026.07.0"), &store).unwrap_err();
763        assert!(matches!(&err, ResolveError::NotInstalled { layer } if layer == "2026.07.0"));
764        assert!(
765            err.to_string().contains("varve install"),
766            "error must carry the fix: {err}"
767        );
768    }
769
770    // rivet: verifies REQ-PIN-001
771    #[test]
772    fn partial_layer_is_an_error_not_a_fallback() {
773        // The layer's MANIFEST declares both tools; only one was laid down.
774        // That is a genuinely incomplete install, and re-installing is the
775        // right advice. The fixture must declare them, or this case cannot be
776        // told apart from the one below.
777        let (_tmp, store) = store();
778        store
779            .lay_down(
780                &crate::manifest::fixtures::manifest_with_tools(
781                    "2026.07.0",
782                    "qualified",
783                    1,
784                    "2026-07-01T00:00:00Z",
785                    &[("rivet", "sha256:aa"), ("synth", "sha256:bb")],
786                ),
787                &[("rivet", b"r")],
788            )
789            .unwrap();
790        let p = pin(
791            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ntools = [\"rivet\", \"synth\"]\n",
792        );
793        match resolve(&p, &store).unwrap_err() {
794            ResolveError::PartialLayer { missing, .. } => {
795                assert_eq!(missing, vec!["synth".to_string()]);
796            }
797            other => panic!("expected PartialLayer, got: {other}"),
798        }
799    }
800
801    // rivet: verifies REQ-PIN-001
802    #[test]
803    fn a_pin_naming_a_tool_the_layer_never_had_is_not_told_to_reinstall() {
804        // A ten-persona audit graded this the ONE true dead end in the tool:
805        // `tools = ["notathing"]` produced "run `varve install` to repair it",
806        // install succeeded and changed nothing, and the same error returned.
807        // A fix that provably cannot work is worse than no advice, because the
808        // user doubts their machine rather than their pin.
809        let (_tmp, store) = store();
810        store
811            .lay_down(
812                &crate::manifest::fixtures::manifest_with_tools(
813                    "2026.07.0",
814                    "qualified",
815                    1,
816                    "2026-07-01T00:00:00Z",
817                    &[("rivet", "sha256:aa")],
818                ),
819                &[("rivet", b"r")],
820            )
821            .unwrap();
822        let p = pin(
823            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ntools = [\"notathing\"]\n",
824        );
825        match resolve(&p, &store).unwrap_err() {
826            ResolveError::PinNamesUnknownTool {
827                missing, available, ..
828            } => {
829                assert_eq!(missing, vec!["notathing".to_string()]);
830                assert!(
831                    available.contains("rivet"),
832                    "names what IS there: {available}"
833                );
834            }
835            other => panic!("expected PinNamesUnknownTool, got: {other}"),
836        }
837    }
838
839    // rivet: verifies REQ-PIN-001
840    #[test]
841    fn pinned_digest_wins_and_a_mismatching_name_is_a_hard_failure() {
842        let (_tmp, store) = store();
843        let july = fixtures::manifest("2026.07.0", "qualified");
844        store.lay_down(&july, &[("synth", b"s")]).unwrap();
845        let d_july = manifest_digest(&july);
846
847        // Pin says layer 2026.08.0 but pins July's digest: refuse loudly.
848        let hex = d_july.strip_prefix("sha256:").unwrap();
849        let p = pin(&format!(
850            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.08.0\"\ndigest = \"sha256:{hex}\"\n"
851        ));
852        let err = resolve(&p, &store).unwrap_err();
853        assert!(
854            matches!(&err, ResolveError::NameDigestMismatch { named, found, .. }
855                if named == "2026.08.0" && found == "2026.07.0"),
856            "got: {err}"
857        );
858    }
859
860    // rivet: verifies REQ-PIN-001
861    #[test]
862    fn matching_digest_pin_resolves() {
863        let (_tmp, store) = store();
864        let july = fixtures::manifest("2026.07.0", "qualified");
865        store.lay_down(&july, &[("synth", b"s")]).unwrap();
866        let hex = manifest_digest(&july)
867            .strip_prefix("sha256:")
868            .unwrap()
869            .to_string();
870        let p = pin(&format!(
871            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ndigest = \"sha256:{hex}\"\n"
872        ));
873        let resolved = resolve(&p, &store).unwrap();
874        assert_eq!(resolved.layer.layer.to_string(), "2026.07.0");
875    }
876
877    // rivet: verifies REQ-NOUPDATE-001
878    #[test]
879    fn a_newer_layer_in_the_core_cannot_change_what_a_pin_resolves_to() {
880        let (_tmp, store) = store();
881        store
882            .lay_down(
883                &fixtures::manifest("2026.07.0", "qualified"),
884                &[("synth", b"july")],
885            )
886            .unwrap();
887        let p = qualified_pin("2026.07.0");
888        let before = resolve(&p, &store).unwrap();
889
890        // A newer layer arrives. The pin must not move.
891        store
892            .lay_down(
893                &fixtures::manifest("2026.08.0", "qualified"),
894                &[("synth", b"august")],
895            )
896            .unwrap();
897        let after = resolve(&p, &store).unwrap();
898        assert_eq!(
899            before, after,
900            "resolution is a pure function of (pin, store entry)"
901        );
902        assert_eq!(after.layer.layer.to_string(), "2026.07.0");
903    }
904
905    // rivet: verifies REQ-NOUPDATE-001
906    #[test]
907    fn ambiguous_name_fails_closed_instead_of_choosing() {
908        let (_tmp, store) = store();
909        // Same layer name, two different manifests (e.g. differing counters):
910        // without a digest in the pin, refusing is the only honest answer.
911        let a = fixtures::manifest("2026.07.0", "qualified");
912        let mut b = a.clone();
913        b.extend_from_slice(b"\n");
914        store.lay_down(&a, &[]).unwrap();
915        store.lay_down(&b, &[]).unwrap();
916        let err = resolve(&qualified_pin("2026.07.0"), &store).unwrap_err();
917        assert!(
918            matches!(&err, ResolveError::Ambiguous { count: 2, .. }),
919            "got: {err}"
920        );
921    }
922
923    // rivet: verifies REQ-SCOPE-001
924    #[test]
925    fn resolution_and_listing_never_write_to_the_core() {
926        fn tree_snapshot(root: &std::path::Path) -> Vec<(String, Vec<u8>)> {
927            let mut out = Vec::new();
928            if !root.exists() {
929                return out;
930            }
931            let mut stack = vec![root.to_path_buf()];
932            while let Some(dir) = stack.pop() {
933                let mut entries: Vec<_> = std::fs::read_dir(&dir)
934                    .unwrap()
935                    .map(|e| e.unwrap().path())
936                    .collect();
937                entries.sort();
938                for path in entries {
939                    if path.is_dir() {
940                        stack.push(path);
941                    } else {
942                        out.push((path.display().to_string(), std::fs::read(&path).unwrap()));
943                    }
944                }
945            }
946            out.sort();
947            out
948        }
949
950        let (_tmp, store) = store();
951        store
952            .lay_down(
953                &fixtures::manifest("2026.07.0", "qualified"),
954                &[("synth", b"s")],
955            )
956            .unwrap();
957        let before = tree_snapshot(store.root());
958        let _ = resolve(&qualified_pin("2026.07.0"), &store).unwrap();
959        let _ = store.list().unwrap();
960        let _ = resolve(&qualified_pin("2026.09.0"), &store).unwrap_err();
961        let after = tree_snapshot(store.root());
962        assert_eq!(
963            before, after,
964            "select/verify/report must never mutate the core"
965        );
966    }
967
968    // rivet: verifies REQ-REALM2-001
969    #[test]
970    fn a_tool_the_manifest_declares_for_other_platforms_is_not_exposed_here() {
971        // A layer's manifest declares a tool for EVERY platform it ships. loom
972        // ships no aarch64-apple-darwin, so on that host the name is declared
973        // and no file lands. Exposing it would make an unrestricted pin refuse
974        // to resolve at all — caught by the two-realm system gate, where
975        // `varve verify` failed with `missing ["loom"]` on a layer that had
976        // deliberately omitted it.
977        let (_tmp, store) = store();
978        let manifest = format!(
979            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","artifactType":"application/vnd.pulseengine.varve.layer.v1+json","annotations":{{"eu.pulseengine.varve.layer":"2026.07.0","eu.pulseengine.varve.channel":"qualified"}},"manifests":[
980{{"digest":"sha256:aa","annotations":{{"eu.pulseengine.tool":"rivet","eu.pulseengine.platform":"{here}"}}}},
981{{"digest":"sha256:bb","annotations":{{"eu.pulseengine.tool":"loom","eu.pulseengine.platform":"some-other-triple"}}}}]}}"#,
982            here = crate::platform::host_platform()
983        );
984        // Only `rivet` lands, exactly as the installer would place it.
985        store
986            .lay_down(manifest.as_bytes(), &[("rivet", b"r")])
987            .unwrap();
988        let resolved = resolve(&qualified_pin("2026.07.0"), &store).unwrap();
989        let names: Vec<&str> = resolved.tools.iter().map(|(n, _)| n.as_str()).collect();
990        assert_eq!(names, ["rivet"], "loom is declared, not laid down here");
991    }
992
993    // rivet: verifies REQ-REALM2-001
994    #[test]
995    fn a_declared_tool_whose_bytes_are_missing_still_collides_with_a_composed_one() {
996        // The other half of the same rule, and the reason it reads the SIGNED
997        // manifest at all. If the root's `wasm-tools` failed to land, deciding
998        // from `bin/` alone would hand the bare name to the included layer
999        // without a word — dispatch chosen by install state, which is exactly
1000        // what clause 4c forbids. The composed layer HAS the name on disk, so
1001        // the collision is real and must still be refused.
1002        let (_tmp, store) = store();
1003        let up = manifest_composing("2026.08.0", &["wasm-tools"], "sha256:none");
1004        // Strip the include from the upstream layer: it is a leaf.
1005        let up = String::from_utf8(up).unwrap().replace(
1006            r#",{"digest":"sha256:none","annotations":{"eu.pulseengine.varve.kind":"layer"}}"#,
1007            "",
1008        );
1009        let up_digest = store
1010            .lay_down(up.as_bytes(), &[("wasm-tools", b"upstream")])
1011            .unwrap();
1012        // The root DECLARES wasm-tools and lays down only rivet.
1013        let root = manifest_composing("2026.07.0", &["wasm-tools", "rivet"], &up_digest);
1014        store.lay_down(&root, &[("rivet", b"r")]).unwrap();
1015
1016        let err = resolve(&qualified_pin("2026.07.0"), &store).unwrap_err();
1017        let msg = err.to_string();
1018        assert!(
1019            msg.contains("provided by more than one layer"),
1020            "a half-installed root must not silently yield the name: {msg}"
1021        );
1022    }
1023
1024    // rivet: verifies REQ-PASSTHROUGH-001
1025    #[test]
1026    fn carried_names_cover_the_whole_composition_whatever_the_pin_selects() {
1027        // Clause 2. The pin exposes `rivet` only; the layer also carries `Loom`
1028        // (manifest only, no bytes on this host) and `ghost` (bin/ only), and
1029        // composes `Wasm-Tools`. All of them are CARRIED, folded to lower case.
1030        let (_tmp, store) = store();
1031        let up = store
1032            .lay_down(
1033                &fixtures::manifest("2026.08.0", "qualified"),
1034                &[("Wasm-Tools", b"w")],
1035            )
1036            .unwrap();
1037        store
1038            .lay_down(
1039                &manifest_composing("2026.07.0", &["rivet", "Loom"], &up),
1040                &[("rivet", b"r"), ("ghost", b"g")],
1041            )
1042            .unwrap();
1043        let mut p = qualified_pin("2026.07.0");
1044        p.tools = Some(vec![crate::pin::ToolSelector {
1045            name: "rivet".into(),
1046            realm: None,
1047        }]);
1048        let layer = resolve(&p, &store).unwrap().layer;
1049        let names = carried_tool_names(&p, &layer, &store).unwrap();
1050        let got: Vec<&str> = names.iter().map(String::as_str).collect();
1051        assert_eq!(got, ["ghost", "loom", "rivet", "wasm-tools"]);
1052    }
1053
1054    // rivet: verifies REQ-PASSTHROUGH-001
1055    #[test]
1056    fn carried_names_fail_closed_when_a_manifest_cannot_be_read() {
1057        let (_tmp, store) = store();
1058        let up = store
1059            .lay_down(
1060                &fixtures::manifest("2026.08.0", "qualified"),
1061                &[("w", b"w")],
1062            )
1063            .unwrap();
1064        store
1065            .lay_down(
1066                &manifest_composing("2026.07.0", &["rivet"], &up),
1067                &[("rivet", b"r")],
1068            )
1069            .unwrap();
1070        let p = qualified_pin("2026.07.0");
1071        let layer = resolve(&p, &store).unwrap().layer;
1072        assert!(carried_tool_names(&p, &layer, &store).is_ok());
1073
1074        // The included layer's manifest vanishes: we cannot say what it carries.
1075        let inc = store.get(&up).unwrap().unwrap();
1076        std::fs::remove_file(inc.root.join("layer.json")).unwrap();
1077        assert!(carried_tool_names(&p, &layer, &store).is_err());
1078
1079        // So does the root's own.
1080        std::fs::remove_file(layer.root.join("layer.json")).unwrap();
1081        assert!(carried_tool_names(&p, &layer, &store).is_err());
1082    }
1083
1084    // rivet: verifies REQ-PASSTHROUGH-001
1085    #[test]
1086    fn a_carried_name_that_is_not_ascii_is_an_error_not_a_name() {
1087        // ASCII folding cannot compare it with a filesystem's own folding.
1088        let (_tmp, store) = store();
1089        store
1090            .lay_down(
1091                &fixtures::manifest("2026.07.0", "qualified"),
1092                &[("rivet", b"r"), ("\u{f1}", b"n")],
1093            )
1094            .unwrap();
1095        let p = qualified_pin("2026.07.0");
1096        let layer = resolve(&p, &store).unwrap().layer;
1097        let why = carried_tool_names(&p, &layer, &store).unwrap_err();
1098        assert!(why.contains("not ASCII"), "{why}");
1099    }
1100
1101    // rivet: verifies REQ-PASSTHROUGH-001
1102    #[cfg(unix)]
1103    #[test]
1104    fn carried_names_fail_closed_when_bin_cannot_be_listed() {
1105        use std::os::unix::fs::PermissionsExt;
1106        let (_tmp, store) = store();
1107        store
1108            .lay_down(
1109                &fixtures::manifest("2026.07.0", "qualified"),
1110                &[("rivet", b"r")],
1111            )
1112            .unwrap();
1113        let p = qualified_pin("2026.07.0");
1114        let layer = resolve(&p, &store).unwrap().layer;
1115        assert!(carried_tool_names(&p, &layer, &store).is_ok());
1116        let bin = layer.root.join("bin");
1117        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o000)).unwrap();
1118        let unlistable = std::fs::read_dir(&bin).is_err();
1119        let got = carried_tool_names(&p, &layer, &store);
1120        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
1121        // Skip only where permission bits are not enforced (running as root).
1122        if !unlistable {
1123            return;
1124        }
1125        assert!(
1126            got.is_err(),
1127            "an unlistable bin/ read as 'carries nothing there'"
1128        );
1129    }
1130
1131    // rivet: verifies REQ-PASSTHROUGH-001
1132    #[test]
1133    fn a_layer_with_no_bin_directory_carries_just_its_manifest_names() {
1134        // NotFound is the one error that is not an error: nothing is there.
1135        let (_tmp, store) = store();
1136        store
1137            .lay_down(
1138                &fixtures::manifest("2026.07.0", "qualified"),
1139                &[("rivet", b"r")],
1140            )
1141            .unwrap();
1142        let p = qualified_pin("2026.07.0");
1143        let layer = resolve(&p, &store).unwrap().layer;
1144        std::fs::remove_dir_all(layer.root.join("bin")).unwrap();
1145        assert!(carried_tool_names(&p, &layer, &store).is_ok());
1146    }
1147}