murmur-artifact 0.11.0

The shared artifact model for Murmur capsules: manifest schema, .mur.zip packing and unpacking, the registry trait, refs, lockfile, and inference config.
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
//! The artifact index a source publishes beside its release assets: every version it serves of
//! every artifact, each with the payload files that make it up, their SHA-256, and the `murmur:`
//! interfaces the version's component names.
//!
//! [`index_directory`] derives an index from the `.mur.zip` files themselves; only the scope and
//! the release tag say where the files live. [`ArtifactIndex::from_json`] is the one reader, and
//! [`ArtifactIndex::to_json`] the one writer: its output is a pure function of the index value, so
//! indexing the same files twice gives the same bytes.

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::Path;

use semver::Version;
use serde::Serialize;
use serde_json::{Map, Value};
use thiserror::Error;

use crate::{
    artifact::ArtifactError, artifact_name_format_error, build_info_from_artifact_bytes,
    is_reserved_version, load_manifest_from_artifact_bytes, newest_fitting_level,
    read_component_contracts, sha256_hex, version_fit, FitSubject, RuntimeType, VersionFit,
    WitContracts, WitLevel, BUILD_INFO_FILE, LOCAL_SCOPE,
};

/// The `schema_version` [`ArtifactIndex::from_json`] reads and [`ArtifactIndex::to_json`] writes.
pub const ARTIFACT_INDEX_SCHEMA_VERSION: u64 = 2;

/// The file name a source publishes its index under, and `mur index`'s default output.
pub const ARTIFACT_INDEX_FILE_NAME: &str = "artifacts-index.json";

/// The extension every payload file carries.
pub const ARTIFACT_FILE_SUFFIX: &str = ".mur.zip";

/// The namespace of the interfaces an index records. `wasi:` imports link against any
/// semver-compatible version the host provides, so they never decide whether a version fits.
pub const MURMUR_INTERFACE_PREFIX: &str = "murmur:";

/// One source's index: [`Self::artifacts`] sorted by name, each artifact's versions newest first.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ArtifactIndex {
    pub schema_version: u64,
    /// The scope every artifact in the index is named under.
    pub scope: String,
    pub artifacts: Vec<IndexedArtifact>,
}

/// One artifact. The artifact-level fields describe its newest version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexedArtifact {
    /// The bare name, as packed in `murmur.yaml`.
    pub name: String,
    /// The packed `runtime:` role (`tool`, `hook`, `driver`, `skill`, …).
    pub runtime: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub tags: Vec<String>,
    /// Newest first by semver precedence.
    pub versions: Vec<IndexedVersion>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexedVersion {
    pub version: String,
    /// The release tag whose assets hold [`Self::assets`].
    pub release: String,
    /// The WIT level the version was built at: the label its files pack in `murmur-build.json`,
    /// else the newest level its `interfaces` fit. `mur index --merge` keeps the earlier index's
    /// value for unchanged assets.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub built_at_level: Option<u64>,
    /// Every `murmur:` interface the version's component exports or imports, sorted and
    /// deduplicated across its assets.
    pub interfaces: Vec<String>,
    /// Sorted by file name.
    pub assets: Vec<IndexedAsset>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexedAsset {
    /// `<name>-<version>.mur.zip`.
    pub file: String,
    /// [`sha256_hex`] of the file's bytes.
    pub sha256: String,
}

/// Why a JSON document is not an index this reader accepts.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ArtifactIndexError {
    #[error("is not valid JSON: {0}")]
    Malformed(String),
    #[error("is a schema 1 index")]
    Schema1,
    #[error("has schema_version {0}, and this mur reads only schema 2")]
    UnsupportedSchema(String),
    /// `at` locates the offending value, e.g. `artifacts[2].versions[0].assets`.
    #[error("is not a valid schema 2 index: {at} {reason}")]
    Invalid { at: String, reason: String },
}

/// Why [`index_directory`] or [`merge_indexes`] wrote no index.
#[derive(Debug, Error)]
pub enum IndexBuildError {
    #[error("cannot read the directory {dir}: {source}")]
    ReadDir {
        dir: String,
        #[source]
        source: io::Error,
    },
    #[error("{dir} holds no {ARTIFACT_FILE_SUFFIX} file to index")]
    NoArtifacts { dir: String },
    #[error("{file} cannot be indexed: {reason}")]
    File { file: String, reason: String },
    #[error("'{scope}' is not a usable index scope: it {reason}")]
    InvalidScope { scope: String, reason: String },
    #[error("'{release}' is not a usable release tag: it {reason}")]
    InvalidRelease {
        release: String,
        reason: &'static str,
    },
    #[error("the index being merged has scope '{previous}', and these files are indexed for scope '{scope}'")]
    ScopeMismatch { previous: String, scope: String },
}

/// What [`merge_indexes`] did with the earlier index's versions.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MergeReport {
    /// Versions only the earlier index holds, carried over verbatim.
    pub kept: usize,
    /// Versions both hold whose asset files or digests differ, written from the new files.
    pub replaced: usize,
}

impl ArtifactIndex {
    /// Read an index, checking `schema_version` before anything else, then every constraint of
    /// the schema 2 format: part-rule names and scope, unique sorted artifacts, versions that
    /// parse as semver newest first, `murmur:`-only sorted interfaces, and assets whose file
    /// names agree with their artifact and version. Keys the format does not define
    /// are ignored.
    pub fn from_json(text: &str) -> Result<Self, ArtifactIndexError> {
        let value: Value = serde_json::from_str(text)
            .map_err(|error| ArtifactIndexError::Malformed(error.to_string()))?;
        let root = value
            .as_object()
            .ok_or_else(|| invalid("the document", "is not a JSON object"))?;
        match root.get("schema_version") {
            Some(Value::Number(n)) if n.as_u64() == Some(ARTIFACT_INDEX_SCHEMA_VERSION) => {}
            Some(Value::Number(n)) if n.as_u64() == Some(1) => {
                return Err(ArtifactIndexError::Schema1)
            }
            Some(Value::String(s)) if s == "1" => return Err(ArtifactIndexError::Schema1),
            Some(other) => return Err(ArtifactIndexError::UnsupportedSchema(other.to_string())),
            None => return Err(invalid("schema_version", "is missing")),
        }
        read_index(root)
    }

