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
//! The versioned WIT interface names a component binary declares.
//!
//! The host resolves exactly one version of each interface and keeps no fallback (see
//! `crates/capsule-runtime/wit/VERSIONING.md`), so both directions matter: an artifact stops
//! instantiating when a package it *exports* is renamed by a version bump, and equally when a
//! package it *imports* is. The two lists here are the floor an installed artifact was built
//! against, read out of the component bytes rather than declared anywhere by hand.
//!
//! Extraction is best-effort by design. A skill, a core module, or a payload
//! that does not parse simply has nothing to record; that is not an error, and
//! [`wit_contracts_from_artifact_bytes`] is total for exactly that reason.
//! [`read_component_contracts`] is the strict reader, for a payload packaged as wasm, where a
//! missing or unreadable component is a defect of the artifact.

use std::collections::BTreeSet;
use std::fs;
use std::io::{self, Cursor, Read, Seek};
use std::path::Path;

use serde::{Deserialize, Serialize};
use thiserror::Error;
use wasmparser::{Encoding, Parser, Payload};
use zip::ZipArchive;

use crate::{
    payload_shape::{select_root_wasm_in_archive, PayloadShapeError},
    zip_guard,
};

/// The versioned WIT interface names a component declares, in both directions.
///
/// Each list is sorted ascending and deduplicated, and holds fully-qualified instance names
/// byte for byte as the component binary carries them (e.g. `murmur:tool/run@0.1.0`). Bare
/// function and type externs — names without a `/` — are not interfaces and are not recorded.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WitContracts {
    /// Interfaces the host resolves when it instantiates the artifact.
    #[serde(default)]
    pub exports: Vec<String>,
    /// Interfaces the host must provide for the artifact to link.
    #[serde(default)]
    pub imports: Vec<String>,
}

impl WitContracts {
    /// Every recorded interface name across both directions, exports first.
    pub fn all(&self) -> impl Iterator<Item = &str> {
        self.exports
            .iter()
            .chain(self.imports.iter())
            .map(String::as_str)
    }

    /// The recorded names starting with `prefix`, sorted ascending and deduplicated across
    /// the two directions.
    #[must_use]
    pub fn matching_prefix(&self, prefix: &str) -> Vec<String> {
        let mut matches: Vec<String> = self
            .all()
            .filter(|name| name.starts_with(prefix))
            .map(str::to_string)
            .collect();
        sort_dedup(&mut matches);
        matches
    }

    /// The recorded `murmur:` interfaces whose version is not the one `served` lists for their
    /// package: exports in recorded order, then imports in recorded order.
    ///
    /// `served` is a `(package, version)` table such as [`crate::WitLevel::served`]; fit against
    /// a level is [`crate::version_fit`], which calls this.
    /// Versions compare as exact strings, matching a host that resolves one instance name per
    /// interface. A name is reported when its package is absent from `served`, when it carries
    /// no `@version`, or when its version differs. Names outside the `murmur:` namespace are
    /// never reported: `wasi:*` imports link against any semver-compatible version the host
    /// provides, and other namespaces are not the host's interfaces.
    #[must_use]
    pub fn unserved_against(&self, served: &[(&str, &str)]) -> Vec<UnservedInterface> {
        let exports = self
            .exports
            .iter()
            .map(|name| (name, ContractDirection::Export));
        let imports = self
            .imports
            .iter()
            .map(|name| (name, ContractDirection::Import));
        exports
            .chain(imports)
            .filter_map(|(name, direction)| {
                let (package, rest) = name.split_once('/')?;
                if !package.starts_with("murmur:") {
                    return None;
                }
                let artifact_version = rest.rsplit_once('@').map(|(_, version)| version);
                let served_version = served
                    .iter()
                    .find(|(served_package, _)| *served_package == package)
                    .map(|(_, version)| *version);
                if artifact_version.is_some() && artifact_version == served_version {
                    return None;
                }
                Some(UnservedInterface {
                    interface: name.clone(),
                    direction,
                    package: package.to_string(),
                    artifact_version: artifact_version.map(str::to_string),
                    served_version: served_version.map(str::to_string),
                })
            })
            .collect()
    }
}

/// Which side of the component boundary a recorded interface name sits on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContractDirection {
    /// The artifact exports the interface and the host resolves it.
    Export,
    /// The artifact imports the interface and the host must provide it.
    Import,
}

