murmur-artifact 0.6.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
use std::{fs, path::Path};

use serde_yaml::Value;
use thiserror::Error;

use crate::manifest_path::MANIFEST_FILENAME;
use crate::RuntimeType;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
    pub name: String,
    pub version: String,
    pub runtime: String,
    pub implementation: Option<String>,
    /// Declared packaging type, from `execution:` (`wasm` | `native` | `static`). When present it
    /// is authoritative for [`Manifest::registry_runtime`]; when absent that method falls back to
    /// deriving the type from `runtime:` + `implementation:`.
    pub execution: Option<RuntimeType>,
    /// Companion files that must sit beside this manifest for `build_artifact` to succeed.
    /// Declared via `requires_files:`; when absent it defaults to `["skill.md"]` for
    /// `runtime: skill` and to an empty list for every other role. An explicit value — including
    /// an empty list — always wins over that default.
    pub requires_files: Vec<String>,
}

#[derive(Debug, Error)]
pub enum ManifestError {
    #[error("{} not found at {}", MANIFEST_FILENAME, .0)]
    NotFound(String),
    #[error("{0}")]
    YamlSyntax(String),
    #[error("{}: missing required field '{field}'", MANIFEST_FILENAME)]
    MissingField { field: String },
    #[error(
        "{}: field '{field}' has invalid type (expected {expected}, got {got})",
        MANIFEST_FILENAME
    )]
    InvalidType {
        field: String,
        expected: String,
        got: String,
    },
    #[error("{}: field '{field}' {message}", MANIFEST_FILENAME)]
    InvalidValue { field: String, message: String },
    #[error("failed to read {} at {path}: {source}", MANIFEST_FILENAME)]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
}

#[must_use = "validated manifest is required to proceed with build"]
pub fn load_manifest(path: &Path) -> Result<Manifest, ManifestError> {
    let content = fs::read_to_string(path).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            return ManifestError::NotFound(path.display().to_string());
        }
        ManifestError::Io {
            path: path.display().to_string(),
            source,
        }
    })?;

    Manifest::from_yaml_str(&content)
}

impl Manifest {
    /// The registry's packaging type for this artifact.
    ///
    /// A declared `execution:` field is authoritative. Only when it is absent does the type get
    /// derived from the role: `runtime: skill` → `Static`; `runtime: tool` +
    /// `implementation: native` → `Native`; everything else → `Wasm`.
    #[must_use]
    pub fn registry_runtime(&self) -> RuntimeType {
        if let Some(execution) = self.execution {
            return execution;
        }
        if self.runtime == "skill" {
            RuntimeType::Static
        } else if self.runtime == "tool" && self.implementation.as_deref() == Some("native") {
            RuntimeType::Native
        } else {
            RuntimeType::Wasm
        }
    }

    #[must_use = "parsed manifest is required to proceed with build"]
    pub fn from_yaml_str(input: &str) -> Result<Self, ManifestError> {
        let value: Value = serde_yaml::from_str(input).map_err(|err| {
            if let Some(location) = err.location() {
                ManifestError::YamlSyntax(format!(
                    "{}: YAML syntax error at line {}, column {}: {}",
                    MANIFEST_FILENAME,
                    location.line(),
                    location.column(),
                    err
                ))
            } else {
                ManifestError::YamlSyntax(format!("{MANIFEST_FILENAME}: YAML syntax error: {err}"))
            }
        })?;

        let root = value
            .as_mapping()
            .ok_or_else(|| ManifestError::InvalidType {
                field: "<root>".to_string(),
                expected: "mapping".to_string(),
                got: yaml_type_name(&value),
            })?;

        let name = required_string(root, "name")?;
        let version = required_string(root, "version")?;
        let runtime = required_string(root, "runtime")?;
        let implementation = optional_string(root, "implementation");
        let execution = optional_runtime_type(root, "execution")?;
        let requires_files = optional_string_seq(root, "requires_files")?
            .unwrap_or_else(|| default_requires_files(&runtime));

        Ok(Self {
            name,
            version,
            runtime,
            implementation,
            execution,
            requires_files,
        })
    }
}