    /// The index as `serde_json` pretty JSON with one trailing newline.
    #[must_use]
    pub fn to_json(&self) -> String {
        let mut text = serde_json::to_string_pretty(self)
            .unwrap_or_else(|error| unreachable!("an index always serializes: {error}"));
        text.push('\n');
        text
    }

    /// The number of versions across every artifact.
    #[must_use]
    pub fn version_count(&self) -> usize {
        self.artifacts.iter().map(|a| a.versions.len()).sum()
    }
}

impl IndexedArtifact {
    /// The newest version [`version_fit`] accepts for `level`.
    #[must_use]
    pub fn newest_fitting(&self, level: &WitLevel) -> Option<&IndexedVersion> {
        self.versions
            .iter()
            .find(|version| version_fit(&FitSubject::indexed(version), level) == VersionFit::Fits)
    }
}

/// The built-at level of an index version that packs no label: the newest of `levels` its
/// `interfaces` fit, `None` when they fit none.
#[must_use]
pub fn derived_built_at_level(interfaces: &[String], levels: &[WitLevel]) -> Option<u64> {
    let contracts = WitContracts {
        exports: Vec::new(),
        imports: interfaces.to_vec(),
    };
    newest_fitting_level(&contracts, levels)
}

/// The `murmur:` names among `contracts`' exports and imports, sorted and deduplicated.
#[must_use]
pub fn murmur_interfaces(contracts: &WitContracts) -> Vec<String> {
    contracts.matching_prefix(MURMUR_INTERFACE_PREFIX)
}

/// Why `scope` cannot head an index, if it cannot: it must pass the part rule and must not be
/// [`LOCAL_SCOPE`], which no source serves.
#[must_use]
pub fn index_scope_error(scope: &str) -> Option<String> {
    if let Some(reason) = artifact_name_format_error(scope) {
        return Some(reason);
    }
    (scope == LOCAL_SCOPE).then(|| {
        format!("is '{LOCAL_SCOPE}', which names artifacts installed from a .mur.zip file")
    })
}

/// Why `tag` cannot be recorded as a version's `release`, if it cannot.
#[must_use]
pub fn release_tag_error(tag: &str) -> Option<&'static str> {
    if tag.is_empty() {
        Some("is empty")
    } else if tag.chars().any(|c| c.is_whitespace() || c.is_control()) {
        Some("contains whitespace or a control character")
    } else {
        None
    }
}

/// The file name of one payload, as a release asset and in a store's version directory:
/// `<name>-<version>.mur.zip`, `name` the bare part.
#[must_use]
pub fn asset_file_name(name: &str, version: &str) -> String {
    format!("{}{ARTIFACT_FILE_SUFFIX}", payload_stem(name, version))
}

/// The file name of the sha256 a store keeps beside the payload [`asset_file_name`] names:
/// `<name>-<version>.sha256`.
#[must_use]
pub fn sha256_file_name(name: &str, version: &str) -> String {
    format!("{}.sha256", payload_stem(name, version))
}

/// The suffix a release asset's attestation adds to the asset's file name, and that a store's
/// attestation sidecar adds to the payload stem: `<file>.sigstore.json`.
pub const ATTESTATION_FILE_SUFFIX: &str = ".sigstore.json";

/// The file name of the attestation a store keeps beside the payload [`asset_file_name`] names:
/// `<name>-<version>.sigstore.json`, the Sigstore bundle the payload was installed with.
#[must_use]
pub fn attestation_file_name(name: &str, version: &str) -> String {
    format!("{}{ATTESTATION_FILE_SUFFIX}", payload_stem(name, version))
}

/// The file name of the metadata sidecar a store keeps beside the payload [`asset_file_name`]
/// names: `<name>-<version>.meta.json`.
#[must_use]
pub fn metadata_file_name(name: &str, version: &str) -> String {
    format!("{}.meta.json", payload_stem(name, version))
}

/// `<name>-<version>`, the part of a payload's file name before its extension.
pub(crate) fn payload_stem(name: &str, version: &str) -> String {
    format!("{name}-{version}")
}

/// The first sentence of a manifest `description:`: its first non-empty line, trimmed, cut after
/// the first `.`, `!` or `?` that ends the line or is followed by whitespace. `None` when no line
/// has text.
#[must_use]
pub fn description_summary(description: &str) -> Option<String> {
    let line = description
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())?;
    let mut chars = line.char_indices().peekable();
    while let Some((at, c)) = chars.next() {
        if matches!(c, '.' | '!' | '?') && chars.peek().is_none_or(|(_, next)| next.is_whitespace())
        {
            return Some(line[..at + c.len_utf8()].to_string());
        }
    }
    Some(line.to_string())
}

/// The search tags for an artifact: the role tags of its `runtime`, then each `-`-separated word
/// of its bare name except `murmur`, skipping words already present.
#[must_use]
pub fn derived_tags(runtime: &str, name: &str) -> Vec<String> {
    let mut tags: Vec<String> = match runtime {
        "driver" => vec!["driver".into(), "inference".into()],
        other => vec![other.to_string()],
    };
    for word in name.split('-') {
        if word.is_empty() || word == "murmur" || tags.iter().any(|tag| tag == word) {
            continue;
        }
        tags.push(word.to_string());
    }
    tags
}

/// One `.mur.zip` file read for indexing.
struct ScannedFile {
    file: String,
    name: String,
    version: String,
    runtime: String,
    sha256: String,
    interfaces: Vec<String>,
    description: Option<String>,
    built_at_level: Option<u64>,
}