/// One recorded `murmur:` interface a host serving a given table would refuse.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnservedInterface {
    /// The fully-qualified instance name as the component carries it.
    pub interface: String,
    pub direction: ContractDirection,
    /// The text before the first `/`, e.g. `murmur:hook`.
    pub package: String,
    /// The text after the last `@`; `None` when the name carries no version.
    pub artifact_version: Option<String>,
    /// The version the table serves for `package`; `None` when it serves no version of it.
    pub served_version: Option<String>,
}

/// Why component bytes could not be read for their WIT contracts.
#[derive(Debug, Error)]
pub enum WitContractError {
    /// The bytes are not a well-formed wasm binary.
    #[error("could not parse wasm payload: {0}")]
    Parse(#[from] wasmparser::BinaryReaderError),
}

/// Extract the WIT contracts declared by a wasm binary.
///
/// Returns `Ok(None)` when the bytes are a core module rather than a component: a core module
/// carries no component-model interface names, so there is nothing to record.
///
/// Only the outermost component's own import and export sections are read. `parse_all` descends
/// into nested modules and components, whose interfaces belong to the composition, not to what
/// the host resolves on this artifact.
pub fn extract_wit_contracts(
    component_bytes: &[u8],
) -> Result<Option<WitContracts>, WitContractError> {
    let mut contracts = WitContracts::default();
    let mut is_component = false;
    // 0 while inside the outermost unit; deeper once a nested module or component opens.
    let mut depth: usize = 0;

    for payload in Parser::new(0).parse_all(component_bytes) {
        match payload? {
            Payload::Version { encoding, .. } => {
                if depth == 0 {
                    is_component = encoding == Encoding::Component;
                    if !is_component {
                        return Ok(None);
                    }
                }
            }
            Payload::ModuleSection { .. } | Payload::ComponentSection { .. } => depth += 1,
            Payload::End(_) => depth = depth.saturating_sub(1),
            Payload::ComponentExportSection(reader) if depth == 0 => {
                for export in reader {
                    push_interface(&mut contracts.exports, export?.name.name);
                }
            }
            Payload::ComponentImportSection(reader) if depth == 0 => {
                for import in reader {
                    push_interface(&mut contracts.imports, import?.name.name);
                }
            }
            _ => {}
        }
    }

    if !is_component {
        return Ok(None);
    }

    sort_dedup(&mut contracts.exports);
    sort_dedup(&mut contracts.imports);
    Ok(Some(contracts))
}

/// Extract the WIT contracts of the component packed inside a `.mur.zip`.
///
/// Total: `None` for anything that cannot be read as a component — bytes that are not a zip, an
/// archive with no root wasm entry or an ambiguous pair of them, a payload over the artifact
/// decompression cap, a core module, or a binary that does not parse.
#[must_use]
pub fn wit_contracts_from_artifact_bytes(artifact_bytes: &[u8]) -> Option<WitContracts> {
    wit_contracts_from_artifact_reader(Cursor::new(artifact_bytes))
}

/// [`wit_contracts_from_artifact_bytes`] over a seekable reader, typically an open `.mur.zip`
/// file.
///
/// Only the zip central directory and the selected root wasm entry are read, so an archive with
/// no wasm entry costs one central-directory read rather than the whole payload. Total on the
/// same terms: `None` for anything that cannot be read as a component.
#[must_use]
pub fn wit_contracts_from_artifact_reader<R: Read + Seek>(reader: R) -> Option<WitContracts> {
    let mut archive = ZipArchive::new(reader).ok()?;
    let wasm = read_root_wasm_from_archive(&mut archive)?;
    extract_wit_contracts(&wasm).ok().flatten()
}

/// Why a `.mur.zip` yields no component to read WIT contracts from. Each displays as a clause
/// that names the root wasm entry when one was selected.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ComponentReadError {
    #[error("it is not a zip archive ({0})")]
    NotAZip(String),
    #[error("it has no root .wasm entry (expected capsule.wasm or one root *.wasm)")]
    NoRootWasm,
    #[error("its root .wasm entries are ambiguous: {}, and none is capsule.wasm", names.join(", "))]
    AmbiguousRootWasm { names: Vec<String> },
    #[error("its root .wasm entry {name} is over the {limit}-byte decompression cap")]
    OverDecompressionCap { name: String, limit: u64 },
    #[error("its root .wasm entry {name} cannot be read: {reason}")]
    Unreadable { name: String, reason: String },
    #[error("its root .wasm entry {name} is a core module, not a component")]
    CoreModule { name: String },
    #[error("its root .wasm entry {name} does not parse as a component: {reason}")]
    NotAComponent { name: String, reason: String },
}

