midenup 1.0.0

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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Structural validation of a channel manifest.
//!
//! Deliberately **platform-neutral**: a manifest is not invalid because *this* machine cannot
//! install one of its components. Whether an artifact exists for the current target, and whether
//! the component/artifact cardinality matrix holds for a selected target, are decided when an
//! installation plan is built -- not here. Conflating the two would make a manifest "invalid" on a
//! Mac and valid on Linux.
//!
//! Every rule returns rather than short-circuits, so `update-manifest check` can report everything
//! wrong with a manifest in one pass instead of one error per run.
//!
//! # This is not run at parse time
//!
//! Loading a manifest is deliberately permissive. Validation is an *authoring* gate
//! (`update-manifest check`) and an *install-time* gate (plan construction, scoped to the channel
//! actually being installed) -- not a precondition for reading the document.
//!
//! The reason is concrete. The manifest published at the time of writing has dangling requirements
//! in channel 0.13.3: `midenc` requires `base` and `std`, which were renamed to `core` and
//! `protocol`. Failing the parse would make every `midenup` and `miden` invocation fail for every
//! user, including those on channels that are perfectly well-formed, because one stale channel in
//! the same file is broken.
//!
//! This is the same rule applied to unrecognized component kinds: a defect that is scoped to one
//! part of a manifest must not take down the rest of it. A broken channel becomes uninstallable;
//! it does not make the tool unusable.

use std::collections::{BTreeSet, HashMap};

use super::{Channel, Component, ComponentKind, Manifest};
use crate::plan::{destination_for, validate_artifact_id};

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ValidationError {
    #[error("duplicate channel '{0}': channel names must be unique")]
    DuplicateChannel(semver::Version),
    #[error("channel {channel}: duplicate component '{component}'")]
    DuplicateComponent {
        channel: semver::Version,
        component: String,
    },
    #[error(
        "channel {channel}: component '{component}' requires '{requires}', which is not in the \
         channel"
    )]
    UnknownRequirement {
        channel: semver::Version,
        component: String,
        requires: String,
    },
    #[error("channel {channel}: components form a requirement cycle: {}", path.join(" -> "))]
    RequirementCycle {
        channel: semver::Version,
        path: Vec<String>,
    },
    #[error("manifest timestamp must be a positive UTC epoch, got {0}")]
    InvalidTimestamp(i64),
    #[error("channel {channel}: component '{component}' has an invalid {field}: {reason}")]
    InvalidName {
        channel: semver::Version,
        component: String,
        field: &'static str,
        reason: String,
    },
    #[error("channel {channel}: components '{first}' and '{second}' both install to '{path}'")]
    DestinationCollision {
        channel: semver::Version,
        first: String,
        second: String,
        path: String,
    },
    #[error("channel {channel}: alias '{alias}' is defined by both '{first}' and '{second}'")]
    ConflictingAlias {
        channel: semver::Version,
        alias: String,
        first: String,
        second: String,
    },
    #[error(
        "channel {channel}: alias '{alias}' on component '{component}' collides with the command \
         name of component '{collides_with}'"
    )]
    AliasShadowsCommand {
        channel: semver::Version,
        alias: String,
        component: String,
        collides_with: String,
    },
    #[error(
        "channel {channel}: component '{component}' is hidden but defines no aliases, so it can \
         never be invoked"
    )]
    HiddenWithoutAliases {
        channel: semver::Version,
        component: String,
    },
    #[error(
        "channel {channel}: command component '{component}' defines neither a format nor any \
         aliases, so it can never be invoked"
    )]
    UnreachableCommand {
        channel: semver::Version,
        component: String,
    },
    #[error("network '{network}' names channel {version}, which is not in this manifest")]
    DanglingNetwork {
        network: String,
        version: semver::Version,
    },
    #[error("network name '{name}' is invalid: {reason}")]
    InvalidNetworkName { name: String, reason: String },
    #[error(
        "this manifest declares no '{0}' network, which is the channel midenup uses when nothing \
         else selects one"
    )]
    MissingDefaultNetwork(&'static str),
    #[error(
        "channel {channel}: artifact '{artifact}' of component '{component}' declares archive \
         format '{format}', which midenup cannot read; supported formats are {supported}"
    )]
    UnsupportedArchiveFormat {
        channel: semver::Version,
        component: String,
        artifact: String,
        format: String,
        supported: String,
    },
    #[error(
        "channel {channel}: artifact '{artifact}' of component '{component}' is fetched from a \
         '{format}' archive but does not declare one, so the archive itself would be installed as \
         '{artifact}'; add \"archive\": \"{format}\""
    )]
    UndeclaredArchive {
        channel: semver::Version,
        component: String,
        artifact: String,
        format: &'static str,
    },
}