/// Index every `.mur.zip` regular file directly inside `dir`, recording `release` on every
/// version. Every other entry is ignored.
///
/// Each version is one file, `<name>-<version>.mur.zip`. Its `built_at_level` is the label the
/// file packs in `murmur-build.json`; a file that packs none gets the newest of `levels` its
/// `interfaces` fit, and none when they fit no level.
///
/// Refuses the whole directory when any one file cannot be indexed (unreadable, no packed
/// `murmur.yaml`, a malformed packed `murmur-build.json`, a name or version the registry would
/// refuse, a file name that is not `<name>-<version>.mur.zip` for its packed name and version),
/// or when `dir` holds no such file. The result depends only on the files' names and bytes and on
/// `levels`, never on directory order or file times.
pub fn index_directory(
    dir: &Path,
    scope: &str,
    release: &str,
    levels: &[WitLevel],
) -> Result<ArtifactIndex, IndexBuildError> {
    if let Some(reason) = index_scope_error(scope) {
        return Err(IndexBuildError::InvalidScope {
            scope: scope.to_string(),
            reason,
        });
    }
    if let Some(reason) = release_tag_error(release) {
        return Err(IndexBuildError::InvalidRelease {
            release: release.to_string(),
            reason,
        });
    }

    let read_dir_error = |source| IndexBuildError::ReadDir {
        dir: dir.display().to_string(),
        source,
    };
    let mut file_names = Vec::new();
    for entry in fs::read_dir(dir).map_err(read_dir_error)? {
        let entry = entry.map_err(read_dir_error)?;
        let Some(file_name) = entry.file_name().to_str().map(str::to_string) else {
            continue;
        };
        if file_name.ends_with(ARTIFACT_FILE_SUFFIX)
            && fs::metadata(entry.path()).is_ok_and(|meta| meta.is_file())
        {
            file_names.push(file_name);
        }
    }
    if file_names.is_empty() {
        return Err(IndexBuildError::NoArtifacts {
            dir: dir.display().to_string(),
        });
    }
    file_names.sort();

    // name → version → the one file of that version. A file name is `<name>-<version>.mur.zip`
    // for the name and version it packs, so no two files share a version.
    let mut grouped: BTreeMap<String, BTreeMap<String, ScannedFile>> = BTreeMap::new();
    for file_name in file_names {
        let scanned = scan_file(dir, file_name)?;
        grouped
            .entry(scanned.name.clone())
            .or_default()
            .insert(scanned.version.clone(), scanned);
    }

    let artifacts = grouped
        .into_iter()
        .map(|(name, versions)| {
            let mut versions: Vec<(String, ScannedFile)> = versions.into_iter().collect();
            versions.sort_by(|(a, _), (b, _)| compare_versions(b, a));
            let newest = &versions[0].1;
            let runtime = newest.runtime.clone();
            let description = newest.description.as_deref().and_then(description_summary);
            let tags = derived_tags(&runtime, &name);
            let versions = versions
                .into_iter()
                .map(|(version, file)| {
                    let mut interfaces = file.interfaces;
                    interfaces.sort();
                    interfaces.dedup();
                    let built_at_level = file
                        .built_at_level
                        .or_else(|| derived_built_at_level(&interfaces, levels));
                    IndexedVersion {
                        version,
                        release: release.to_string(),
                        built_at_level,
                        interfaces,
                        assets: vec![IndexedAsset {
                            file: file.file,
                            sha256: file.sha256,
                        }],
                    }
                })
                .collect();
            IndexedArtifact {
                name,
                runtime,
                description,
                tags,
                versions,
            }
        })
        .collect();

    Ok(ArtifactIndex {
        schema_version: ARTIFACT_INDEX_SCHEMA_VERSION,
        scope: scope.to_string(),
        artifacts,
    })
}

fn scan_file(dir: &Path, file: String) -> Result<ScannedFile, IndexBuildError> {
    let path = dir.join(&file).display().to_string();
    let refuse = |reason: String| IndexBuildError::File {
        file: path.clone(),
        reason,
    };

    let bytes = fs::read(dir.join(&file)).map_err(|e| refuse(format!("it cannot be read: {e}")))?;
    let manifest = load_manifest_from_artifact_bytes(&bytes).map_err(|error| {
        refuse(match error {
            ArtifactError::Zip { source, .. } => format!("it is not a zip archive ({source})"),
            ArtifactError::MissingManifest => "it holds no packed murmur.yaml".to_string(),
            ArtifactError::Manifest(error) => format!("its packed murmur.yaml is invalid: {error}"),
            other => format!("its packed murmur.yaml cannot be read: {other}"),
        })
    })?;

    let name = manifest.name.clone();
    if let Some(reason) = artifact_name_format_error(&name) {
        return Err(refuse(format!("its packed name '{name}' {reason}")));
    }
    let version = manifest.version.clone();
    if is_reserved_version(&version) {
        return Err(refuse(format!(
            "its packed version '{version}' is reserved and names no single release"
        )));
    }
    if let Err(error) = Version::parse(&version) {
        return Err(refuse(format!(
            "its packed version '{version}' is not a semantic version ({error})"
        )));
    }

    let expected = asset_file_name(&name, &version);
    if file != expected {
        return Err(refuse(format!(
            "its file name does not match its packed name '{name}' and version '{version}': \
             expected {expected}"
        )));
    }

    let packaging = manifest.registry_runtime();

    // Only a wasm payload carries a component; a static one declares no interface.
    let interfaces = match packaging {
        RuntimeType::Wasm => read_component_contracts(&bytes)
            .map(|contracts| murmur_interfaces(&contracts))
            .map_err(|error| {
                refuse(format!(
                    "its wasm payload cannot be read as a component: {error}"
                ))
            })?,
        RuntimeType::Static => Vec::new(),
    };
    let built_at_level = build_info_from_artifact_bytes(&bytes)
        .map_err(|error| refuse(format!("its packed {BUILD_INFO_FILE} {error}")))?
        .map(|info| info.built_at_level);

    Ok(ScannedFile {
        sha256: sha256_hex(&bytes),
        file,
        name,
        version,
        runtime: manifest.runtime,
        interfaces,
        description: manifest.description,
        built_at_level,
    })
}