/// The companion files a role requires when `requires_files:` is not declared. Reproduces the
/// hardcoded `skill.md` check `build_artifact` used to apply to `runtime: skill`, so a manifest
/// that says nothing about `requires_files:` builds exactly as it did before.
fn default_requires_files(runtime: &str) -> Vec<String> {
    if runtime == "skill" {
        vec!["skill.md".to_string()]
    } else {
        Vec::new()
    }
}

/// Parses `execution:` into a [`RuntimeType`]. An unparseable value is a hard error rather than a
/// silent fall-back to the derived default — a typo'd packaging type must not publish as `wasm`.
fn optional_runtime_type(
    root: &serde_yaml::Mapping,
    field: &str,
) -> Result<Option<RuntimeType>, ManifestError> {
    let key = Value::String(field.to_string());
    let Some(value) = root.get(&key) else {
        return Ok(None);
    };

    let raw = value.as_str().ok_or_else(|| ManifestError::InvalidType {
        field: field.to_string(),
        expected: "string".to_string(),
        got: yaml_type_name(value),
    })?;

    raw.parse::<RuntimeType>()
        .map(Some)
        .map_err(|_| ManifestError::InvalidType {
            field: field.to_string(),
            expected: "one of: wasm, native, static".to_string(),
            got: raw.to_string(),
        })
}

fn optional_string_seq(
    root: &serde_yaml::Mapping,
    field: &str,
) -> Result<Option<Vec<String>>, ManifestError> {
    let key = Value::String(field.to_string());
    let Some(value) = root.get(&key) else {
        return Ok(None);
    };

    let seq = value
        .as_sequence()
        .ok_or_else(|| ManifestError::InvalidType {
            field: field.to_string(),
            expected: "sequence of strings".to_string(),
            got: yaml_type_name(value),
        })?;

    seq.iter()
        .map(|entry| {
            entry
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| ManifestError::InvalidType {
                    field: field.to_string(),
                    expected: "sequence of strings".to_string(),
                    got: yaml_type_name(entry),
                })
        })
        .collect::<Result<Vec<_>, _>>()
        .map(Some)
}

fn optional_string(root: &serde_yaml::Mapping, field: &str) -> Option<String> {
    let key = serde_yaml::Value::String(field.to_string());
    root.get(&key)?.as_str().map(str::to_string)
}

fn required_string(root: &serde_yaml::Mapping, field: &str) -> Result<String, ManifestError> {
    let key = Value::String(field.to_string());
    let value = root.get(&key).ok_or_else(|| ManifestError::MissingField {
        field: field.into(),
    })?;

    let value_str = value.as_str().ok_or_else(|| ManifestError::InvalidType {
        field: field.to_string(),
        expected: "string".to_string(),
        got: yaml_type_name(value),
    })?;

    Ok(value_str.to_string())
}

/// What kind of YAML node this is, in the vocabulary a manifest author writes in, for a refusal
/// that tells them what they wrote rather than what a deserializer expected.
#[must_use]
pub fn describe_yaml_shape(value: &Value) -> &'static str {
    match value {
        Value::Null => "an empty block",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Sequence(_) => "a sequence",
        Value::Mapping(_) => "a mapping",
        Value::Tagged(_) => "a tagged value",
    }
}

fn yaml_type_name(value: &Value) -> String {
    match value {
        Value::Null => "null".into(),
        Value::Bool(_) => "boolean".into(),
        Value::Number(_) => "number".into(),
        Value::String(_) => "string".into(),
        Value::Sequence(_) => "sequence".into(),
        Value::Mapping(_) => "mapping".into(),
        Value::Tagged(_) => "tagged".into(),
    }
}

/// The substitution point for the entry's `gateway.api_key` in [`UpstreamAuth::value`].
pub const UPSTREAM_AUTH_KEY_PLACEHOLDER: &str = "{key}";

/// How an artifact's upstream expects its credential to be presented, from the artifact's own
/// bundled `murmur.yaml`:
///
/// ```yaml
/// upstream_auth:
///   header: Authorization
///   value: "Bearer {key}"
/// ```
///
/// The runtime attaches `header` to each request the artifact sends through its credential
/// gateway, with `{key}` replaced by the entry's `gateway.api_key`. Holds the template only, never
/// a key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpstreamAuth {
    /// A valid HTTP header name, as written. Compared case-insensitively on the wire.
    pub header: String,
    /// The header value template. Contains [`UPSTREAM_AUTH_KEY_PLACEHOLDER`] exactly once.
    pub value: String,
}