/// Validates a whole manifest, returning every problem found.
pub fn validate_manifest(manifest: &Manifest) -> Result<(), Vec<ValidationError>> {
    let mut errors = Vec::new();

    if manifest.date <= 0 {
        errors.push(ValidationError::InvalidTimestamp(manifest.date));
    }

    let mut seen_channels = BTreeSet::new();
    for channel in manifest.channels.iter() {
        if !seen_channels.insert(channel.name.clone()) {
            errors.push(ValidationError::DuplicateChannel(channel.name.clone()));
        }
        validate_channel(channel, &mut errors);
    }

    validate_networks(manifest, &mut errors);

    if errors.is_empty() { Ok(()) } else { Err(errors) }
}

/// Rules over the `networks` map.
///
/// Deliberately no ordering invariant between networks. It is tempting to require that devnet be at
/// least testnet, and testnet at least mainnet, but a mainnet hotfix legitimately inverts it, and a
/// validator that has to be overridden during an incident is worse than no validator.
fn validate_networks(manifest: &Manifest, errors: &mut Vec<ValidationError>) {
    use crate::channel::{DEFAULT_NETWORK, canonical_network};

    if !manifest.networks.contains_key(DEFAULT_NETWORK) {
        errors.push(ValidationError::MissingDefaultNetwork(DEFAULT_NETWORK));
    }

    let known: BTreeSet<&semver::Version> = manifest.channels.iter().map(|c| &c.name).collect();

    for (name, version) in manifest.networks.iter() {
        let invalid =
            |reason: String| ValidationError::InvalidNetworkName { name: name.clone(), reason };

        if name.is_empty() {
            errors.push(invalid("a network must have a name".to_string()));
        } else if let Err(err) = validate_artifact_id(name) {
            // A network name is joined straight onto `toolchains/` and written with
            // `replace_symlink`, which renames over whatever is at that path. `../../../.zshrc`
            // would make an ordinary `midenup install` replace a file outside `$MIDENUP_HOME`.
            // Same rule as every other name that becomes a path segment, deliberately.
            errors.push(invalid(err.to_string()));
        } else if semver::Version::parse(name).is_ok() {
            errors.push(invalid(
                "a network may not be named like a channel, which would make 'midenup install \
                 <name>' ambiguous"
                    .to_string(),
            ));
        } else if canonical_network(name) != name {
            errors.push(invalid(format!(
                "'{name}' is rewritten to '{}' before any lookup, so a network declared under it \
                 could never be reached",
                canonical_network(name)
            )));
        }

        if !known.contains(version) {
            errors.push(ValidationError::DanglingNetwork {
                network: name.clone(),
                version: version.clone(),
            });
        }
    }
}

fn validate_channel(channel: &Channel, errors: &mut Vec<ValidationError>) {
    let mut seen: HashMap<&str, ()> = HashMap::new();
    for component in channel.components.iter() {
        if seen.insert(component.name.as_ref(), ()).is_some() {
            errors.push(ValidationError::DuplicateComponent {
                channel: channel.name.clone(),
                component: component.name.to_string(),
            });
        }
    }

    validate_requirements(channel, errors);
    validate_names(channel, errors);
    validate_destinations(channel, errors);
    validate_aliases(channel, errors);
}