/// Merge `fresh`, indexed from a release's files, over `previous`, an earlier index of the same
/// scope.
///
/// Every version `fresh` holds is taken from it. A version both hold with the same assets keeps
/// `previous`'s `built_at_level` when it has one; one whose assets differ is counted as replaced.
/// Every other version is kept verbatim, except that one with no `built_at_level` gets the newest
/// of `levels` its `interfaces` fit. An artifact's own fields come from whichever index holds its
/// newest version, `fresh` on a tie.
pub fn merge_indexes(
    fresh: ArtifactIndex,
    previous: ArtifactIndex,
    levels: &[WitLevel],
) -> Result<(ArtifactIndex, MergeReport), IndexBuildError> {
    if fresh.scope != previous.scope {
        return Err(IndexBuildError::ScopeMismatch {
            previous: previous.scope,
            scope: fresh.scope,
        });
    }

    let mut report = MergeReport::default();
    let mut merged: BTreeMap<String, IndexedArtifact> = BTreeMap::new();
    let mut earlier: BTreeMap<String, IndexedArtifact> = previous
        .artifacts
        .into_iter()
        .map(|artifact| (artifact.name.clone(), artifact))
        .collect();

    for mut artifact in fresh.artifacts {
        let Some(old) = earlier.remove(&artifact.name) else {
            merged.insert(artifact.name.clone(), artifact);
            continue;
        };
        let old_is_newer =
            compare_versions(&old.versions[0].version, &artifact.versions[0].version)
                == Ordering::Greater;
        for old_version in old.versions.iter() {
            match artifact
                .versions
                .iter_mut()
                .find(|version| version.version == old_version.version)
            {
                Some(version) if version.assets == old_version.assets => {
                    if old_version.built_at_level.is_some() {
                        version.built_at_level = old_version.built_at_level;
                    }
                }
                Some(_) => report.replaced += 1,
                None => {
                    report.kept += 1;
                    artifact
                        .versions
                        .push(kept_version(old_version.clone(), levels));
                }
            }
        }
        artifact
            .versions
            .sort_by(|a, b| compare_versions(&b.version, &a.version));
        if old_is_newer {
            artifact.runtime = old.runtime;
            artifact.description = old.description;
            artifact.tags = old.tags;
        }
        merged.insert(artifact.name.clone(), artifact);
    }
    for (name, mut artifact) in earlier {
        report.kept += artifact.versions.len();
        artifact.versions = artifact
            .versions
            .into_iter()
            .map(|version| kept_version(version, levels))
            .collect();
        merged.insert(name, artifact);
    }

    Ok((
        ArtifactIndex {
            schema_version: ARTIFACT_INDEX_SCHEMA_VERSION,
            scope: fresh.scope,
            artifacts: merged.into_values().collect(),
        },
        report,
    ))
}

/// A version carried over from an earlier index, given the derived built-at level when it records
/// none.
fn kept_version(mut version: IndexedVersion, levels: &[WitLevel]) -> IndexedVersion {
    if version.built_at_level.is_none() {
        version.built_at_level = derived_built_at_level(&version.interfaces, levels);
    }
    version
}

/// Semver precedence, then build metadata, so two distinct versions never compare equal. A
/// string that is not semver sorts below every one that is, and two such strings compare as
/// text: a store files any version string that is not reserved.
#[must_use]
pub fn compare_versions(a: &str, b: &str) -> Ordering {
    Version::parse(a)
        .ok()
        .cmp(&Version::parse(b).ok())
        .then_with(|| a.cmp(b))
}

// ── Reading ───────────────────────────────────────────────────────────────────

fn invalid(at: impl Into<String>, reason: impl Into<String>) -> ArtifactIndexError {
    ArtifactIndexError::Invalid {
        at: at.into(),
        reason: reason.into(),
    }
}

fn child(at: &str, key: &str) -> String {
    if at.is_empty() {
        key.to_string()
    } else {
        format!("{at}.{key}")
    }
}

fn object<'a>(value: &'a Value, at: &str) -> Result<&'a Map<String, Value>, ArtifactIndexError> {
    value
        .as_object()
        .ok_or_else(|| invalid(at, "is not a JSON object"))
}

fn required<'a>(
    obj: &'a Map<String, Value>,
    at: &str,
    key: &str,
) -> Result<&'a Value, ArtifactIndexError> {
    obj.get(key)
        .ok_or_else(|| invalid(child(at, key), "is missing"))
}

fn string(value: &Value, at: &str) -> Result<String, ArtifactIndexError> {
    value
        .as_str()
        .map(str::to_string)
        .ok_or_else(|| invalid(at, "is not a string"))
}

fn required_string(
    obj: &Map<String, Value>,
    at: &str,
    key: &str,
) -> Result<String, ArtifactIndexError> {
    string(required(obj, at, key)?, &child(at, key))
}

fn optional_string(
    obj: &Map<String, Value>,
    at: &str,
    key: &str,
) -> Result<Option<String>, ArtifactIndexError> {
    obj.get(key)
        .map(|value| string(value, &child(at, key)))
        .transpose()
}

fn required_array<'a>(
    obj: &'a Map<String, Value>,
    at: &str,
    key: &str,
) -> Result<&'a Vec<Value>, ArtifactIndexError> {
    required(obj, at, key)?
        .as_array()
        .ok_or_else(|| invalid(child(at, key), "is not an array"))
}

fn string_array(
    obj: &Map<String, Value>,
    at: &str,
    key: &str,
) -> Result<Vec<String>, ArtifactIndexError> {
    let at = child(at, key);
    let items = obj
        .get(key)
        .ok_or_else(|| invalid(&at, "is missing"))?
        .as_array()
        .ok_or_else(|| invalid(&at, "is not an array"))?;
    items
        .iter()
        .enumerate()
        .map(|(i, item)| string(item, &format!("{at}[{i}]")))
        .collect()
}

fn read_index(root: &Map<String, Value>) -> Result<ArtifactIndex, ArtifactIndexError> {
    let scope = required_string(root, "", "scope")?;
    if let Some(reason) = index_scope_error(&scope) {
        return Err(invalid("scope", format!("'{scope}' {reason}")));
    }
    let mut artifacts: Vec<IndexedArtifact> = Vec::new();
    for (i, value) in required_array(root, "", "artifacts")?.iter().enumerate() {
        let at = format!("artifacts[{i}]");
        let artifact = read_artifact(value, &at)?;
        if let Some(prev) = artifacts.last() {
            if prev.name.as_bytes() >= artifact.name.as_bytes() {
                return Err(invalid(
                    child(&at, "name"),
                    format!(
                        "'{}' does not sort after '{}'; artifacts are sorted by name and names are \
                         unique",
                        artifact.name, prev.name
                    ),
                ));
            }
        }
        artifacts.push(artifact);
    }
    Ok(ArtifactIndex {
        schema_version: ARTIFACT_INDEX_SCHEMA_VERSION,
        scope,
        artifacts,
    })
}