/// The WIT contracts of the component packed inside a `.mur.zip`, or why there is none.
///
/// The strict counterpart of [`wit_contracts_from_artifact_bytes`], for a caller that expects a
/// component — a payload packaged as wasm — and must refuse one it cannot read rather than
/// record it as declaring nothing.
pub fn read_component_contracts(artifact_bytes: &[u8]) -> Result<WitContracts, ComponentReadError> {
    let mut archive = ZipArchive::new(Cursor::new(artifact_bytes))
        .map_err(|error| ComponentReadError::NotAZip(error.to_string()))?;
    let name = select_root_wasm_in_archive(&mut archive).map_err(|error| match error {
        PayloadShapeError::MissingRootWasm => ComponentReadError::NoRootWasm,
        PayloadShapeError::MultipleRootWasm { names } => {
            ComponentReadError::AmbiguousRootWasm { names }
        }
    })?;
    let wasm = zip_guard::read_zip_entry_capped(
        &mut archive,
        &name,
        zip_guard::max_artifact_decompressed_bytes(),
    )
    .map_err(|error| match error {
        zip_guard::ZipGuardError::DecompressionCeilingExceeded { limit, .. } => {
            ComponentReadError::OverDecompressionCap {
                name: name.clone(),
                limit,
            }
        }
        other => ComponentReadError::Unreadable {
            name: name.clone(),
            reason: other.to_string(),
        },
    })?;
    match extract_wit_contracts(&wasm) {
        Ok(Some(contracts)) => Ok(contracts),
        Ok(None) => Err(ComponentReadError::CoreModule { name }),
        // wasmparser pretty-prints some reasons across lines; the refusal is one line.
        Err(WitContractError::Parse(error)) => Err(ComponentReadError::NotAComponent {
            name,
            reason: error
                .to_string()
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" "),
        }),
    }
}

fn read_root_wasm_from_archive<R: Read + Seek>(archive: &mut ZipArchive<R>) -> Option<Vec<u8>> {
    let selected = select_root_wasm_in_archive(archive).ok()?;
    zip_guard::read_zip_entry_capped(
        archive,
        &selected,
        zip_guard::max_artifact_decompressed_bytes(),
    )
    .ok()
}

/// Every `murmur:*` package declared by a `.wit` file under `dir`, recursively, as
/// `("murmur:<name>", "<version>")` pairs.
///
/// A declaration is a line that, trimmed, reads `package murmur:<name>@<version>;`. A name that
/// is a WIT keyword is written with a leading `%` (`murmur:%stream`); the `%` is escaping and is
/// dropped. Files without the `.wit` extension are not read.
///
/// Errors with [`io::ErrorKind::InvalidData`], naming the file, on a `package murmur:` line with
/// no `@version`: every `murmur:*` package is versioned (see
/// `crates/capsule-runtime/wit/VERSIONING.md`). Any error reading `dir` or a file under it is
/// returned as is.
pub fn wit_package_declarations(dir: &Path) -> io::Result<BTreeSet<(String, String)>> {
    let mut declared = BTreeSet::new();
    collect_package_declarations(dir, &mut declared)?;
    Ok(declared)
}

fn collect_package_declarations(
    dir: &Path,
    into: &mut BTreeSet<(String, String)>,
) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            collect_package_declarations(&path, into)?;
            continue;
        }
        if path.extension().and_then(|ext| ext.to_str()) != Some("wit") {
            continue;
        }
        for line in fs::read_to_string(&path)?.lines() {
            let Some(declaration) = line
                .trim()
                .strip_prefix("package murmur:")
                .and_then(|rest| rest.strip_suffix(';'))
            else {
                continue;
            };
            let (name, version) = declaration.split_once('@').ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("unversioned package in {}: {}", path.display(), line.trim()),
                )
            })?;
            let name = name.strip_prefix('%').unwrap_or(name);
            into.insert((format!("murmur:{name}"), version.to_string()));
        }
    }
    Ok(())
}

/// Record `name` when it names an interface. Component extern names that carry no `/` are
/// bare functions or types, not interfaces, and pin no interface version.
fn push_interface(into: &mut Vec<String>, name: &str) {
    if name.contains('/') {
        into.push(name.to_string());
    }
}