fn validate_requirements(channel: &Channel, errors: &mut Vec<ValidationError>) {
    let known: BTreeSet<&str> = channel.components.iter().map(|c| c.name.as_ref()).collect();
    for component in channel.components.iter() {
        for requires in component.requires.iter() {
            if !known.contains(requires.as_str()) {
                errors.push(ValidationError::UnknownRequirement {
                    channel: channel.name.clone(),
                    component: component.name.to_string(),
                    requires: requires.clone(),
                });
            }
        }
    }

    // Only look for cycles once every edge is known to resolve; otherwise the graph is incomplete
    // and any cycle it reports is an artefact of the missing nodes.
    if errors.iter().any(|e| matches!(e, ValidationError::UnknownRequirement { .. })) {
        return;
    }

    let index: HashMap<&str, usize> = channel
        .components
        .iter()
        .enumerate()
        .map(|(i, c)| (c.name.as_ref(), i))
        .collect();
    let mut graph = petgraph::graphmap::DiGraphMap::<usize, ()>::new();
    for (i, component) in channel.components.iter().enumerate() {
        graph.add_node(i);
        for requires in component.requires.iter() {
            if let Some(&j) = index.get(requires.as_str()) {
                graph.add_edge(j, i, ());
            }
        }
    }

    for scc in petgraph::algo::tarjan_scc(&graph) {
        let is_cycle =
            scc.len() > 1 || scc.first().is_some_and(|&n| graph.neighbors(n).any(|m| m == n));
        if is_cycle {
            let mut path: Vec<String> =
                scc.iter().map(|&i| channel.components[i].name.to_string()).collect();
            path.sort();
            errors.push(ValidationError::RequirementCycle { channel: channel.name.clone(), path });
        }
    }
}

fn validate_names(channel: &Channel, errors: &mut Vec<ValidationError>) {
    for component in channel.components.iter() {
        let invalid = |field: &'static str, reason: String| ValidationError::InvalidName {
            channel: channel.name.clone(),
            component: component.name.to_string(),
            field,
            reason,
        };

        if let ComponentKind::Executable { spec, .. } | ComponentKind::CargoExtension { spec, .. } =
            component.kind()
        {
            if let Err(err) = validate_artifact_id(&spec.installed_executable) {
                errors.push(invalid("installed-executable", err.to_string()));
            }
            if let Some(symlink) = spec.symlink_name.as_deref()
                && let Err(err) = validate_artifact_id(symlink)
            {
                errors.push(invalid("symlink-name", err.to_string()));
            }
            if spec.hide && spec.aliases.is_empty() {
                errors.push(ValidationError::HiddenWithoutAliases {
                    channel: channel.name.clone(),
                    component: component.name.to_string(),
                });
            }
        }

        // A command is reachable through any of three routes: a bare `format`, a declared
        // subcommand, or an alias. The real `node` component declares only `subcommands` -- each
        // carrying its full `docker compose ...` invocation -- so requiring `format` here would
        // reject the shipped manifest.
        if let ComponentKind::Command { format, aliases, subcommands, .. } = component.kind()
            && format.is_empty()
            && aliases.is_empty()
            && subcommands.is_empty()
        {
            errors.push(ValidationError::UnreachableCommand {
                channel: channel.name.clone(),
                component: component.name.to_string(),
            });
        }

        for (id, artifact) in component.artifacts.artifacts.iter() {
            if let Err(err) = validate_artifact_id(id) {
                errors.push(invalid("artifact id", err.to_string()));
            }

            // Stricter than parsing on purpose: an unreadable format parses, so that one channel
            // cannot break every other command (spec section 4.4), but nothing should be
            // *published* that the publishing build cannot install.
            match artifact.archive() {
                Some(archive) if !archive.format.is_supported() => {
                    errors.push(ValidationError::UnsupportedArchiveFormat {
                        channel: channel.name.clone(),
                        component: component.name.to_string(),
                        artifact: id.to_string(),
                        format: archive.format.to_string(),
                        // From the format table, so adding a format updates what this reports.
                        supported: crate::artifact::ArchiveFormat::supported_spellings()
                            .collect::<Vec<_>>()
                            .join(", "),
                    });
                },
                Some(_) => {},
                None => {
                    if let Some(format) = undeclared_archive(id, artifact, component) {
                        errors.push(ValidationError::UndeclaredArchive {
                            channel: channel.name.clone(),
                            component: component.name.to_string(),
                            artifact: id.to_string(),
                            format,
                        });
                    }
                },
            }
        }
    }
}