fn read_artifact(value: &Value, at: &str) -> Result<IndexedArtifact, ArtifactIndexError> {
    let obj = object(value, at)?;
    let name = required_string(obj, at, "name")?;
    if let Some(reason) = artifact_name_format_error(&name) {
        return Err(invalid(child(at, "name"), format!("'{name}' {reason}")));
    }
    let runtime = required_string(obj, at, "runtime")?;
    if runtime.is_empty() {
        return Err(invalid(child(at, "runtime"), "is empty"));
    }
    let description = optional_string(obj, at, "description")?;
    if description.as_deref() == Some("") {
        return Err(invalid(child(at, "description"), "is empty"));
    }
    let tags = string_array(obj, at, "tags")?;
    for (i, tag) in tags.iter().enumerate() {
        if tags[..i].contains(tag) {
            return Err(invalid(
                format!("{at}.tags[{i}]"),
                format!("repeats '{tag}'"),
            ));
        }
    }

    let values = required_array(obj, at, "versions")?;
    if values.is_empty() {
        return Err(invalid(child(at, "versions"), "is empty"));
    }
    let mut versions: Vec<IndexedVersion> = Vec::new();
    for (j, value) in values.iter().enumerate() {
        let at = format!("{at}.versions[{j}]");
        let version = read_version(value, &at, &name)?;
        if let Some(prev) = versions.last() {
            if compare_versions(&prev.version, &version.version) != Ordering::Greater {
                return Err(invalid(
                    child(&at, "version"),
                    format!(
                        "'{}' is not older than '{}'; versions are unique and newest first",
                        version.version, prev.version
                    ),
                ));
            }
        }
        versions.push(version);
    }

    Ok(IndexedArtifact {
        name,
        runtime,
        description,
        tags,
        versions,
    })
}

fn read_version(value: &Value, at: &str, name: &str) -> Result<IndexedVersion, ArtifactIndexError> {
    let obj = object(value, at)?;
    let version = required_string(obj, at, "version")?;
    if is_reserved_version(&version) {
        return Err(invalid(
            child(at, "version"),
            format!("'{version}' is reserved"),
        ));
    }
    if let Err(error) = Version::parse(&version) {
        return Err(invalid(
            child(at, "version"),
            format!("'{version}' is not a semantic version ({error})"),
        ));
    }
    let release = required_string(obj, at, "release")?;
    if let Some(reason) = release_tag_error(&release) {
        return Err(invalid(child(at, "release"), reason));
    }
    let built_at_level = match obj.get("built_at_level") {
        None => None,
        Some(value) => Some(value.as_u64().ok_or_else(|| {
            invalid(child(at, "built_at_level"), "is not a non-negative integer")
        })?),
    };

    let interfaces = string_array(obj, at, "interfaces")?;
    for (i, interface) in interfaces.iter().enumerate() {
        let at = format!("{at}.interfaces[{i}]");
        if !interface.starts_with(MURMUR_INTERFACE_PREFIX) {
            return Err(invalid(
                at,
                format!("'{interface}' is not a {MURMUR_INTERFACE_PREFIX} interface"),
            ));
        }
        if i > 0 && interfaces[i - 1] >= *interface {
            return Err(invalid(
                at,
                format!(
                    "'{interface}' does not sort after '{}'; interfaces are sorted and unique",
                    interfaces[i - 1]
                ),
            ));
        }
    }

    let values = required_array(obj, at, "assets")?;
    if values.is_empty() {
        return Err(invalid(child(at, "assets"), "is empty"));
    }
    let mut assets: Vec<IndexedAsset> = Vec::new();
    for (k, value) in values.iter().enumerate() {
        let at = format!("{at}.assets[{k}]");
        let asset = read_asset(value, &at, name, &version)?;
        if let Some(prev) = assets.last() {
            if prev.file >= asset.file {
                return Err(invalid(
                    child(&at, "file"),
                    format!(
                        "'{}' does not sort after '{}'; assets are sorted by file and unique",
                        asset.file, prev.file
                    ),
                ));
            }
        }
        assets.push(asset);
    }

    Ok(IndexedVersion {
        version,
        release,
        built_at_level,
        interfaces,
        assets,
    })
}

fn read_asset(
    value: &Value,
    at: &str,
    name: &str,
    version: &str,
) -> Result<IndexedAsset, ArtifactIndexError> {
    let obj = object(value, at)?;
    let file = required_string(obj, at, "file")?;
    // An index an older `mur index` wrote may carry a `platform` key on a native tool's asset,
    // whose file name then ends `-<platform>.mur.zip`. Such an asset is read so an install
    // fetches it and refuses its native payload by name.
    let tagged = optional_string(obj, at, "platform")?.is_some();
    let expected = asset_file_name(name, version);
    let stem = format!("{}-", payload_stem(name, version));
    let tagged_name = tagged
        && file
            .strip_prefix(&stem)
            .is_some_and(|tail| tail.ends_with(ARTIFACT_FILE_SUFFIX));
    if file != expected && !tagged_name {
        return Err(invalid(
            child(at, "file"),
            format!("'{file}' is not '{expected}', the file name of this artifact and version"),
        ));
    }
    let sha256 = required_string(obj, at, "sha256")?;
    if sha256.len() != 64
        || !sha256
            .bytes()
            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
    {
        return Err(invalid(
            child(at, "sha256"),
            "is not 64 lowercase hexadecimal characters",
        ));
    }
    Ok(IndexedAsset { file, sha256 })
}

#[cfg(test)]
mod tests {
    use std::io::{Cursor, Write};

    use zip::{write::SimpleFileOptions, ZipWriter};

    use super::*;

    fn levels() -> Vec<WitLevel> {
        crate::parse_wit_levels("1 murmur:hook@0.9.0\n1 murmur:tool@0.1.0\n").unwrap()
    }

    fn served() -> WitLevel {
        levels().remove(0)
    }

    fn payload(manifest: &str, component: Option<&str>) -> Vec<u8> {
        labelled(manifest, component, None)
    }

    /// A payload that also packs `label` as its `murmur-build.json`.
    fn labelled(manifest: &str, component: Option<&str>, label: Option<&str>) -> Vec<u8> {
        let mut buf = Vec::new();
        {
            let mut zip = ZipWriter::new(Cursor::new(&mut buf));
            zip.start_file("murmur.yaml", SimpleFileOptions::default())
                .unwrap();
            zip.write_all(manifest.as_bytes()).unwrap();
            if let Some(wat) = component {
                zip.start_file("capsule.wasm", SimpleFileOptions::default())
                    .unwrap();
                zip.write_all(&wat::parse_str(wat).unwrap()).unwrap();
            }
            if let Some(label) = label {
                zip.start_file(BUILD_INFO_FILE, SimpleFileOptions::default())
                    .unwrap();
                zip.write_all(label.as_bytes()).unwrap();
            }
            zip.finish().unwrap();
        }
        buf
    }

    fn importing(names: &[&str]) -> String {
        let imports: String = names
            .iter()
            .map(|name| format!("(import \"{name}\" (instance))"))
            .collect();
        format!("(component {imports})")
    }