impl UpstreamAuth {
    /// The header value for `key`.
    #[must_use]
    pub fn render(&self, key: &str) -> String {
        self.value.replacen(UPSTREAM_AUTH_KEY_PLACEHOLDER, key, 1)
    }
}

/// Header names `upstream_auth.header` may not use.
///
/// The artifact picks the header, so it must not be able to pick one the upstream reflects into
/// the response it reads back (`Host` into a redirect or error page, `Origin` into CORS headers,
/// `Referer`, `Cookie`), nor one that routes or frames the request.
const RESERVED_AUTH_HEADERS: &[&str] = &[
    "host",
    "origin",
    "referer",
    "cookie",
    "connection",
    "content-length",
    "content-type",
    "content-encoding",
    "expect",
    "keep-alive",
    "te",
    "trailer",
    "transfer-encoding",
    "upgrade",
];

/// The retired name of the [`UpstreamAuth`] block. A manifest that declares it is refused by
/// [`refuse_retired_auth_block`]; nothing under this name is ever read.
pub const RETIRED_AUTH_BLOCK: &str = "inference_auth";

/// Refuses a manifest whose top level declares [`RETIRED_AUTH_BLOCK`], whatever it holds and
/// whether or not `upstream_auth:` sits beside it.
pub fn refuse_retired_auth_block(manifest_yaml: &str) -> Result<(), ManifestError> {
    refuse_retired_key(&parse_manifest_value(manifest_yaml)?)
}

fn refuse_retired_key(value: &Value) -> Result<(), ManifestError> {
    let declared = value
        .as_mapping()
        .is_some_and(|root| root.contains_key(Value::String(RETIRED_AUTH_BLOCK.to_string())));
    if declared {
        return Err(ManifestError::InvalidValue {
            field: RETIRED_AUTH_BLOCK.to_string(),
            message: "was renamed to 'upstream_auth'; this murmur reads only the new name"
                .to_string(),
        });
    }
    Ok(())
}

fn parse_manifest_value(manifest_yaml: &str) -> Result<Value, ManifestError> {
    serde_yaml::from_str(manifest_yaml).map_err(|err| {
        ManifestError::YamlSyntax(format!("{MANIFEST_FILENAME}: YAML syntax error: {err}"))
    })
}

/// Reads the top-level `upstream_auth:` block from an artifact's bundled manifest text.
///
/// `Ok(None)` means the manifest has no `upstream_auth` key. `Err` means the manifest declares
/// [`RETIRED_AUTH_BLOCK`], or the block is present and unusable: not a mapping, `header` or
/// `value` missing or not a string, `header` not a valid HTTP header name, or `value` not
/// containing `{key}` exactly once or carrying characters no header value may hold.
pub fn parse_upstream_auth(manifest_yaml: &str) -> Result<Option<UpstreamAuth>, ManifestError> {
    const FIELD: &str = "upstream_auth";
    let value = parse_manifest_value(manifest_yaml)?;
    refuse_retired_key(&value)?;
    let Some(block) = value
        .as_mapping()
        .and_then(|root| root.get(Value::String(FIELD.to_string())))
    else {
        return Ok(None);
    };
    let block = block
        .as_mapping()
        .ok_or_else(|| ManifestError::InvalidType {
            field: FIELD.to_string(),
            expected: "mapping".to_string(),
            got: yaml_type_name(block),
        })?;

    let header = required_string(block, "header").map_err(|err| prefix_field(err, FIELD))?;
    let template = required_string(block, "value").map_err(|err| prefix_field(err, FIELD))?;

    if http::HeaderName::from_bytes(header.as_bytes()).is_err() {
        return Err(ManifestError::InvalidValue {
            field: format!("{FIELD}.header"),
            message: format!("'{header}' is not a valid HTTP header name"),
        });
    }
    if RESERVED_AUTH_HEADERS
        .iter()
        .any(|reserved| header.eq_ignore_ascii_case(reserved))
    {
        return Err(ManifestError::InvalidValue {
            field: format!("{FIELD}.header"),
            message: format!(
                "'{header}' cannot carry the key: it controls how the request is routed or \
                 framed, or upstreams commonly echo it back in the response"
            ),
        });
    }
    let placeholders = template.matches(UPSTREAM_AUTH_KEY_PLACEHOLDER).count();
    if placeholders != 1 {
        return Err(ManifestError::InvalidValue {
            field: format!("{FIELD}.value"),
            message: format!(
                "must contain {UPSTREAM_AUTH_KEY_PLACEHOLDER} exactly once (found {placeholders})"
            ),
        });
    }
    if http::HeaderValue::from_str(&template.replace(UPSTREAM_AUTH_KEY_PLACEHOLDER, "")).is_err() {
        return Err(ManifestError::InvalidValue {
            field: format!("{FIELD}.value"),
            message: "contains characters an HTTP header value cannot hold".to_string(),
        });
    }

    Ok(Some(UpstreamAuth {
        header,
        value: template,
    }))
}