/// The archive format an artifact is evidently fetched from while declaring none.
///
/// This is the one artifact mistake nothing downstream can catch: the container arrives as a
/// regular file of the planned mode, so it installs, verifies and records as a success, and only
/// fails when something tries to run it. Judged on the *resolved* URI, so a `%extension` of
/// `tar.gz` is seen the same as a literal one, and on the path it is fetched from, so a query
/// string or a fragment cannot carry the extension out of sight.
///
/// An artifact id carrying the same extension is left alone: `bundle.tar.gz` installed as
/// `bundle.tar.gz` is asking for the archive itself, which is a legitimate thing to want.
fn undeclared_archive(
    id: &str,
    artifact: &crate::artifact::Artifact,
    component: &Component,
) -> Option<&'static str> {
    // Best effort: an artifact whose URI cannot be resolved at all has its own errors, and platform
    // -specific resolution is not this validator's business.
    let uris = artifact.get_uris_for(id, component).ok()?;

    crate::artifact::ArchiveFormat::supported_spellings().find(|spelling| {
        let suffix = format!(".{spelling}");
        !id.ends_with(&suffix) && uris.iter().any(|uri| uri.path().ends_with(&suffix))
    })
}

fn validate_destinations(channel: &Channel, errors: &mut Vec<ValidationError>) {
    // A notional root: collisions are a property of the manifest, not of where it is installed.
    let root = std::path::Path::new("/");
    let mut claimed: HashMap<std::path::PathBuf, &Component> = HashMap::new();

    for component in channel.components.iter() {
        for id in component.artifacts.artifacts.keys() {
            let Ok(destination) = destination_for(component, id, root) else {
                // Unsupported kinds and invalid ids are reported by their own rules.
                continue;
            };
            if let Some(previous) = claimed.insert(destination.path.clone(), component)
                && previous.name != component.name
            {
                errors.push(ValidationError::DestinationCollision {
                    channel: channel.name.clone(),
                    first: previous.name.to_string(),
                    second: component.name.to_string(),
                    path: destination.path.display().to_string(),
                });
            }
        }
    }
}

