instruction-md 0.4.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
Documentation
//! The registry (instruction/1, §7 and §20): every built-in block and inline kind, its body, forms and typed
//! attributes, the rule keywords and the grammar's patterns. The data is the specification's `registry.json`,
//! embedded as vendored (CC BY 4.0, instruction.md); this module only types it and answers what the reader, the text
//! profile and the checks ask of it.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::LazyLock;

use serde::Deserialize;
use serde_json::Value;

use crate::pattern::Pattern;

/// The registry as vendored: the specification's `registry.json`.
pub const REGISTRY_JSON: &str = include_str!("registry.json");

/// The JSON-Schema subset the registry types an attribute with. An empty spec accepts any value.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct AttrSpec {
    /// string, boolean, integer, number or array
    #[serde(rename = "type", default)]
    pub attr_type: String,
    #[serde(default, rename = "enum")]
    pub enum_values: Option<Vec<String>>,
    #[serde(default)]
    pub pattern: String,
    #[serde(default)]
    pub minimum: Option<f64>,
    #[serde(default)]
    pub maximum: Option<f64>,
    #[serde(default)]
    pub items: Option<Box<AttrSpec>>,
    #[serde(skip)]
    pub(crate) compiled: Option<Pattern>,
}

/// A block kind's registry entry.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct KindSpec {
    /// markdown, yaml or none
    pub body: String,
    /// container, leaf, keyword, alert
    pub forms: Vec<String>,
    #[serde(default)]
    pub attributes: BTreeMap<String, AttrSpec>,
    #[serde(default)]
    pub required: Vec<String>,
    #[serde(default)]
    pub family: String,
    /// The kind this one means: always is must, avoid is should with not, info is note (§6.1).
    #[serde(default)]
    pub alias: Option<String>,
    #[serde(default)]
    pub flags: Option<BTreeMap<String, Value>>,
    /// A column lives in columns, a tab in tabs, a step in steps (§8).
    #[serde(default)]
    pub parent: Option<String>,
    /// An example's body is quoted Markdown, never scanned for Instruction syntax (§6.2).
    #[serde(default)]
    pub opaque: bool,
    /// The bodies a format attribute may choose; none: the default body only.
    #[serde(default)]
    pub formats: Vec<String>,
}

impl KindSpec {
    /// Does the kind take this form?
    pub fn takes(&self, form: &str) -> bool {
        self.forms.iter().any(|f| f == form)
    }

    /// The bodies the kind's format attribute may choose.
    pub fn formats(&self) -> Vec<String> {
        if !self.formats.is_empty() {
            return self.formats.clone();
        }
        vec![if self.body == "yaml" { "yaml".into() } else { "markdown".into() }]
    }
}

#[derive(Debug, Default, Deserialize)]
struct Grammar {
    kind: String,
    id: String,
    parameter: String,
    digest: String,
}

/// The registry, typed.
#[derive(Debug, Default, Deserialize)]
pub struct Registry {
    /// instruction-registry/1
    pub format: String,
    /// The specification edition: "1".
    pub spec: String,
    /// The attributes every kind takes.
    pub common_attributes: BTreeMap<String, AttrSpec>,
    /// The block kinds, by name.
    pub kinds: BTreeMap<String, KindSpec>,
    /// The inline kinds and their own attributes.
    pub inline: BTreeMap<String, BTreeMap<String, AttrSpec>>,
    /// An authored keyword's kind: MUST NOT → never, ALWAYS → must, INFO → note.
    pub keywords: BTreeMap<String, String>,
    /// SHOULD NOT and AVOID keep their negation as not: true.
    pub keyword_flags: BTreeMap<String, BTreeMap<String, Value>>,
    grammar: Grammar,
    #[serde(skip)]
    kind_pattern: Option<Pattern>,
    #[serde(skip)]
    id_pattern: Option<Pattern>,
    #[serde(skip)]
    parameter_pattern: Option<Pattern>,
    #[serde(skip)]
    digest_pattern: Option<Pattern>,
}

static REGISTRY: LazyLock<Registry> = LazyLock::new(|| {
    // (the embedded registry is fixed data the tests read: should it ever not parse, the registry is empty, and
    // every kind reads as unknown, rather than a panic)
    let mut r: Registry = serde_json::from_str(REGISTRY_JSON).unwrap_or_default();
    let compile = |specs: &mut BTreeMap<String, AttrSpec>| {
        for s in specs.values_mut() {
            if !s.pattern.is_empty() {
                s.compiled = Some(Pattern::must(&s.pattern));
            }
        }
    };
    compile(&mut r.common_attributes);
    for k in r.kinds.values_mut() {
        compile(&mut k.attributes);
    }
    for a in r.inline.values_mut() {
        compile(a);
    }
    r.kind_pattern = Some(Pattern::must(&r.grammar.kind));
    r.id_pattern = Some(Pattern::must(&r.grammar.id));
    r.parameter_pattern = Some(Pattern::must(&r.grammar.parameter));
    r.digest_pattern = Some(Pattern::must(&r.grammar.digest));
    r
});

