instruction-md 0.6.1

Read, check, resolve and verify instruction.md files (Markdown rules for AI agents, specification instruction/1): the reader and its diagnostics, the exact text an agent receives, composition of bases and includes, and Ed25519 signature verification. No I/O, no unsafe.
Documentation
//! S28 bindings as data: a `binding` extension manifest read (its `provides.protocol`), and the manifests this crate
//! ships so a host need not hard-code a protocol's stable versions. The port of `packages/spec/src/bindings.ts`. The
//! core names no protocol; these are extensions, versioned on their own, and a host may load others the same way.

use crate::protocol::Compat;
use serde_json::Value;

/// A version's maturity in its binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Maturity {
    Draft,
    Stable,
    Deprecated,
}

/// A binding: its extension id and version, and the protocol it describes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
    pub id: String,
    pub version: String,
    pub name: String,
    /// Each version with its maturity, in the manifest's order.
    pub versions: Vec<(String, Maturity)>,
    pub compat: Compat,
    pub kinds: Vec<String>,
    /// What the binding says an attribute means on a kind (`service.src`, `tool.name`), in the manifest's order.
    pub meaning: Vec<(String, String)>,
}

impl Binding {
    /// The stable versions: what a bare protocol name means (S28).
    pub fn stable(&self) -> Vec<&str> {
        self.versions.iter().filter(|(_, m)| *m == Maturity::Stable).map(|(v, _)| v.as_str()).collect()
    }
}

/// A binding manifest (format instruction-extension/1, role binding) read; `None` when it isn't one.
pub fn binding_from(m: &Value) -> Option<Binding> {
    if m.get("format")?.as_str()? != "instruction-extension/1" || !m.get("roles")?.as_array()?.iter().any(|r| r == "binding") {
        return None;
    }
    let p = m.get("provides")?.get("protocol")?;
    let versions = p
        .get("versions")?
        .as_object()?
        .iter()
        .map(|(v, s)| {
            let maturity = match s.as_str() {
                Some("stable") => Maturity::Stable,
                Some("deprecated") => Maturity::Deprecated,
                _ => Maturity::Draft,
            };
            (v.clone(), maturity)
        })
        .collect();
    let compat = match p.get("compat").and_then(Value::as_str) {
        Some("semver-minor") => Compat::SemverMinor,
        Some("date") => Compat::Date,
        _ => Compat::Exact,
    };
    Some(Binding {
        id: m.get("id")?.as_str()?.to_string(),
        version: m.get("version")?.as_str()?.to_string(),
        name: p.get("name")?.as_str()?.to_string(),
        versions,
        compat,
        kinds: p.get("kinds").and_then(Value::as_array).map(|k| k.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(),
        meaning: p
            .get("meaning")
            .and_then(Value::as_object)
            .map(|m| m.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string()))).collect())
            .unwrap_or_default(),
    })
}

/// x402 (HTTP 402 payments): version 2 stable, version 1 deprecated; versions compared as written.
pub fn x402() -> Binding {
    Binding {
        id: "org.x402/x402".into(),
        version: "2.0.0".into(),
        name: "x402".into(),
        versions: vec![("1".into(), Maturity::Deprecated), ("2".into(), Maturity::Stable)],
        compat: Compat::Exact,
        kinds: vec!["wallet".into(), "service".into()],
        meaning: Vec::new(),
    }
}

/// OpenAPI (S32; the specification's `bindings/openapi.extension.json`): 3.0 and 3.1 stable, 2.0 (Swagger) deprecated,
/// compared semver-minor. A `service`'s `src` is the OpenAPI document, and a `tool`'s `name` an operationId in it.
pub fn openapi() -> Binding {
    Binding {
        id: "org.openapis/openapi".into(),
        version: "1.0.0".into(),
        name: "openapi".into(),
        versions: vec![("2.0".into(), Maturity::Deprecated), ("3.0".into(), Maturity::Stable), ("3.1".into(), Maturity::Stable)],
        compat: Compat::SemverMinor,
        kinds: vec!["service".into(), "tool".into()],
        meaning: vec![
            ("service.src".into(), "the OpenAPI document (JSON or YAML), not the API's own address".into()),
            ("tool.name".into(), "an operation's operationId in that document".into()),
        ],
    }
}

/// The binding this crate ships for a protocol name.
pub fn known(name: &str) -> Option<Binding> {
    match name {
        "x402" => Some(x402()),
        "openapi" => Some(openapi()),
        _ => None,
    }
}

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

    #[test]
    fn reads_a_manifest_and_ships_x402() {
        let m: Value = serde_json::from_str(r#"{"format":"instruction-extension/1","id":"org.x402/x402","version":"2.0.0","spec":["1"],"roles":["binding"],"provides":{"protocol":{"name":"x402","versions":{"1":"deprecated","2":"stable"},"compat":"exact","kinds":["wallet","service"]}}}"#).unwrap();
        assert_eq!(binding_from(&m), Some(x402()));
        assert_eq!(x402().stable(), vec!["2"]);
        assert!(known("a2a").is_none());
    }

    #[test]
    fn ships_openapi_as_the_specification_publishes_it() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("conformance/specification/bindings/openapi.extension.json");
        let m: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
        assert_eq!(binding_from(&m), Some(openapi()));
        assert_eq!(known("openapi"), Some(openapi()));
        assert_eq!(openapi().stable(), vec!["3.0", "3.1"]);
    }
}