fn sort_dedup(names: &mut Vec<String>) {
    names.sort();
    names.dedup();
}

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

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

    use super::*;

    fn zip_with(files: &[(&str, &[u8])]) -> Vec<u8> {
        let mut buf = Vec::new();
        {
            let mut zip = ZipWriter::new(Cursor::new(&mut buf));
            for (name, bytes) in files {
                zip.start_file(*name, SimpleFileOptions::default()).unwrap();
                zip.write_all(bytes).unwrap();
            }
            zip.finish().unwrap();
        }
        buf
    }

    fn component(wat: &str) -> Vec<u8> {
        wat::parse_str(wat).unwrap()
    }

    const EXPORTING_COMPONENT: &str = r#"
        (component
          (core module $m (func (export "run")))
          (core instance $i (instantiate $m))
          (func $run (result u32) (canon lift (core func $i "run")))
          (component $inner
            (core module $n (func (export "nested")))
            (core instance $ni (instantiate $n))
            (func $nested (canon lift (core func $ni "nested")))
            (instance $niface (export "nested" (func $nested)))
            (export "murmur:nested/inner@9.9.9" (instance $niface))
          )
          (instance $iface (export "handle" (func $run)))
          (export "murmur:hook/lifecycle@0.5.0" (instance $iface))
        )
    "#;

    /// The nested component in the fixture exports an interface of its own, which belongs to
    /// the composition rather than to what the host resolves on the artifact.
    #[test]
    fn records_the_outermost_components_exports_only() {
        let contracts = extract_wit_contracts(&component(EXPORTING_COMPONENT))
            .unwrap()
            .unwrap();
        assert_eq!(contracts.exports, vec!["murmur:hook/lifecycle@0.5.0"]);
        assert!(contracts.imports.is_empty());
    }

    #[test]
    fn records_imported_interface_names_sorted_and_deduplicated() {
        let wat = r#"
            (component
              (import "murmur:tool-registry/invoke@0.1.0" (instance))
              (import "wasi:cli/environment@0.2.0" (instance))
              (import "murmur:runtime/inference@0.4.0" (instance))
            )
        "#;
        let contracts = extract_wit_contracts(&component(wat)).unwrap().unwrap();
        assert_eq!(
            contracts.imports,
            vec![
                "murmur:runtime/inference@0.4.0",
                "murmur:tool-registry/invoke@0.1.0",
                "wasi:cli/environment@0.2.0",
            ]
        );
    }

    #[test]
    fn ignores_externs_that_do_not_name_an_interface() {
        let wat = r#"
            (component
              (import "plain-func" (func))
              (core module $m (func (export "f")))
              (core instance $i (instantiate $m))
              (func $f (canon lift (core func $i "f")))
              (export "bare-export" (func $f))
            )
        "#;
        let contracts = extract_wit_contracts(&component(wat)).unwrap().unwrap();
        assert!(contracts.exports.is_empty());
        assert!(contracts.imports.is_empty());
    }

    #[test]
    fn a_core_module_yields_none() {
        let module = component(r#"(module (func (export "f")))"#);
        assert!(extract_wit_contracts(&module).unwrap().is_none());
    }

    #[test]
    fn unparseable_bytes_are_an_error() {
        assert!(extract_wit_contracts(b"\0asm").is_err());
    }

    #[test]
    fn reads_the_component_out_of_an_artifact_zip() {
        let archive = zip_with(&[
            ("murmur.yaml", b"name: demo\n"),
            ("tool.wasm", &component(EXPORTING_COMPONENT)),
        ]);
        let contracts = wit_contracts_from_artifact_bytes(&archive).unwrap();
        assert_eq!(contracts.exports, vec!["murmur:hook/lifecycle@0.5.0"]);
    }

    #[test]
    fn capsule_wasm_wins_over_other_root_wasm_entries() {
        let archive = zip_with(&[
            ("capsule.wasm", &component(EXPORTING_COMPONENT)),
            ("other.wasm", b"\0asm"),
        ]);
        let contracts = wit_contracts_from_artifact_bytes(&archive).unwrap();
        assert_eq!(contracts.exports, vec!["murmur:hook/lifecycle@0.5.0"]);
    }

    #[test]
    fn unreadable_payloads_yield_none() {
        assert!(wit_contracts_from_artifact_bytes(b"not-a-zip-at-all").is_none());
        assert!(wit_contracts_from_artifact_bytes(&zip_with(&[("tool.wasm", b"\0asm")])).is_none());
        assert!(
            wit_contracts_from_artifact_bytes(&zip_with(&[("SKILL.md", b"# guidance")])).is_none()
        );
        assert!(
            wit_contracts_from_artifact_bytes(&zip_with(&[("bin/demo", b"\x7fELF")])).is_none()
        );
        assert!(wit_contracts_from_artifact_bytes(&zip_with(&[
            ("a.wasm", b"\0asm"),
            ("b.wasm", b"\0asm"),
        ]))
        .is_none());
        let module = component(r#"(module (func (export "f")))"#);
        assert!(wit_contracts_from_artifact_bytes(&zip_with(&[("tool.wasm", &module)])).is_none());
    }

    #[test]
    fn the_strict_reader_reads_a_packed_component() {
        let archive = zip_with(&[("capsule.wasm", &component(EXPORTING_COMPONENT))]);
        assert_eq!(
            read_component_contracts(&archive).ok(),
            wit_contracts_from_artifact_bytes(&archive)
        );
    }

    #[test]
    fn the_strict_reader_names_why_a_payload_holds_no_component() {
        assert!(matches!(
            read_component_contracts(b"not-a-zip-at-all"),
            Err(ComponentReadError::NotAZip(_))
        ));
        assert_eq!(
            read_component_contracts(&zip_with(&[("SKILL.md", b"# guidance")])),
            Err(ComponentReadError::NoRootWasm)
        );
        assert_eq!(
            read_component_contracts(&zip_with(&[("a.wasm", b"\0asm"), ("b.wasm", b"\0asm")])),
            Err(ComponentReadError::AmbiguousRootWasm {
                names: vec!["a.wasm".to_string(), "b.wasm".to_string()]
            })
        );
        let module = component("(module)");
        let error = read_component_contracts(&zip_with(&[("capsule.wasm", &module)])).unwrap_err();
        assert_eq!(
            error.to_string(),
            "its root .wasm entry capsule.wasm is a core module, not a component"
        );
        let error =
            read_component_contracts(&zip_with(&[("capsule.wasm", b"not wasm")])).unwrap_err();
        assert!(
            matches!(&error, ComponentReadError::NotAComponent { name, .. } if name == "capsule.wasm"),
            "{error:?}"
        );
        assert!(
            error
                .to_string()
                .starts_with("its root .wasm entry capsule.wasm does not parse as a component: "),
            "{error}"
        );
    }

    #[test]
    fn reader_variant_reads_the_same_contracts_as_the_bytes_variant() {
        let archive = zip_with(&[("tool.wasm", &component(EXPORTING_COMPONENT))]);
        assert_eq!(
            wit_contracts_from_artifact_reader(Cursor::new(&archive)),
            wit_contracts_from_artifact_bytes(&archive)
        );
        assert!(wit_contracts_from_artifact_reader(Cursor::new(b"not-a-zip")).is_none());
    }

    const SERVED: &[(&str, &str)] = &[
        ("murmur:hook", "0.9.0"),
        ("murmur:runtime", "0.4.0"),
        ("murmur:text", "0.1.0"),
        ("murmur:tool", "0.1.0"),
    ];

    fn contracts_of(exports: &[&str], imports: &[&str]) -> WitContracts {
        WitContracts {
            exports: exports.iter().map(|name| name.to_string()).collect(),
            imports: imports.iter().map(|name| name.to_string()).collect(),
        }
    }

    #[test]
    fn unserved_skips_a_name_at_the_served_version() {
        let contracts = contracts_of(
            &["murmur:hook/lifecycle@0.9.0"],
            &["murmur:runtime/inference@0.4.0"],
        );
        assert!(contracts.unserved_against(SERVED).is_empty());
    }

    #[test]
    fn unserved_reports_a_retired_export_and_import_with_both_versions() {
        let contracts = contracts_of(
            &["murmur:hook/lifecycle@0.8.0"],
            &["murmur:runtime/inference@0.3.0"],
        );
        assert_eq!(
            contracts.unserved_against(SERVED),
            vec![
                UnservedInterface {
                    interface: "murmur:hook/lifecycle@0.8.0".to_string(),
                    direction: ContractDirection::Export,
                    package: "murmur:hook".to_string(),
                    artifact_version: Some("0.8.0".to_string()),
                    served_version: Some("0.9.0".to_string()),
                },
                UnservedInterface {
                    interface: "murmur:runtime/inference@0.3.0".to_string(),
                    direction: ContractDirection::Import,
                    package: "murmur:runtime".to_string(),
                    artifact_version: Some("0.3.0".to_string()),
                    served_version: Some("0.4.0".to_string()),
                },
            ]
        );
    }

    #[test]
    fn unserved_reports_a_package_the_table_does_not_serve() {
        let without_text: Vec<(&str, &str)> = SERVED
            .iter()
            .copied()
            .filter(|(package, _)| *package != "murmur:text")
            .collect();
        let contracts = contracts_of(
            &["murmur:tool/run@0.1.0"],
            &["murmur:text/chunks@0.1.0", "murmur:text/stream@0.1.0"],
        );
        let unserved = contracts.unserved_against(&without_text);
        assert_eq!(unserved.len(), 2, "{unserved:?}");
        for interface in &unserved {
            assert_eq!(interface.package, "murmur:text");
            assert_eq!(interface.direction, ContractDirection::Import);
            assert_eq!(interface.artifact_version.as_deref(), Some("0.1.0"));
            assert_eq!(interface.served_version, None);
        }
    }

    #[test]
    fn unserved_reports_an_unversioned_name() {
        let contracts = contracts_of(&["murmur:tool/run"], &[]);
        let unserved = contracts.unserved_against(SERVED);
        assert_eq!(unserved.len(), 1);
        assert_eq!(unserved[0].package, "murmur:tool");
        assert_eq!(unserved[0].artifact_version, None);
        assert_eq!(unserved[0].served_version.as_deref(), Some("0.1.0"));
    }

    #[test]
    fn unserved_never_reports_other_namespaces() {
        let contracts = contracts_of(
            &["foo:bar/baz@9.9.9"],
            &["wasi:cli/environment@0.2.0", "foo:bar/baz@9.9.9"],
        );
        assert!(contracts.unserved_against(SERVED).is_empty());
    }

    #[test]
    fn matching_prefix_spans_both_directions() {
        let contracts = WitContracts {
            exports: vec!["murmur:tool/run@0.1.0".to_string()],
            imports: vec![
                "murmur:tool-registry/invoke@0.1.0".to_string(),
                "wasi:cli/environment@0.2.0".to_string(),
            ],
        };
        assert_eq!(
            contracts.matching_prefix("murmur:tool"),
            vec!["murmur:tool-registry/invoke@0.1.0", "murmur:tool/run@0.1.0",]
        );
        assert!(contracts.matching_prefix("murmur:hook").is_empty());
    }

    fn write(path: &Path, text: &str) {
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, text).unwrap();
    }

    #[test]
    fn package_declarations_are_read_recursively_with_the_keyword_escape_dropped() {
        let tree = tempfile::tempdir().unwrap();
        write(
            &tree.path().join("worlds.wit"),
            "package murmur:host@0.1.0;\n\nworld w {}\n",
        );
        write(
            &tree.path().join("deps/murmur-stream/stream.wit"),
            "  package murmur:%stream@0.1.0;\ninterface events {}\n",
        );
        write(
            &tree.path().join("deps/nested/deeper/task.wit"),
            "package murmur:task@0.2.0;\n",
        );
        write(
            &tree.path().join("deps/wasi/cli.wit"),
            "package wasi:cli@0.2.0;\n",
        );
        write(
            &tree.path().join("README.md"),
            "package murmur:ignored@9.9.9;\n",
        );

        let declared = wit_package_declarations(tree.path()).unwrap();
        let expected: BTreeSet<(String, String)> = [
            ("murmur:host", "0.1.0"),
            ("murmur:stream", "0.1.0"),
            ("murmur:task", "0.2.0"),
        ]
        .into_iter()
        .map(|(package, version)| (package.to_string(), version.to_string()))
        .collect();
        assert_eq!(declared, expected);
    }

    #[test]
    fn an_unversioned_package_declaration_is_refused_naming_the_file() {
        let tree = tempfile::tempdir().unwrap();
        let file = tree.path().join("deps/bare.wit");
        write(&file, "package murmur:bare;\n");

        let err = wit_package_declarations(tree.path()).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(
            err.to_string().contains(&file.display().to_string()),
            "{err}"
        );
    }

    #[test]
    fn a_missing_directory_is_an_error() {
        let tree = tempfile::tempdir().unwrap();
        assert!(wit_package_declarations(&tree.path().join("absent")).is_err());
    }
}