midenup 1.0.1

The Miden toolchain manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! Building a staged installation tree and checking it before it is published.

use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    path::{Path, PathBuf},
};

use colored::Colorize;

use crate::{
    install::{CargoError, ExecError, ExtractError},
    plan::{InstallationPlan, PlanStep},
    state::{RealizedMethod, Receipt},
    utils,
};

#[derive(Debug, thiserror::Error)]
pub enum StageError {
    #[error(transparent)]
    Acquire(#[from] ExecError),
    #[error(transparent)]
    Cargo(#[from] CargoError),
    #[error(transparent)]
    Extract(#[from] ExtractError),
    #[error("failed to create '{path}': {source}")]
    Create {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("component '{owner}' was installed, but '{path}' is missing")]
    Missing { owner: String, path: PathBuf },
    #[error("component '{owner}' installed '{path}', but it is not a regular file")]
    NotAFile { owner: String, path: PathBuf },
    #[error("component '{owner}' installed '{path}' with mode {found:o}, expected {expected:o}")]
    WrongMode {
        owner: String,
        path: PathBuf,
        expected: u32,
        found: u32,
    },
    #[error("the shim '{path}' was not created")]
    MissingSymlink { path: PathBuf },
    #[error("failed to carry '{path}' forward from the previous installation: {source}")]
    Seed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("component '{owner}' declares a fallback that cannot be executed as one")]
    UnsupportedFallback { owner: String },
}

/// How each destination in a staged tree was actually produced.
pub type Realized = BTreeMap<PathBuf, RealizedMethod>;

/// The publication a new one is being built from.
///
/// Seeding is what makes an update cheap -- unchanged files are copied rather than re-fetched --
/// but it is also how an update can silently carry stale content forward, so it is scoped
/// deliberately: only files the previous receipt *owns*, only those the new plan still wants, and
/// never those of a component known to have changed.
pub struct Seed<'a> {
    /// The previous publication's directory.
    pub publication: &'a Path,
    /// What that publication owns. Nothing outside it is carried forward, whatever is on disk.
    pub receipt: &'a Receipt,
    /// Components whose files must be re-acquired rather than reused.
    pub stale: &'a [String],
}

/// The subdirectories every staged tree has.
///
/// Created up front so a step never has to reason about whether its parent exists.
const LAYOUT: &[&str] = &["bin", "lib", "etc", "opt"];

/// Prepares an empty staged tree at `into`.
pub fn prepare(into: &Path) -> Result<(), StageError> {
    for dir in std::iter::once(into.to_path_buf()).chain(LAYOUT.iter().map(|name| into.join(name)))
    {
        std::fs::create_dir_all(&dir).map_err(|source| StageError::Create { path: dir, source })?;
    }
    Ok(())
}

/// Copies forward everything `from` owns that the new plan still wants.
///
/// Deliberately *not* a directory copy. Copying the old toolchain tree wholesale would carry
/// forward anything that had ever landed there -- files of components since removed upstream,
/// leftovers from an interrupted install, Cargo's own bookkeeping -- and leave no way to tell
/// inherited content from installed content. The receipt is the ownership record, so it is the
/// only thing consulted here.
pub fn seed(plan: &InstallationPlan, into: &Path, from: &Seed<'_>) -> Result<(), StageError> {
    let wanted: HashSet<&Path> = plan.steps.iter().map(|step| step.dest()).collect();

    for output in &from.receipt.outputs {
        if from.stale.iter().any(|name| name == &output.owner) {
            continue;
        }

        let dest = into.join(&output.path);
        if !wanted.contains(dest.as_path()) {
            // Not part of the new installation. Omitting it here is how components removed
            // upstream stop being installed.
            continue;
        }

        let src = from.publication.join(&output.path);
        // A missing source is not a failure: the step below simply acquires it instead. Refusing
        // to proceed would turn a partially cleaned-up publication into an unrecoverable one.
        if !src.is_file() {
            continue;
        }

        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|source| StageError::Seed { path: dest.clone(), source })?;
        }
        crate::trace!("seeding {} from the previous publication", dest.display());
        std::fs::copy(&src, &dest)
            .map_err(|source| StageError::Seed { path: dest.clone(), source })?;
    }

    // Note what is *not* here: `var/`. It lives at `$MIDENUP_HOME/var/<channel>`, outside every
    // publication, so there is nothing to carry forward and no way for staging to disturb it.
    Ok(())
}