/// Names a child of `block` by its full dotted path rather than its bare key.
fn prefix_field(err: ManifestError, block: &str) -> ManifestError {
    match err {
        ManifestError::MissingField { field } => ManifestError::MissingField {
            field: format!("{block}.{field}"),
        },
        ManifestError::InvalidType {
            field,
            expected,
            got,
        } => ManifestError::InvalidType {
            field: format!("{block}.{field}"),
            expected,
            got,
        },
        other => other,
    }
}

#[cfg(test)]
mod upstream_auth_tests {
    use super::*;

    /// Each block exactly as the four shipped drivers write it, comment line included.
    const ANTHROPIC: &str = "name: murmur-driver-anthropic\nversion: 0.1.0\nruntime: driver\n\n\
        # How this provider expects the inference credential to be presented; the runtime substitutes {key}.\n\
        upstream_auth:\n  header: x-api-key\n  value: \"{key}\"\n";
    const BEARER: &str = "\n# How this provider expects the inference credential to be presented; the runtime substitutes {key}.\n\
        upstream_auth:\n  header: Authorization\n  value: \"Bearer {key}\"\n";

    fn bearer(name: &str) -> String {
        format!("name: {name}\nversion: 0.1.0\nruntime: driver\n{BEARER}")
    }

    #[test]
    fn upstream_auth_parses_the_anthropic_block() {
        let auth = parse_upstream_auth(ANTHROPIC).unwrap().unwrap();
        assert_eq!(auth.header, "x-api-key");
        assert_eq!(auth.render("sk-1"), "sk-1");
    }

    #[test]
    fn upstream_auth_parses_the_three_bearer_blocks() {
        for driver in [
            "murmur-driver-openai",
            "murmur-driver-deepseek",
            "murmur-driver-moonshotai",
        ] {
            let auth = parse_upstream_auth(&bearer(driver)).unwrap().unwrap();
            assert_eq!(auth.header, "Authorization", "{driver}");
            assert_eq!(auth.render("sk-2"), "Bearer sk-2", "{driver}");
        }
    }

    #[test]
    fn upstream_auth_absent_is_none() {
        let yaml = "name: d\nversion: 0.1.0\nruntime: driver\n";
        assert_eq!(parse_upstream_auth(yaml).unwrap(), None);
    }

    fn refused(block: &str) -> String {
        let yaml = format!("name: d\nversion: 0.1.0\nruntime: driver\n{block}");
        parse_upstream_auth(&yaml).unwrap_err().to_string()
    }

    #[test]
    fn upstream_auth_refuses_each_malformed_block() {
        let cases = [
            (
                "upstream_auth: x-api-key\n",
                "'upstream_auth' has invalid type",
            ),
            ("upstream_auth:\n", "'upstream_auth' has invalid type"),
            (
                "upstream_auth:\n  value: \"{key}\"\n",
                "'upstream_auth.header'",
            ),
            (
                "upstream_auth:\n  header: x-api-key\n",
                "'upstream_auth.value'",
            ),
            (
                "upstream_auth:\n  header: [x]\n  value: \"{key}\"\n",
                "'upstream_auth.header' has invalid type",
            ),
            (
                "upstream_auth:\n  header: x-api-key\n  value: 42\n",
                "'upstream_auth.value' has invalid type",
            ),
            (
                "upstream_auth:\n  header: \"bad header\"\n  value: \"{key}\"\n",
                "not a valid HTTP header name",
            ),
            (
                "upstream_auth:\n  header: \"\"\n  value: \"{key}\"\n",
                "not a valid HTTP header name",
            ),
            (
                "upstream_auth:\n  header: Authorization\n  value: Bearer\n",
                "exactly once (found 0)",
            ),
            (
                "upstream_auth:\n  header: Authorization\n  value: \"{key}{key}\"\n",
                "exactly once (found 2)",
            ),
            (
                "upstream_auth:\n  header: Authorization\n  value: \"Bearer\\n{key}\"\n",
                "cannot hold",
            ),
        ];
        for (block, expected) in cases {
            let message = refused(block);
            assert!(
                message.contains(expected),
                "{block:?}: expected {expected:?} in {message:?}"
            );
        }
    }