    fn sha(fill: char) -> String {
        fill.to_string().repeat(64)
    }

    fn version(version: &str, release: &str, assets: &[(&str, char)]) -> IndexedVersion {
        IndexedVersion {
            version: version.to_string(),
            release: release.to_string(),
            built_at_level: None,
            interfaces: vec![],
            assets: assets
                .iter()
                .map(|(file, fill)| IndexedAsset {
                    file: (*file).to_string(),
                    sha256: sha(*fill),
                })
                .collect(),
        }
    }

    fn artifact(name: &str, versions: Vec<IndexedVersion>) -> IndexedArtifact {
        IndexedArtifact {
            name: name.to_string(),
            runtime: "tool".to_string(),
            description: None,
            tags: derived_tags("tool", name),
            versions,
        }
    }

    fn index(artifacts: Vec<IndexedArtifact>) -> ArtifactIndex {
        ArtifactIndex {
            schema_version: ARTIFACT_INDEX_SCHEMA_VERSION,
            scope: "ana".to_string(),
            artifacts,
        }
    }

    #[test]
    fn versions_order_by_semver_then_text() {
        let mut versions = vec!["0.9.0", "dev", "0.10.0", "abc", "1.0.0-rc.1"];
        versions.sort_by(|a, b| compare_versions(b, a));
        assert_eq!(versions, ["1.0.0-rc.1", "0.10.0", "0.9.0", "dev", "abc"]);
    }

    #[test]
    fn description_summary_takes_the_first_sentence_of_the_first_line() {
        assert_eq!(
            description_summary("\n  Read, write and patch files. Also more.\nSecond line."),
            Some("Read, write and patch files.".to_string())
        );
        assert_eq!(
            description_summary("Version 1.2 ships! Next"),
            Some("Version 1.2 ships!".to_string())
        );
        assert_eq!(
            description_summary("Does it work?"),
            Some("Does it work?".to_string())
        );
        assert_eq!(
            description_summary("no terminator here"),
            Some("no terminator here".to_string())
        );
        assert_eq!(description_summary(" \n \n"), None);
    }

    #[test]
    fn derived_tags_follow_the_role_then_the_name_words() {
        assert_eq!(derived_tags("tool", "tool-editor"), ["tool", "editor"]);
        assert_eq!(
            derived_tags("driver", "murmur-driver-anthropic"),
            ["driver", "inference", "anthropic"]
        );
        assert_eq!(derived_tags("hook", "murmur-hook-x"), ["hook", "x"]);
        assert_eq!(derived_tags("skill", "skill"), ["skill"]);
        assert_eq!(derived_tags("recipe", "a-b-a"), ["recipe", "a", "b"]);
    }