/// Runs every step of `plan` into `staging_root`, then creates the `opt/` shims.
///
/// A step whose destination already exists is skipped: it was seeded from the previous
/// publication, and [seed] only carries forward what is still current.
///
/// The check is against the step's *exact* destination, never a containing directory: `lib/`
/// exists as soon as the tree is prepared, so testing it would be true from the start and skip
/// every package download.
///
/// Returns how each destination was actually produced, which is not always what the plan declared:
/// see [PlanStep::fallback].
pub fn execute(
    plan: &InstallationPlan,
    staging_root: &Path,
    verbose: bool,
    debug: bool,
) -> Result<Realized, StageError> {
    let mut pending_extractions = Vec::new();
    let mut realized = Realized::new();
    let mut announced = BTreeSet::new();

    let planned = planned_announcements(plan);
    announce_summary(&planned);
    let mut progress = Progress { done: 0, total: planned.len() };

    for step in &plan.steps {
        if step.dest().exists() {
            crate::trace!(
                "carried forward from the previous publication: {}",
                step.dest().display()
            );
            continue;
        }

        // Collected so that every package sharing a crate is extracted by one script.
        if matches!(step, PlanStep::ExtractPackage { .. }) {
            pending_extractions.push(step.clone());
            continue;
        }

        announce(step, &mut announced, Some(&mut progress));

        let method = match run(step, staging_root, verbose, debug) {
            Ok(method) => method,
            Err(err) => {
                // A declared Cargo fallback is what makes an unavailable artifact recoverable
                // rather than fatal. Only one retry: if the build fails too, the original
                // acquisition failure is not the interesting one.
                let Some(fallback) = step.fallback() else {
                    return Err(err);
                };
                crate::warn!("could not acquire {}: {err}", step.owner().bold());
                announce(fallback, &mut announced, None);
                run(fallback, staging_root, verbose, debug)?
            },
        };

        realized.insert(step.dest().to_path_buf(), method);
    }

    if !pending_extractions.is_empty() {
        for step in &pending_extractions {
            announce(step, &mut announced, Some(&mut progress));
        }
        let script = staging_root.join("extract").with_extension("rs");
        crate::install::extract(&pending_extractions, &script, verbose)?;
        // The script is a build artefact, not part of the toolchain.
        let _ = std::fs::remove_file(&script);
        for step in &pending_extractions {
            realized.insert(step.dest().to_path_buf(), RealizedMethod::Extracted);
        }
    }

    create_symlinks(plan, staging_root)?;

    Ok(realized)
}

/// The kind of work a step performs, as the announcements name it.
fn action_of(step: &PlanStep) -> &'static str {
    match step {
        PlanStep::Download { .. } => "downloading",
        PlanStep::CopyLocal { .. } => "copying",
        PlanStep::CargoBuild { .. } => "building",
        PlanStep::ExtractPackage { .. } => "extracting",
    }
}

/// How far through the announcements the install is. A position in a list, not an estimate of
/// time remaining: the steps are wildly unequal.
struct Progress {
    done: usize,
    total: usize,
}

/// Every announcement this plan will make, deduplicated and filtered exactly as [announce] is, so
/// the counter always reaches its total.
fn planned_announcements(plan: &InstallationPlan) -> Vec<(String, &'static str)> {
    let mut seen = BTreeSet::new();
    let mut planned = Vec::new();

    for step in &plan.steps {
        if step.dest().exists() {
            continue;
        }
        let entry = (step.owner().to_string(), action_of(step));
        if seen.insert(entry.clone()) {
            planned.push(entry);
        }
    }

    planned
}