    #[test]
    fn upstream_auth_refuses_a_header_the_upstream_echoes_or_routes_by() {
        for header in ["Host", "origin", "Referer", "Cookie", "Content-Length"] {
            let message = refused(&format!(
                "upstream_auth:\n  header: {header}\n  value: \"{{key}}\"\n"
            ));
            assert!(
                message.contains("'upstream_auth.header'") && message.contains("cannot carry"),
                "{header}: {message}"
            );
        }
    }

    const RETIRED: &str = "inference_auth:\n  header: x-api-key\n  value: \"{key}\"\n";
    const RENAMED: &str = "field 'inference_auth' was renamed to 'upstream_auth'";

    #[test]
    fn retired_block_alone_is_refused() {
        let message = refused(RETIRED);
        assert!(message.contains(RENAMED), "{message}");
    }

    #[test]
    fn retired_block_beside_a_valid_upstream_auth_is_refused() {
        let message = refused(&format!(
            "upstream_auth:\n  header: Authorization\n  value: \"Bearer {{key}}\"\n{RETIRED}"
        ));
        assert!(message.contains(RENAMED), "{message}");
    }

    #[test]
    fn retired_block_check_passes_a_manifest_without_the_old_name() {
        let base = "name: d\nversion: 0.1.0\nruntime: tool\n";
        refuse_retired_auth_block(base).unwrap();
        refuse_retired_auth_block(&format!(
            "{base}upstream_auth:\n  header: x-api-key\n  value: \"{{key}}\"\n"
        ))
        .unwrap();
        assert!(matches!(
            refuse_retired_auth_block(&format!("{base}{RETIRED}")),
            Err(ManifestError::InvalidValue { field, .. }) if field == RETIRED_AUTH_BLOCK
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn missing_name_field_is_actionable() {
        let err = Manifest::from_yaml_str("version: 0.0.1\nruntime: wasm\n").unwrap_err();
        assert!(err.to_string().contains("missing required field 'name'"));
    }

    #[test]
    fn missing_version_field_is_actionable() {
        let err = Manifest::from_yaml_str("name: hello\nruntime: wasm\n").unwrap_err();
        assert!(err.to_string().contains("missing required field 'version'"));
    }

    #[test]
    fn missing_runtime_field_is_actionable() {
        let err = Manifest::from_yaml_str("name: hello\nversion: 0.0.1\n").unwrap_err();
        assert!(err.to_string().contains("missing required field 'runtime'"));
    }

    #[test]
    fn malformed_yaml_reports_line_info() {
        let err = Manifest::from_yaml_str("name: ok\nversion: [\n").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("line"));
        assert!(msg.contains("column"));
    }

    #[test]
    fn type_mismatch_reports_expected_and_got() {
        let err = Manifest::from_yaml_str("name: 42\nversion: 1.0.0\nruntime: wasm\n").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("field 'name'"));
        assert!(msg.contains("expected string"));
        assert!(msg.contains("got number"));
    }

    #[test]
    fn registry_runtime_skill_returns_static_type() {
        let manifest =
            Manifest::from_yaml_str("name: my-skill\nversion: 0.1.0\nruntime: skill\n").unwrap();
        assert_eq!(manifest.registry_runtime(), RuntimeType::Static);
    }

    #[test]
    fn registry_runtime_tool_native_returns_native() {
        let manifest = Manifest::from_yaml_str(
            "name: my-tool\nversion: 0.1.0\nruntime: tool\nimplementation: native\n",
        )
        .unwrap();
        assert_eq!(manifest.registry_runtime(), RuntimeType::Native);
    }

    #[test]
    fn registry_runtime_wasm_returns_wasm() {
        let manifest =
            Manifest::from_yaml_str("name: my-wasm\nversion: 0.1.0\nruntime: wasm\n").unwrap();
        assert_eq!(manifest.registry_runtime(), RuntimeType::Wasm);
    }

    #[test]
    fn execution_field_overrides_derived_registry_runtime() {
        let manifest = Manifest::from_yaml_str(
            "name: my-tool\nversion: 0.1.0\nruntime: tool\nexecution: static\n",
        )
        .unwrap();
        assert_eq!(manifest.execution, Some(RuntimeType::Static));
        // Role-based derivation would have said Wasm for a plain tool.
        assert_eq!(manifest.registry_runtime(), RuntimeType::Static);
    }

    #[test]
    fn execution_field_overrides_skill_static_default() {
        let manifest = Manifest::from_yaml_str(
            "name: my-skill\nversion: 0.1.0\nruntime: skill\nexecution: wasm\n",
        )
        .unwrap();
        assert_eq!(manifest.registry_runtime(), RuntimeType::Wasm);
    }

    #[test]
    fn execution_is_parsed_case_insensitively() {
        let manifest = Manifest::from_yaml_str(
            "name: my-tool\nversion: 0.1.0\nruntime: tool\nexecution: STATIC\n",
        )
        .unwrap();
        assert_eq!(manifest.registry_runtime(), RuntimeType::Static);
    }

    #[test]
    fn execution_absent_preserves_all_derived_branches() {
        let skill = Manifest::from_yaml_str("name: s\nversion: 0.1.0\nruntime: skill\n").unwrap();
        let native = Manifest::from_yaml_str(
            "name: n\nversion: 0.1.0\nruntime: tool\nimplementation: native\n",
        )
        .unwrap();
        let wasm = Manifest::from_yaml_str("name: w\nversion: 0.1.0\nruntime: tool\n").unwrap();

        assert_eq!(skill.execution, None);
        assert_eq!(skill.registry_runtime(), RuntimeType::Static);
        assert_eq!(native.registry_runtime(), RuntimeType::Native);
        assert_eq!(wasm.registry_runtime(), RuntimeType::Wasm);
    }

    #[test]
    fn invalid_execution_value_is_rejected() {
        let err = Manifest::from_yaml_str(
            "name: my-tool\nversion: 0.1.0\nruntime: tool\nexecution: banana\n",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("field 'execution'"), "error was: {msg}");
        assert!(msg.contains("wasm, native, static"), "error was: {msg}");
        assert!(msg.contains("got banana"), "error was: {msg}");
    }

    #[test]
    fn non_string_execution_value_is_rejected() {
        let err = Manifest::from_yaml_str(
            "name: my-tool\nversion: 0.1.0\nruntime: tool\nexecution: 42\n",
        )
        .unwrap_err();
        assert!(err.to_string().contains("field 'execution'"));
    }

    #[test]
    fn requires_files_defaults_to_skill_md_for_skill_role() {
        let manifest =
            Manifest::from_yaml_str("name: s\nversion: 0.1.0\nruntime: skill\n").unwrap();
        assert_eq!(manifest.requires_files, vec!["skill.md".to_string()]);
    }

    #[test]
    fn requires_files_defaults_to_empty_for_other_roles() {
        let manifest = Manifest::from_yaml_str("name: t\nversion: 0.1.0\nruntime: tool\n").unwrap();
        assert!(manifest.requires_files.is_empty());
    }

    #[test]
    fn explicit_requires_files_wins_over_role_default() {
        let manifest = Manifest::from_yaml_str(
            "name: t\nversion: 0.1.0\nruntime: tool\nrequires_files:\n  - config.json\n",
        )
        .unwrap();
        assert_eq!(manifest.requires_files, vec!["config.json".to_string()]);
    }

    #[test]
    fn explicit_empty_requires_files_overrides_skill_default() {
        let manifest = Manifest::from_yaml_str(
            "name: s\nversion: 0.1.0\nruntime: skill\nrequires_files: []\n",
        )
        .unwrap();
        assert!(manifest.requires_files.is_empty());
    }

    #[test]
    fn non_sequence_requires_files_is_rejected() {
        let err = Manifest::from_yaml_str(
            "name: s\nversion: 0.1.0\nruntime: skill\nrequires_files: nope\n",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("field 'requires_files'"), "error was: {msg}");
        assert!(msg.contains("sequence of strings"), "error was: {msg}");
    }
}