fn validate_aliases(channel: &Channel, errors: &mut Vec<ValidationError>) {
    // Direct command names first: `miden <name>` for anything callable.
    let mut command_names: HashMap<String, &str> = HashMap::new();
    for component in channel.components.iter() {
        if let Some(display) = component.get_cli_display() {
            let name = display.trim_start_matches("miden ").to_string();
            command_names.insert(name, component.name.as_ref());
        }
    }

    let mut aliases: HashMap<String, &str> = HashMap::new();
    for component in channel.components.iter() {
        let declared: Vec<&String> = match component.kind() {
            ComponentKind::Executable { spec, .. } | ComponentKind::CargoExtension { spec, .. } => {
                spec.aliases.keys().collect()
            },
            ComponentKind::Command { aliases, .. } => aliases.keys().collect(),
            _ => vec![],
        };

        for alias in declared {
            if let Some(&owner) = command_names.get(alias)
                && owner != component.name.as_ref()
            {
                errors.push(ValidationError::AliasShadowsCommand {
                    channel: channel.name.clone(),
                    alias: alias.clone(),
                    component: component.name.to_string(),
                    collides_with: owner.to_string(),
                });
            }
            if let Some(previous) = aliases.insert(alias.clone(), component.name.as_ref())
                && previous != component.name.as_ref()
            {
                errors.push(ValidationError::ConflictingAlias {
                    channel: channel.name.clone(),
                    alias: alias.clone(),
                    first: previous.to_string(),
                    second: component.name.to_string(),
                });
            }
        }
    }
}

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

    use super::*;
    use crate::{
        artifact::{Artifact, Artifacts},
        exec::Executable,
        manifest::{ExecutableComponent, InstallationMethod},
        profile::Profile,
        version::Authority,
    };

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

    fn executable(name: &'static str, installed: &str) -> Component {
        component(
            name,
            ComponentKind::Executable {
                installation_method: InstallationMethod::Prebuilt,
                spec: ExecutableComponent {
                    installed_executable: installed.to_string(),
                    ..Default::default()
                },
            },
        )
    }

    fn with_artifact(mut component: Component, id: &str) -> Component {
        component.artifacts.insert(
            id.to_string(),
            Artifact::TargetAgnostic {
                uri: "https://example.invalid/x".to_string(),
                digest: None,
                archive: None,
                extra: Default::default(),
            },
        );
        component
    }

    fn manifest(components: Vec<Component>) -> Manifest {
        let mut m = Manifest::default();
        m.channels.push(Channel::new(semver::Version::new(0, 15, 0), components));
        m
    }

    fn errors_of(m: &Manifest) -> Vec<ValidationError> {
        validate_manifest(m).err().unwrap_or_default()
    }

    fn with_mainnet(mut m: Manifest) -> Manifest {
        m.promote(crate::channel::DEFAULT_NETWORK, semver::Version::new(0, 15, 0));
        m
    }

    #[test]
    fn a_valid_manifest_passes() {
        let m =
            with_mainnet(manifest(vec![with_artifact(executable("vm", "miden-vm"), "miden-vm")]));
        assert_eq!(validate_manifest(&m), Ok(()));
    }

    #[test]
    fn a_network_naming_an_absent_channel_is_rejected() {
        let mut m = with_mainnet(manifest(vec![]));
        m.promote("testnet", semver::Version::new(9, 9, 9));
        assert!(errors_of(&m).iter().any(|e| matches!(
            e,
            ValidationError::DanglingNetwork { network, version }
                if network == "testnet" && *version == semver::Version::new(9, 9, 9)
        )));
    }

    /// `midenup install 0.15.0` must be unambiguous, so a network may not be named like a channel.
    #[test]
    fn a_network_named_like_a_version_is_rejected() {
        let mut m = with_mainnet(manifest(vec![]));
        m.promote("0.15.0", semver::Version::new(0, 15, 0));
        assert!(errors_of(&m).iter().any(
            |e| matches!(e, ValidationError::InvalidNetworkName { name, .. } if name == "0.15.0")
        ));
    }

    /// `stable` is rewritten to `mainnet` before any lookup happens, so a network declared under
    /// that name could never be reached. The same holds for every traditional synonym.
    #[test]
    fn a_network_named_after_a_synonym_is_rejected() {
        for synonym in ["stable", "beta", "nightly"] {
            let mut m = with_mainnet(manifest(vec![]));
            m.promote(synonym, semver::Version::new(0, 15, 0));
            assert!(
                errors_of(&m).iter().any(
                    |e| matches!(e, ValidationError::InvalidNetworkName { name, .. } if name == synonym)
                ),
                "'{synonym}' must be rejected as a network name"
            );
        }
    }

    #[test]
    fn an_empty_network_name_is_rejected() {
        let src = serde_json::json!({
            "manifest_version": "3.0.0",
            "date": 1735689600,
            "networks": {"": "0.15.0", "mainnet": "0.15.0"},
            "channels": [{"name": "0.15.0", "components": []}]
        })
        .to_string();
        let manifest = crate::manifest::VersionedManifest::parse_str(&src).expect("must parse");
        assert!(errors_of(&manifest).iter().any(
            |e| matches!(e, ValidationError::InvalidNetworkName { name, .. } if name.is_empty())
        ));
    }

    /// A network name becomes a path segment under `toolchains/`, so one that escapes it would let
    /// a manifest make an ordinary `midenup install` replace a file anywhere on the machine.
    #[test]
    fn a_network_name_that_is_not_a_single_path_segment_is_rejected() {
        for name in ["../../../.zshrc", "..", "sub/net"] {
            let src = serde_json::json!({
                "manifest_version": "3.0.0",
                "date": 1735689600,
                "networks": {name: "0.15.0", "mainnet": "0.15.0"},
                "channels": [{"name": "0.15.0", "components": []}]
            })
            .to_string();
            let manifest = crate::manifest::VersionedManifest::parse_str(&src).expect("must parse");
            assert!(
                errors_of(&manifest).iter().any(|e| matches!(
                    e,
                    ValidationError::InvalidNetworkName { name: reported, .. } if reported == name
                )),
                "'{name}' must be rejected as a network name"
            );
        }
    }

    /// Deliberately valid: a mainnet hotfix puts mainnet ahead of testnet. There is no ordering
    /// invariant between networks, and this test exists so that adding one fails.
    #[test]
    fn mainnet_ahead_of_testnet_is_valid() {
        let mut m = manifest(vec![with_artifact(executable("vm", "miden-vm"), "miden-vm")]);
        m.channels.push(Channel::new(semver::Version::new(0, 16, 0), vec![]));
        m.promote(crate::channel::DEFAULT_NETWORK, semver::Version::new(0, 16, 0));
        m.promote("testnet", semver::Version::new(0, 15, 0));
        assert_eq!(validate_manifest(&m), Ok(()));
    }

    #[test]
    fn a_manifest_without_mainnet_is_rejected() {
        assert!(
            errors_of(&manifest(vec![]))
                .iter()
                .any(|e| matches!(e, ValidationError::MissingDefaultNetwork(_)))
        );
    }

    #[test]
    fn several_networks_naming_one_channel_are_valid() {
        let mut m =
            with_mainnet(manifest(vec![with_artifact(executable("vm", "miden-vm"), "miden-vm")]));
        m.promote("testnet", semver::Version::new(0, 15, 0));
        m.promote("devnet", semver::Version::new(0, 15, 0));
        assert_eq!(validate_manifest(&m), Ok(()));
    }

    #[test]
    fn duplicate_channels_are_rejected() {
        let mut m = manifest(vec![]);
        m.channels.push(Channel::new(semver::Version::new(0, 15, 0), vec![]));
        assert!(errors_of(&m).iter().any(|e| matches!(e, ValidationError::DuplicateChannel(_))));
    }

    #[test]
    fn duplicate_components_are_rejected() {
        let m = manifest(vec![executable("vm", "miden-vm"), executable("vm", "other")]);
        assert!(
            errors_of(&m)
                .iter()
                .any(|e| matches!(e, ValidationError::DuplicateComponent { .. }))
        );
    }

    #[test]
    fn a_dangling_requirement_is_rejected() {
        let mut vm = executable("vm", "miden-vm");
        vm.requires = vec!["ghost".to_string()];
        assert!(
            errors_of(&manifest(vec![vm]))
                .iter()
                .any(|e| matches!(e, ValidationError::UnknownRequirement { .. }))
        );
    }

    #[test]
    fn a_requirement_cycle_is_rejected_with_its_members() {
        let mut a = component("a", ComponentKind::Package);
        let mut b = component("b", ComponentKind::Package);
        a.requires = vec!["b".to_string()];
        b.requires = vec!["a".to_string()];

        let found = errors_of(&manifest(vec![a, b]));
        let cycle = found.iter().find_map(|e| match e {
            ValidationError::RequirementCycle { path, .. } => Some(path.clone()),
            _ => None,
        });
        assert_eq!(cycle, Some(vec!["a".to_string(), "b".to_string()]));
    }

    /// A dangling requirement makes the graph incomplete, so any cycle it "finds" is noise.
    /// Report the real problem and stop.
    #[test]
    fn a_dangling_requirement_suppresses_cycle_noise() {
        let mut a = component("a", ComponentKind::Package);
        a.requires = vec!["ghost".to_string()];
        let found = errors_of(&manifest(vec![a]));
        assert!(!found.iter().any(|e| matches!(e, ValidationError::RequirementCycle { .. })));
    }

    #[test]
    fn a_non_positive_timestamp_is_rejected() {
        let mut m = manifest(vec![]);
        m.date = 0;
        assert!(errors_of(&m).iter().any(|e| matches!(e, ValidationError::InvalidTimestamp(0))));
    }

    #[test]
    fn an_unsafe_installed_executable_is_rejected() {
        let m = manifest(vec![executable("vm", "../../bin/sh")]);
        assert!(errors_of(&m).iter().any(|e| matches!(
            e,
            ValidationError::InvalidName { field: "installed-executable", .. }
        )));
    }

    #[test]
    fn an_unsafe_artifact_id_is_rejected() {
        let m = manifest(vec![with_artifact(component("core", ComponentKind::Package), "../evil")]);
        assert!(
            errors_of(&m)
                .iter()
                .any(|e| matches!(e, ValidationError::InvalidName { field: "artifact id", .. }))
        );
    }

    /// Parsing accepts an unreadable container so an unrelated channel stays usable; publishing one
    /// is a different matter.
    #[test]
    fn an_unreadable_archive_format_is_rejected_for_publication() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/core.zip",
                "archive": "zip"
            }))
            .expect("an unknown format must still parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors
                .iter()
                .any(|e| matches!(e, ValidationError::UnsupportedArchiveFormat { .. })),
            "{errors:?}"
        );
    }

    #[test]
    fn a_readable_archive_declaration_validates() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/core.tar.gz",
                "archive": "tar.gz"
            }))
            .expect("must parse"),
        );

        assert!(validate_manifest(&with_mainnet(manifest(vec![c]))).is_ok());
    }

    /// The mistake nothing downstream can catch: without the declaration the container installs as
    /// the artifact, and only fails when something runs it.
    #[test]
    fn an_archive_uri_without_an_archive_declaration_is_rejected() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/core.masp.tar.gz"
            }))
            .expect("must parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors
                .iter()
                .any(|e| matches!(e, ValidationError::UndeclaredArchive { format: "tar.gz", .. })),
            "{errors:?}"
        );
    }

    /// Judged on the resolved URI, so a per-target `%extension` is seen like a literal suffix.
    #[test]
    fn a_substituted_archive_extension_is_also_caught() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/%basename-%target.%extension",
                "extension": "tar.gz",
                "targets": {"aarch64-apple-darwin": {}}
            }))
            .expect("must parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors.iter().any(|e| matches!(e, ValidationError::UndeclaredArchive { .. })),
            "{errors:?}"
        );
    }

    /// The extension is part of what is fetched; a query string is not, and cannot be relied on
    /// to hide it. Fetching this installs a tarball named `core.masp`.
    #[test]
    fn a_query_string_does_not_hide_the_archive_extension() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/core.masp.tar.gz?download=1"
            }))
            .expect("must parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors
                .iter()
                .any(|e| matches!(e, ValidationError::UndeclaredArchive { format: "tar.gz", .. })),
            "{errors:?}"
        );
    }

    /// As for a query string: a fragment is not part of what is fetched either.
    #[test]
    fn a_fragment_does_not_hide_the_archive_extension() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/core.masp.tar.gz#sha256"
            }))
            .expect("must parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors.iter().any(|e| matches!(e, ValidationError::UndeclaredArchive { .. })),
            "{errors:?}"
        );
    }

    /// A local source is a filesystem path all the way through, `?` included.
    #[test]
    fn a_local_archive_without_a_declaration_is_rejected() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "file:///releases/core.masp.tar.gz"
            }))
            .expect("must parse"),
        );

        let errors = errors_of(&manifest(vec![c]));
        assert!(
            errors.iter().any(|e| matches!(e, ValidationError::UndeclaredArchive { .. })),
            "{errors:?}"
        );
    }

    /// Only the path names the file: a host is not a thing that is fetched.
    #[test]
    fn a_host_spelled_like_an_archive_is_left_alone() {
        let mut c = component("vm", ComponentKind::Package);
        c.artifacts.insert(
            "core.masp".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://releases.tar.gz/core.masp"
            }))
            .expect("must parse"),
        );

        assert!(validate_manifest(&with_mainnet(manifest(vec![c]))).is_ok());
    }

    /// An artifact installed *as* the archive is asking for exactly that.
    #[test]
    fn an_artifact_named_for_the_archive_is_left_alone() {
        let mut c = component("assets", ComponentKind::Asset);
        c.artifacts.insert(
            "bundle.tar.gz".to_string(),
            serde_json::from_value(serde_json::json!({
                "uri": "https://example.invalid/bundle.tar.gz"
            }))
            .expect("must parse"),
        );

        assert!(validate_manifest(&with_mainnet(manifest(vec![c]))).is_ok());
    }

    #[test]
    fn two_components_installing_to_one_path_are_rejected() {
        let m = manifest(vec![
            with_artifact(component("core", ComponentKind::Package), "shared.masp"),
            with_artifact(component("other", ComponentKind::Package), "shared.masp"),
        ]);
        assert!(
            errors_of(&m)
                .iter()
                .any(|e| matches!(e, ValidationError::DestinationCollision { .. }))
        );
    }

    #[test]
    fn a_hidden_component_without_aliases_is_rejected() {
        let hidden = component(
            "cargo-miden",
            ComponentKind::CargoExtension {
                installation_method: InstallationMethod::Prebuilt,
                spec: ExecutableComponent {
                    installed_executable: "cargo-miden".to_string(),
                    hide: true,
                    ..Default::default()
                },
            },
        );
        assert!(
            errors_of(&manifest(vec![hidden]))
                .iter()
                .any(|e| matches!(e, ValidationError::HiddenWithoutAliases { .. }))
        );
    }

    /// A command reachable only through its subcommands is valid -- this is what the real `node`
    /// component looks like.
    #[test]
    fn a_command_with_only_subcommands_is_reachable() {
        let cmd = component(
            "node",
            ComponentKind::Command {
                command_name: None,
                format: Executable::default(),
                subcommands: [("up".to_string(), Executable::default_call_format())]
                    .into_iter()
                    .collect(),
                aliases: Default::default(),
            },
        );
        assert!(
            !errors_of(&manifest(vec![cmd]))
                .iter()
                .any(|e| matches!(e, ValidationError::UnreachableCommand { .. }))
        );
    }

    #[test]
    fn a_command_with_no_format_no_subcommands_and_no_aliases_is_rejected() {
        let cmd = component(
            "node",
            ComponentKind::Command {
                command_name: None,
                format: Executable::default(),
                subcommands: Default::default(),
                aliases: Default::default(),
            },
        );
        assert!(
            errors_of(&manifest(vec![cmd]))
                .iter()
                .any(|e| matches!(e, ValidationError::UnreachableCommand { .. }))
        );
    }

    #[test]
    fn two_components_declaring_the_same_alias_are_rejected() {
        let make = |name: &'static str| {
            component(
                name,
                ComponentKind::Executable {
                    installation_method: InstallationMethod::Prebuilt,
                    spec: ExecutableComponent {
                        installed_executable: name.to_string(),
                        aliases: [("shared".to_string(), Executable::default_call_format())]
                            .into_iter()
                            .collect(),
                        ..Default::default()
                    },
                },
            )
        };
        assert!(
            errors_of(&manifest(vec![make("a"), make("b")]))
                .iter()
                .any(|e| matches!(e, ValidationError::ConflictingAlias { .. }))
        );
    }

    /// An alias must not shadow another component's direct `miden <name>` command.
    #[test]
    fn an_alias_shadowing_a_command_name_is_rejected() {
        let vm = executable("vm", "miden-vm");
        let shadower = component(
            "other",
            ComponentKind::Executable {
                installation_method: InstallationMethod::Prebuilt,
                spec: ExecutableComponent {
                    installed_executable: "other".to_string(),
                    aliases: [("vm".to_string(), Executable::default_call_format())]
                        .into_iter()
                        .collect(),
                    ..Default::default()
                },
            },
        );
        assert!(
            errors_of(&manifest(vec![vm, shadower]))
                .iter()
                .any(|e| matches!(e, ValidationError::AliasShadowsCommand { .. }))
        );
    }

    /// Loading a manifest must not run validation.
    ///
    /// Pins the decision in the module docs: the published manifest has dangling requirements in
    /// channel 0.13.3, so validating at parse time would make every command fail for every user.
    #[test]
    fn parsing_does_not_validate() {
        let src = serde_json::json!({
            "manifest_version": "3.0.0",
            "date": 1735689600,
            "channels": [{"name": "0.13.3", "components": [{
                "name": "midenc",
                "version": {"kind": "registry", "version": "0.1.0"},
                "kind": "executable",
                "installation_method": {"kind": "cargo", "crate_name": "midenc"},
                "installed-executable": "midenc",
                "requires": ["base", "std"]
            }]}]
        })
        .to_string();

        let parsed = crate::manifest::VersionedManifest::parse_str(&src)
            .expect("a channel with dangling requirements must still load");

        // ...but validation, when explicitly run, must report it.
        let errors = validate_manifest(&parsed).expect_err("validation must catch it");
        assert_eq!(
            errors
                .iter()
                .filter(|e| matches!(e, ValidationError::UnknownRequirement { .. }))
                .count(),
            2
        );
    }

    /// Every problem is reported in one pass, not one per run.
    #[test]
    fn all_errors_are_collected() {
        let mut m = manifest(vec![executable("vm", "../evil"), executable("vm", "dup")]);
        m.date = -1;
        let found = errors_of(&m);
        assert!(found.len() >= 3, "expected several errors, got {found:?}");
    }
}