    #[test]
    fn schema_1_is_named_whether_a_string_or_a_number() {
        for text in [
            r#"{"schema_version":"1","updated_at":"x","artifacts":[]}"#,
            r#"{"schema_version":1,"artifacts":[]}"#,
        ] {
            assert_eq!(
                ArtifactIndex::from_json(text),
                Err(ArtifactIndexError::Schema1)
            );
        }
        assert_eq!(
            ArtifactIndex::from_json(r#"{"schema_version":99}"#),
            Err(ArtifactIndexError::UnsupportedSchema("99".to_string()))
        );
        assert_eq!(
            ArtifactIndex::from_json(r#"{"schema_version":"2"}"#),
            Err(ArtifactIndexError::UnsupportedSchema("\"2\"".to_string()))
        );
        assert!(matches!(
            ArtifactIndex::from_json("{not json"),
            Err(ArtifactIndexError::Malformed(_))
        ));
    }

    #[test]
    fn a_written_index_reads_back_equal() {
        let mut v = version("0.1.0", "v0.1.0", &[("tool-x-0.1.0.mur.zip", 'a')]);
        v.built_at_level = Some(1);
        v.interfaces = vec!["murmur:tool/run@0.1.0".to_string()];
        let written = index(vec![artifact(
            "tool-x",
            vec![
                version("0.2.0", "v0.2.0", &[("tool-x-0.2.0.mur.zip", 'b')]),
                v,
            ],
        )]);
        let text = written.to_json();
        assert!(text.ends_with("}\n") && !text.ends_with("\n\n"));
        assert!(!text.contains("\"platform\""), "{text}");
        assert_eq!(ArtifactIndex::from_json(&text).unwrap(), written);
    }

    #[test]
    fn invalid_structure_names_the_json_location() {
        let mut value: Value = serde_json::from_str(
            &index(vec![artifact(
                "tool-x",
                vec![version("0.1.0", "v1", &[("tool-x-0.1.0.mur.zip", 'a')])],
            )])
            .to_json(),
        )
        .unwrap();
        value["artifacts"][0]["versions"][0]
            .as_object_mut()
            .unwrap()
            .remove("assets");
        let err = ArtifactIndex::from_json(&value.to_string()).unwrap_err();
        assert_eq!(
            err,
            invalid("artifacts[0].versions[0].assets", "is missing"),
            "{err}"
        );
    }

    #[test]
    fn the_reader_refuses_what_the_format_forbids() {
        let good = index(vec![artifact(
            "tool-x",
            vec![
                version("0.2.0", "v1", &[("tool-x-0.2.0.mur.zip", 'a')]),
                version("0.1.0", "v1", &[("tool-x-0.1.0.mur.zip", 'a')]),
            ],
        )]);
        type Mutation = Box<dyn Fn(&mut Value)>;
        let cases: Vec<(&str, Mutation)> = vec![
            ("scope", Box::new(|v| v["scope"] = "local".into())),
            ("scope", Box::new(|v| v["scope"] = "Ana".into())),
            (
                "artifacts[0].versions[1].version",
                Box::new(|v| {
                    let versions = v["artifacts"][0]["versions"].as_array_mut().unwrap();
                    versions.reverse();
                }),
            ),
            (
                "artifacts[0].versions[0].version",
                Box::new(|v| v["artifacts"][0]["versions"][0]["version"] = "latest".into()),
            ),
            (
                "artifacts[0].versions[0].assets[0].sha256",
                Box::new(|v| {
                    v["artifacts"][0]["versions"][0]["assets"][0]["sha256"] = "A".repeat(64).into()
                }),
            ),
            (
                "artifacts[0].versions[0].assets[0].file",
                Box::new(|v| {
                    v["artifacts"][0]["versions"][0]["assets"][0]["file"] =
                        "tool-y-0.2.0.mur.zip".into()
                }),
            ),
            (
                "artifacts[0].versions[0].interfaces[0]",
                Box::new(|v| {
                    v["artifacts"][0]["versions"][0]["interfaces"] =
                        serde_json::json!(["wasi:cli/run@0.2.0"])
                }),
            ),
            (
                "artifacts[0].versions[0].built_at_level",
                Box::new(|v| v["artifacts"][0]["versions"][0]["built_at_level"] = (-1).into()),
            ),
            (
                "artifacts[0].versions[0].release",
                Box::new(|v| v["artifacts"][0]["versions"][0]["release"] = "v 1".into()),
            ),
        ];
        for (at, mutate) in cases {
            let mut value: Value = serde_json::from_str(&good.to_json()).unwrap();
            mutate(&mut value);
            match ArtifactIndex::from_json(&value.to_string()) {
                Err(ArtifactIndexError::Invalid { at: got, .. }) => assert_eq!(got, at),
                other => panic!("expected Invalid at {at}, got {other:?}"),
            }
        }
    }

    /// An index an older `mur index` wrote carries a `platform` key on a native tool's asset,
    /// whose file name ends with that platform. It still reads, so an install can fetch that
    /// asset and refuse its payload by name; an untagged asset may not carry a tagged name.
    #[test]
    fn an_asset_carrying_a_platform_key_reads_with_its_tagged_file_name() {
        let mut value: Value = serde_json::from_str(
            &index(vec![artifact(
                "tool-x",
                vec![version("0.1.0", "v1", &[("tool-x-0.1.0.mur.zip", 'a')])],
            )])
            .to_json(),
        )
        .unwrap();
        let asset = &mut value["artifacts"][0]["versions"][0]["assets"][0];
        asset["file"] = "tool-x-0.1.0-linux-x86_64.mur.zip".into();
        let untagged = ArtifactIndex::from_json(&value.to_string()).unwrap_err();
        assert!(
            matches!(&untagged, ArtifactIndexError::Invalid { at, .. } if at.ends_with("file")),
            "{untagged:?}"
        );

        value["artifacts"][0]["versions"][0]["assets"][0]["platform"] = "linux-x86_64".into();
        let read = ArtifactIndex::from_json(&value.to_string()).unwrap();
        assert_eq!(
            read.artifacts[0].versions[0].assets[0].file,
            "tool-x-0.1.0-linux-x86_64.mur.zip"
        );
        assert!(!read.to_json().contains("\"platform\""));
    }

    #[test]
    fn unknown_keys_are_ignored() {
        let mut value: Value = serde_json::from_str(
            &index(vec![artifact(
                "tool-x",
                vec![version("0.1.0", "v1", &[("tool-x-0.1.0.mur.zip", 'a')])],
            )])
            .to_json(),
        )
        .unwrap();
        value["later"] = true.into();
        value["artifacts"][0]["versions"][0]["later"] = 1.into();
        assert!(ArtifactIndex::from_json(&value.to_string()).is_ok());
    }

    #[test]
    fn fit_checks_interfaces() {
        let mut v = version("1.0.0", "v1", &[("tool-x-1.0.0.mur.zip", 'a')]);
        assert_eq!(
            version_fit(&FitSubject::indexed(&v), &served()),
            VersionFit::Fits
        );
        v.interfaces = vec!["murmur:tool/run@9.9.9".to_string()];
        match version_fit(&FitSubject::indexed(&v), &served()) {
            VersionFit::Unserved(unserved) => {
                assert_eq!(unserved[0].served_version.as_deref(), Some("0.1.0"))
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn merge_keeps_old_versions_and_counts_replacements() {
        let mut kept = version("0.1.0", "v0.1.0", &[("tool-x-0.1.0.mur.zip", 'a')]);
        kept.built_at_level = Some(1);
        let previous = index(vec![
            artifact(
                "tool-gone",
                vec![version(
                    "1.0.0",
                    "v0.1.0",
                    &[("tool-gone-1.0.0.mur.zip", 'e')],
                )],
            ),
            artifact(
                "tool-x",
                vec![
                    version("0.2.0", "v0.2.0", &[("tool-x-0.2.0.mur.zip", 'b')]),
                    kept.clone(),
                ],
            ),
        ]);
        let fresh = index(vec![artifact(
            "tool-x",
            vec![
                version("0.3.0", "v0.3.0", &[("tool-x-0.3.0.mur.zip", 'c')]),
                version("0.2.0", "v0.3.0", &[("tool-x-0.2.0.mur.zip", 'd')]),
            ],
        )]);
        let (merged, report) = merge_indexes(fresh, previous, &levels()).unwrap();
        assert_eq!(
            report,
            MergeReport {
                kept: 2,
                replaced: 1
            }
        );
        assert_eq!(merged.artifacts[0].name, "tool-gone");
        let versions = &merged.artifacts[1].versions;
        let listed: Vec<_> = versions
            .iter()
            .map(|v| (v.version.as_str(), v.release.as_str()))
            .collect();
        assert_eq!(
            listed,
            [
                ("0.3.0", "v0.3.0"),
                ("0.2.0", "v0.3.0"),
                ("0.1.0", "v0.1.0")
            ]
        );
        assert_eq!(versions[2], kept);
        // A kept version recording no level gets the derived one.
        assert_eq!(merged.artifacts[0].versions[0].built_at_level, Some(1));
        assert!(ArtifactIndex::from_json(&merged.to_json()).is_ok());
    }

    #[test]
    fn merge_keeps_artifact_fields_from_the_index_holding_the_newest_version() {
        let mut newer = artifact(
            "tool-x",
            vec![version("2.0.0", "v2", &[("tool-x-2.0.0.mur.zip", 'a')])],
        );
        newer.description = Some("Old but newest.".to_string());
        let mut older = artifact(
            "tool-x",
            vec![version("1.0.0", "v1", &[("tool-x-1.0.0.mur.zip", 'b')])],
        );
        older.description = Some("Fresh but older.".to_string());
        let (merged, _) = merge_indexes(index(vec![older]), index(vec![newer]), &levels()).unwrap();
        assert_eq!(
            merged.artifacts[0].description.as_deref(),
            Some("Old but newest.")
        );
    }

    #[test]
    fn merge_refuses_another_scope() {
        let mut previous = index(vec![]);
        previous.scope = "bob".to_string();
        assert!(matches!(
            merge_indexes(index(vec![]), previous, &levels()),
            Err(IndexBuildError::ScopeMismatch { .. })
        ));
    }

    #[test]
    fn index_directory_derives_every_field_from_the_files() {
        let dir = tempfile::tempdir().unwrap();
        let tool = |v: &str| {
            payload(
                &format!(
                    "name: tool-echo\nversion: {v}\nruntime: tool\ndescription: |\n  Echo it back. Twice.\n"
                ),
                Some(&importing(&["murmur:tool/run@0.1.0", "wasi:cli/environment@0.2.0"])),
            )
        };
        fs::write(dir.path().join("tool-echo-0.10.0.mur.zip"), tool("0.10.0")).unwrap();
        fs::write(dir.path().join("tool-echo-0.9.0.mur.zip"), tool("0.9.0")).unwrap();
        let skill = payload("name: zz-skill\nversion: 1.0.0\nruntime: skill\n", None);
        fs::write(dir.path().join("zz-skill-1.0.0.mur.zip"), &skill).unwrap();
        fs::write(dir.path().join("notes.txt"), "x").unwrap();
        fs::create_dir(dir.path().join("sub.mur.zip")).unwrap();

        let built = index_directory(dir.path(), "ana", "v1.0.0", &levels()).unwrap();
        assert_eq!(built.artifacts.len(), 2);
        let echo = &built.artifacts[0];
        assert_eq!(echo.name, "tool-echo");
        assert_eq!(echo.description.as_deref(), Some("Echo it back."));
        assert_eq!(echo.tags, ["tool", "echo"]);
        assert_eq!(echo.versions[0].version, "0.10.0");
        assert_eq!(echo.versions[0].interfaces, ["murmur:tool/run@0.1.0"]);
        assert_eq!(echo.versions[0].built_at_level, Some(1));
        assert_eq!(
            echo.versions[0].assets[0].sha256,
            sha256_hex(&tool("0.10.0"))
        );
        let skill = &built.artifacts[1];
        assert_eq!(skill.versions.len(), 1);
        assert_eq!(skill.versions[0].assets.len(), 1);
        assert!(skill.versions[0].interfaces.is_empty());
        assert_eq!(skill.versions[0].built_at_level, Some(1));
        assert!(!built.to_json().contains("\"platform\""));
        assert_eq!(ArtifactIndex::from_json(&built.to_json()).unwrap(), built);
    }

    #[test]
    fn index_directory_refuses_a_file_that_cannot_be_indexed() {
        let cases: Vec<(&str, Vec<u8>, &str)> = vec![
            ("tool-a-0.1.0.mur.zip", Vec::new(), "not a zip archive"),
            (
                "tool-a-0.2.0.mur.zip",
                payload("name: tool-a\nversion: 0.1.0\nruntime: tool\n", None),
                "does not match",
            ),
            (
                "tool-a-banana.mur.zip",
                payload("name: tool-a\nversion: banana\nruntime: tool\n", None),
                "not a semantic version",
            ),
            (
                "tool-a-latest.mur.zip",
                payload("name: tool-a\nversion: latest\nruntime: tool\n", None),
                "reserved",
            ),
            (
                "tool-a-0.1.0.mur.zip",
                payload(
                    "name: tool-a\nversion: 0.1.0\nruntime: tool\nimplementation: native\n",
                    None,
                ),
                "artifact 'tool-a' declares implementation: native",
            ),
            (
                "tool-a-0.1.0-linux-x86_64.mur.zip",
                payload("name: tool-a\nversion: 0.1.0\nruntime: tool\n", None),
                "expected tool-a-0.1.0.mur.zip",
            ),
            (
                "tool-a-0.1.0.mur.zip",
                labelled(
                    "name: tool-a\nversion: 0.1.0\nruntime: tool\n",
                    Some("(component)"),
                    Some("{\"built_at_level\": \"one\"}"),
                ),
                "its packed murmur-build.json sets built_at_level to \"one\"",
            ),
            (
                "tool-a-0.1.0.mur.zip",
                payload("name: tool-a\nversion: 0.1.0\nruntime: tool\n", None),
                "its wasm payload cannot be read as a component: it has no root .wasm entry",
            ),
            (
                "tool-a-0.1.0.mur.zip",
                payload(
                    "name: tool-a\nversion: 0.1.0\nruntime: tool\n",
                    Some("(module)"),
                ),
                "its wasm payload cannot be read as a component: its root .wasm entry \
                 capsule.wasm is a core module, not a component",
            ),
        ];
        for (file, bytes, reason) in cases {
            let dir = tempfile::tempdir().unwrap();
            fs::write(dir.path().join(file), bytes).unwrap();
            let error = index_directory(dir.path(), "ana", "v1", &levels()).unwrap_err();
            let text = error.to_string();
            assert!(
                matches!(error, IndexBuildError::File { .. })
                    && text.contains(file)
                    && text.contains(reason),
                "{file}: {text}"
            );
        }
    }

    #[test]
    fn index_directory_refuses_an_empty_directory() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.txt"), "x").unwrap();
        assert!(matches!(
            index_directory(dir.path(), "ana", "v1", &levels()),
            Err(IndexBuildError::NoArtifacts { .. })
        ));
    }

    #[test]
    fn index_directory_writes_a_packed_label_and_derives_one_otherwise() {
        let dir = tempfile::tempdir().unwrap();
        let stale = importing(&["murmur:tool/run@0.0.9"]);
        // Packed labels are recorded as written, whatever the interfaces say.
        fs::write(
            dir.path().join("tool-a-0.2.0.mur.zip"),
            labelled(
                "name: tool-a\nversion: 0.2.0\nruntime: tool\n",
                Some(&stale),
                Some("{\"built_at_level\":1}\n"),
            ),
        )
        .unwrap();
        // No label, and interfaces fitting no level: no label at all.
        fs::write(
            dir.path().join("tool-a-0.1.0.mur.zip"),
            payload(
                "name: tool-a\nversion: 0.1.0\nruntime: tool\n",
                Some(&stale),
            ),
        )
        .unwrap();
        let built = index_directory(dir.path(), "ana", "v1", &levels()).unwrap();
        let versions = &built.artifacts[0].versions;
        assert_eq!(versions[0].built_at_level, Some(1));
        assert_eq!(versions[1].built_at_level, None);
        assert!(built.to_json().contains("\"built_at_level\": 1"));
    }
}