/// The registry.
pub fn registry() -> &'static Registry {
    &REGISTRY
}

static NEVER: LazyLock<Pattern> = LazyLock::new(|| Pattern::must("[^\\x{0}-\\x{10ffff}]"));

impl Registry {
    /// A block kind's entry.
    pub fn kind(&self, name: &str) -> Option<&KindSpec> {
        self.kinds.get(name)
    }

    /// The grammar's kind pattern: `[a-z][a-z0-9-]*`, optionally `alias:kind`.
    pub fn kind_pattern(&self) -> &Pattern {
        self.kind_pattern.as_ref().unwrap_or(&NEVER)
    }

    /// The grammar's explicit id pattern.
    pub fn id_pattern(&self) -> &Pattern {
        self.id_pattern.as_ref().unwrap_or(&NEVER)
    }

    /// The grammar's parameter name pattern.
    pub fn parameter_pattern(&self) -> &Pattern {
        self.parameter_pattern.as_ref().unwrap_or(&NEVER)
    }

    /// The grammar's digest pattern, `sha256:<64 lower hex>`.
    pub fn digest_pattern(&self) -> &Pattern {
        self.digest_pattern.as_ref().unwrap_or(&NEVER)
    }
}

/// The block kind's registry entry.
pub fn kind(name: &str) -> Option<&'static KindSpec> {
    registry().kinds.get(name)
}

/// The operative rule kinds (§6.1), aliases included.
pub const RULES: &[&str] = &["must", "should", "may", "never", "guardrail", "always", "avoid"];

/// Is the kind a rule?
pub fn is_rule(kind: &str) -> bool {
    RULES.contains(&kind)
}

/// The inline kinds that reference an object and must match the target's kind (§11.1); `ref` is generic.
pub const TYPED_REFERENCES: &[&str] = &["person", "role", "skill", "mcp", "tool", "agent", "service", "source", "resource"];

pub(crate) fn typed_reference(kind: &str) -> bool {
    TYPED_REFERENCES.contains(&kind)
}

/// The attribute an inline kind cannot do without.
pub fn inline_required(kind: &str) -> Option<&'static str> {
    Some(match kind {
        "ref" | "person" | "role" | "skill" | "mcp" | "tool" | "agent" | "service" | "source" | "resource" | "cite" => "ref",
        "button" => "href",
        "abbr" => "title",
        _ => return None,
    })
}

/// The front matter keys this edition defines (§3.1); any other is kept and means nothing to the core.
pub const FRONT_MATTER_KEYS: &[&str] = &[
    "spec",
    "id",
    "version",
    "title",
    "description",
    "language",
    "tags",
    "license",
    "parameters",
    "extends",
    "extensions",
    "references",
    "resolvers",
    "exports",
    "presentation",
    "requires",
];

/// The keys a backmatter may begin with (§3.2 rule 2).
pub const BACKMATTER_KEYS: &[&str] = &["authors", "owners", "review", "history", "sources", "approvals", "notes", "test_results"];

/// The attributes a generated text unit leaves out of a layout's attribute line (§14.2).
pub const PRESENTATION_ATTRS: &[&str] = &["class", "style", "count", "columns", "span", "open"];

/// A kind's normalized meaning: always reads as must, info as note.
pub fn canonical_kind(kind: &str) -> &str {
    match self::kind(kind).and_then(|k| k.alias.as_deref()) {
        Some(alias) => alias,
        None => kind,
    }
}

/// The spec a key has on a kind: the kind's own, then the common attributes.
pub fn attr_spec(kind: &str, key: &str) -> Option<&'static AttrSpec> {
    self::kind(kind).and_then(|k| k.attributes.get(key)).or_else(|| registry().common_attributes.get(key))
}

/// The spec a key has on an inline kind: its own, plus class, style and id.
pub fn inline_attr_spec(kind: &str, key: &str) -> Option<&'static AttrSpec> {
    if let Some(s) = registry().inline.get(kind).and_then(|a| a.get(key)) {
        return Some(s);
    }
    if matches!(key, "class" | "style" | "id") {
        return registry().common_attributes.get(key);
    }
    None
}

/// Every kind family the registry names (`guidance`, `layout`, `connected`, …).
pub fn all_families() -> BTreeSet<String> {
    registry().kinds.values().map(|k| k.family.clone()).filter(|f| !f.is_empty()).collect()
}

/// The authored keywords, longest first (then alphabetically), as the reader's patterns try them.
pub(crate) fn keyword_names() -> String {
    let mut names: Vec<&String> = registry().keywords.keys().collect();
    names.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
    names.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("|")
}