/// States what kind of work is ahead before any of it starts, chiefly so a multi-minute source
/// build is known about before the pause it causes.
fn announce_summary(planned: &[(String, &'static str)]) {
    if let Some(summary) = summarize(planned) {
        crate::info!("{summary}");
    }
}

fn summarize(planned: &[(String, &'static str)]) -> Option<String> {
    if planned.is_empty() {
        return None;
    }

    // A fixed order, so the same plan reads the same way every time.
    let described: Vec<String> = ["downloading", "copying", "building", "extracting"]
        .into_iter()
        .filter_map(|action| {
            let count = planned.iter().filter(|(_, kind)| *kind == action).count();
            if count == 0 {
                return None;
            }
            let (singular, plural) = match action {
                "downloading" => ("download", "downloads"),
                "copying" => ("copy", "copies"),
                "building" => ("source build", "source builds"),
                _ => ("extraction", "extractions"),
            };
            Some(format!("{count} {}", if count == 1 { singular } else { plural }))
        })
        .collect();

    let steps = if planned.len() == 1 { "step" } else { "steps" };
    Some(format!("{} {steps}: {}", planned.len(), described.join(", ")))
}

/// Announces the work a step is about to do, once per component and kind of work.
///
/// `progress` is absent for an unplanned step (a taken fallback), which is left un-numbered rather
/// than pushed past a total fixed before the run began.
fn announce(
    step: &PlanStep,
    announced: &mut BTreeSet<(String, &'static str)>,
    progress: Option<&mut Progress>,
) {
    let action = action_of(step);
    if !announced.insert((step.owner().to_string(), action)) {
        return;
    }

    // Where a source build is the one thing a user is most likely to want to know about, because
    // it is the one that takes minutes rather than seconds.
    let source = if matches!(step, PlanStep::CargoBuild { .. }) {
        " from source"
    } else {
        ""
    };

    match progress {
        Some(progress) => {
            progress.done += 1;
            crate::info!(
                "[{}/{}] {action} component '{}'{source}",
                progress.done,
                progress.total,
                step.owner().bold()
            );
        },
        None => crate::info!("{action} component '{}'{source}", step.owner().bold()),
    }
}

/// Performs one step, reporting how its output was produced.
fn run(
    step: &PlanStep,
    staging_root: &Path,
    verbose: bool,
    debug: bool,
) -> Result<RealizedMethod, StageError> {
    match step {
        PlanStep::Download { .. } | PlanStep::CopyLocal { .. } => {
            crate::install::acquire(step)?;
            Ok(RealizedMethod::Prebuilt)
        },
        PlanStep::CargoBuild { .. } => {
            crate::install::cargo_build(step, staging_root, verbose, debug)?;
            Ok(RealizedMethod::Cargo)
        },
        // Extractions are batched into a single generated script, so one cannot be run alone --
        // which also means one can never be a fallback.
        PlanStep::ExtractPackage { .. } => {
            Err(StageError::UnsupportedFallback { owner: step.owner().to_string() })
        },
    }
}

/// Creates the `opt/` shims described by the plan.
fn create_symlinks(plan: &InstallationPlan, staging_root: &Path) -> Result<(), StageError> {
    let opt = staging_root.join("opt");
    for symlink in &plan.symlinks {
        let link = opt.join(&symlink.name);
        if std::fs::symlink_metadata(&link).is_ok() {
            continue;
        }
        // Relative, so the shim keeps working when the publication directory is renamed or
        // reached through a different path.
        let target = Path::new("..").join("bin").join(&symlink.target_binary);
        crate::trace!("linking {} -> {}", link.display(), target.display());
        utils::fs::symlink(&link, &target).map_err(|err| StageError::Create {
            path: link,
            source: std::io::Error::other(err.to_string()),
        })?;
    }
    Ok(())
}

/// Checks the staged tree structurally, before anything is published.
///
/// Structural only: that each planned file exists, is a regular file, and carries the planned
/// mode. Contents are deliberately not verified -- digests are recorded but never checked -- so
/// this makes no claim about *what* was installed, only that the plan was carried out.
pub fn verify(plan: &InstallationPlan, staging_root: &Path) -> Result<(), StageError> {
    for step in &plan.steps {
        let path = step.dest();
        let metadata = match std::fs::symlink_metadata(path) {
            Ok(metadata) => metadata,
            Err(_) => {
                return Err(StageError::Missing {
                    owner: step.owner().to_string(),
                    path: path.to_path_buf(),
                });
            },
        };

        if !metadata.is_file() {
            return Err(StageError::NotAFile {
                owner: step.owner().to_string(),
                path: path.to_path_buf(),
            });
        }

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            let found = metadata.permissions().mode() & 0o777;
            let expected = step.mode();
            if found != expected {
                return Err(StageError::WrongMode {
                    owner: step.owner().to_string(),
                    path: path.to_path_buf(),
                    expected,
                    found,
                });
            }
        }
    }

    let opt = staging_root.join("opt");
    for symlink in &plan.symlinks {
        let link = opt.join(&symlink.name);
        if std::fs::symlink_metadata(&link).is_err() {
            return Err(StageError::MissingSymlink { path: link });
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;
    use crate::{
        artifact::{Artifact, Artifacts},
        manifest::{Channel, Component, ComponentKind, ExecutableComponent, InstallationMethod},
        plan::{MODE_DATA, MODE_EXECUTABLE, build_plan},
        profile::Profile,
        resolve::Intent,
        state::Output,
        version::Authority,
    };

    const TARGET: &str = "aarch64-apple-darwin";

    #[test]
    fn a_one_step_summary_is_singular() {
        let planned = [("vm".to_string(), "building")];
        assert_eq!(summarize(&planned).as_deref(), Some("1 step: 1 source build"));
    }

    /// A channel with one prebuilt executable and one package, both sourced from local files.
    fn fixture(root: &Path) -> (Channel, PathBuf) {
        let sources = root.join("sources");
        std::fs::create_dir_all(&sources).unwrap();
        std::fs::write(sources.join("miden-vm"), b"binary").unwrap();
        std::fs::write(sources.join("core.masp"), b"package").unwrap();

        let uri = |name: &str| format!("file://{}", sources.join(name).display());
        let artifact = |name: &str| Artifact::TargetAgnostic {
            uri: uri(name),
            digest: None,
            archive: None,
            extra: Default::default(),
        };

        let mut vm_artifacts = Artifacts::default();
        vm_artifacts.insert("miden-vm".to_string(), artifact("miden-vm"));
        let mut core_artifacts = Artifacts::default();
        core_artifacts.insert("core.masp".to_string(), artifact("core.masp"));

        let component = |name: &'static str, kind, artifacts| Component {
            name: Cow::Borrowed(name),
            version: Authority::Registry { version: semver::Version::new(0, 1, 0) },
            kind,
            profiles: vec![Profile::Minimal],
            requires: vec![],
            artifacts,
            extra: Default::default(),
        };

        let channel = Channel::new(
            semver::Version::new(0, 15, 0),
            vec![
                component(
                    "vm",
                    ComponentKind::Executable {
                        installation_method: InstallationMethod::Prebuilt,
                        spec: ExecutableComponent {
                            installed_executable: "miden-vm".to_string(),
                            ..Default::default()
                        },
                    },
                    vm_artifacts,
                ),
                component("core", ComponentKind::Package, core_artifacts),
            ],
        );

        (channel, sources)
    }

    fn staged(root: &Path) -> (InstallationPlan, PathBuf) {
        let (channel, _) = fixture(root);
        let staging = root.join("staging");
        let plan = build_plan(&channel, &Intent::new(&[Profile::Complete], &[]), TARGET, &staging)
            .expect("should plan");
        (plan, staging)
    }

    #[test]
    fn a_staged_tree_contains_every_planned_file() {
        let temp = tempdir::TempDir::new("stage-ok").unwrap();
        let (plan, staging) = staged(temp.path());

        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).expect("should stage");
        verify(&plan, &staging).expect("should verify");

        assert_eq!(std::fs::read(staging.join("bin").join("miden-vm")).unwrap(), b"binary");
        assert_eq!(std::fs::read(staging.join("lib").join("core.masp")).unwrap(), b"package");
    }

    #[test]
    fn the_planned_modes_are_applied() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            let temp = tempdir::TempDir::new("stage-modes").unwrap();
            let (plan, staging) = staged(temp.path());
            prepare(&staging).unwrap();
            execute(&plan, &staging, false, true).unwrap();

            let mode =
                |path: PathBuf| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode(staging.join("bin").join("miden-vm")), MODE_EXECUTABLE);
            assert_eq!(
                mode(staging.join("lib").join("core.masp")),
                MODE_DATA,
                "packages are data, not programs"
            );
        }
    }

    #[test]
    fn shims_are_created_and_point_into_bin() {
        let temp = tempdir::TempDir::new("stage-shims").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).unwrap();

        let shim = staging.join("opt").join("miden vm");
        let target = std::fs::read_link(&shim).expect("the shim must be a symlink");
        assert_eq!(
            target,
            Path::new("..").join("bin").join("miden-vm"),
            "relative, so it survives the publication directory being renamed"
        );
    }

    /// Verification must notice a file the plan promised but staging did not produce.
    #[test]
    fn a_missing_file_fails_verification() {
        let temp = tempdir::TempDir::new("stage-missing").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).unwrap();

        std::fs::remove_file(staging.join("lib").join("core.masp")).unwrap();
        let err = verify(&plan, &staging).expect_err("must fail");
        assert!(matches!(err, StageError::Missing { .. }), "{err}");
    }

    #[test]
    fn a_wrong_mode_fails_verification() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            let temp = tempdir::TempDir::new("stage-mode").unwrap();
            let (plan, staging) = staged(temp.path());
            prepare(&staging).unwrap();
            execute(&plan, &staging, false, true).unwrap();

            std::fs::set_permissions(
                staging.join("bin").join("miden-vm"),
                std::fs::Permissions::from_mode(0o644),
            )
            .unwrap();
            let err = verify(&plan, &staging).expect_err("must fail");
            assert!(matches!(err, StageError::WrongMode { .. }), "{err}");
        }
    }

    #[test]
    fn a_missing_shim_fails_verification() {
        let temp = tempdir::TempDir::new("stage-shim").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).unwrap();

        std::fs::remove_file(staging.join("opt").join("miden vm")).unwrap();
        let err = verify(&plan, &staging).expect_err("must fail");
        assert!(matches!(err, StageError::MissingSymlink { .. }), "{err}");
    }

    /// A directory where a file was planned must not pass: verification is against the exact
    /// destination, not a containing directory that exists as soon as the tree is prepared.
    #[test]
    fn a_directory_where_a_file_was_planned_fails_verification() {
        let temp = tempdir::TempDir::new("stage-dir").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).unwrap();

        let path = staging.join("lib").join("core.masp");
        std::fs::remove_file(&path).unwrap();
        std::fs::create_dir(&path).unwrap();

        let err = verify(&plan, &staging).expect_err("must fail");
        assert!(matches!(err, StageError::NotAFile { .. }), "{err}");
    }

    /// Re-staging an already complete tree must be a no-op, which is what makes updates cheap.
    #[test]
    fn staging_is_idempotent() {
        let temp = tempdir::TempDir::new("stage-idempotent").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        execute(&plan, &staging, false, true).unwrap();

        // Mark the file so a re-download would be detectable.
        let marked = staging.join("bin").join("miden-vm");
        std::fs::write(&marked, b"marked").unwrap();

        execute(&plan, &staging, false, true).expect("re-staging must succeed");
        assert_eq!(
            std::fs::read(&marked).unwrap(),
            b"marked",
            "an existing file must not be re-fetched"
        );
    }

    /// A previous publication with `bin/miden-vm`, `lib/core.masp` and a file it does not own.
    fn previous_publication(root: &Path) -> (PathBuf, Receipt) {
        let dir = root.join("previous");
        prepare(&dir).unwrap();
        std::fs::write(dir.join("bin").join("miden-vm"), b"old-binary").unwrap();
        std::fs::write(dir.join("lib").join("core.masp"), b"old-package").unwrap();
        std::fs::write(dir.join("lib").join("stray.masp"), b"nobody-owns-me").unwrap();

        let output = |path: PathBuf, owner: &str, mode| Output {
            path,
            owner: owner.to_string(),
            mode,
            realized: RealizedMethod::Prebuilt,
            digest: None,
        };

        let receipt = Receipt {
            publication_id: crate::state::PublicationId::generate(),
            plan_key: serde_json::from_str(&format!("\"pk1:{}\"", "a".repeat(64))).unwrap(),
            target: TARGET.to_string(),
            channel: semver::Version::new(0, 15, 0),
            outputs: vec![
                output(PathBuf::from("bin").join("miden-vm"), "vm", MODE_EXECUTABLE),
                output(PathBuf::from("lib").join("core.masp"), "core", MODE_DATA),
            ],
        };

        (dir, receipt)
    }

    /// Seeding copies what the previous receipt owns and nothing else, so an unowned file sitting
    /// in the old publication -- a leftover from an interrupted install, a file of a component
    /// since removed -- is not inherited by the new one.
    #[test]
    fn seeding_copies_only_paths_the_old_receipt_owns() {
        let temp = tempdir::TempDir::new("stage-seed-owned").unwrap();
        let (previous, receipt) = previous_publication(temp.path());
        let (plan, staging) = staged(temp.path());

        prepare(&staging).unwrap();
        seed(
            &plan,
            &staging,
            &Seed {
                publication: &previous,
                receipt: &receipt,
                stale: &[],
            },
        )
        .expect("should seed");

        assert_eq!(
            std::fs::read(staging.join("bin").join("miden-vm")).unwrap(),
            b"old-binary",
            "an owned, still-planned file must be carried forward"
        );
        assert!(
            !staging.join("lib").join("stray.masp").exists(),
            "an unowned file must not be carried forward"
        );
    }

    /// A file the previous publication owned but the new plan does not want is simply not seeded,
    /// which is how a component removed upstream stops being installed.
    #[test]
    fn files_not_in_the_new_plan_are_not_seeded() {
        let temp = tempdir::TempDir::new("stage-seed-dropped").unwrap();
        let (previous, mut receipt) = previous_publication(temp.path());
        std::fs::write(previous.join("bin").join("miden-debug"), b"old-debug").unwrap();
        receipt.outputs.push(Output {
            path: PathBuf::from("bin").join("miden-debug"),
            owner: "debug".to_string(),
            mode: MODE_EXECUTABLE,
            realized: RealizedMethod::Prebuilt,
            digest: None,
        });

        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();
        seed(
            &plan,
            &staging,
            &Seed {
                publication: &previous,
                receipt: &receipt,
                stale: &[],
            },
        )
        .unwrap();

        assert!(!staging.join("bin").join("miden-debug").exists());
    }

    /// A component known to have changed must be re-acquired, not reused -- otherwise an update
    /// that keeps a destination's name would silently keep its old contents.
    #[test]
    fn a_stale_component_is_re_acquired_rather_than_seeded() {
        let temp = tempdir::TempDir::new("stage-seed-stale").unwrap();
        let (previous, receipt) = previous_publication(temp.path());
        let (plan, staging) = staged(temp.path());

        prepare(&staging).unwrap();
        seed(
            &plan,
            &staging,
            &Seed {
                publication: &previous,
                receipt: &receipt,
                stale: &["vm".to_string()],
            },
        )
        .unwrap();
        execute(&plan, &staging, false, true).unwrap();

        assert_eq!(
            std::fs::read(staging.join("bin").join("miden-vm")).unwrap(),
            b"binary",
            "a stale component must be re-acquired"
        );
        assert_eq!(
            std::fs::read(staging.join("lib").join("core.masp")).unwrap(),
            b"old-package",
            "an unchanged component must still be reused"
        );
    }

    /// Staging must never create `var/` inside a publication. It lives outside, keyed by channel,
    /// precisely so that replacing a publication cannot touch it.
    #[test]
    fn staging_never_creates_var_inside_a_publication() {
        let temp = tempdir::TempDir::new("stage-no-var").unwrap();
        let (previous, receipt) = previous_publication(temp.path());
        let (plan, staging) = staged(temp.path());

        prepare(&staging).unwrap();
        seed(
            &plan,
            &staging,
            &Seed {
                publication: &previous,
                receipt: &receipt,
                stale: &[],
            },
        )
        .unwrap();
        execute(&plan, &staging, false, true).unwrap();

        assert!(!staging.join("var").exists());
    }

    /// Every destination the run produced is reported, so the receipt can record how each file was
    /// really obtained rather than how the plan said it would be.
    #[test]
    fn execution_reports_how_each_destination_was_produced() {
        let temp = tempdir::TempDir::new("stage-realized").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();

        let realized = execute(&plan, &staging, false, true).unwrap();
        assert_eq!(
            realized.get(&staging.join("bin").join("miden-vm")),
            Some(&RealizedMethod::Prebuilt)
        );
        assert_eq!(
            realized.get(&staging.join("lib").join("core.masp")),
            Some(&RealizedMethod::Prebuilt)
        );
    }

    /// A transfer failure with no declared fallback stays fatal.
    #[test]
    fn a_failed_transfer_without_a_fallback_is_fatal() {
        let temp = tempdir::TempDir::new("stage-nofallback").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();

        let mut plan = plan;
        let dest = staging.join("bin").join("miden-vm");
        plan.steps[0] = PlanStep::CopyLocal {
            src: temp.path().join("does-not-exist"),
            dest,
            mode: MODE_EXECUTABLE,
            owner: "vm".to_string(),
            archive: None,
            fallback: None,
        };

        assert!(execute(&plan, &staging, false, true).is_err());
    }

    /// Spec section 9.3: a failed transfer for a component declaring a fallback is recoverable,
    /// not fatal -- the fallback carried by the step runs in its place, and what *actually*
    /// produced the file is reported, because uninstall has to match the path really taken.
    ///
    /// The planner only ever puts a Cargo build here; this substitutes a copy so the test does not
    /// invoke Cargo, which is exactly why the field holds a whole step rather than build
    /// arguments.
    #[test]
    fn a_taken_fallback_reports_its_own_method() {
        let temp = tempdir::TempDir::new("stage-fallback-ok").unwrap();
        let (plan, staging) = staged(temp.path());
        prepare(&staging).unwrap();

        let replacement = temp.path().join("replacement");
        std::fs::write(&replacement, b"from-the-fallback").unwrap();

        let mut plan = plan;
        let dest = staging.join("bin").join("miden-vm");
        plan.steps[0] = PlanStep::CopyLocal {
            src: temp.path().join("does-not-exist"),
            dest: dest.clone(),
            mode: MODE_EXECUTABLE,
            owner: "vm".to_string(),
            archive: None,
            fallback: Some(Box::new(PlanStep::CopyLocal {
                src: replacement,
                dest: dest.clone(),
                mode: MODE_EXECUTABLE,
                owner: "vm".to_string(),
                archive: None,
                fallback: None,
            })),
        };

        let realized = execute(&plan, &staging, false, true).expect("the fallback must be taken");
        assert_eq!(std::fs::read(&dest).unwrap(), b"from-the-fallback");
        assert_eq!(realized.get(&dest), Some(&RealizedMethod::Prebuilt));
    }
}