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
//! A typed view of what a document declares beyond its guidance: its connected objects (§10) and the blocks that
//! carry configuration (§9.1), found by the registry's families, with a walker over a tree's directives.
//!
//! - A **connected object** is a directive of a kind a typed reference can name (§11.1): the registry's `connected`
//!   family (`person`, `role`, `skill`, `mcp`, `tool`, `agent`, `service`, `source`) and `resource`.
//! - A **configuration block** is a container of the registry's `technical` family with a structured (YAML) body:
//!   `config`, `workflow`, `schedule`, `sandbox`, `test`, `eval`, `data`, `properties` — data for an explicit compile
//!   or export, never instructions to the model (a `script`'s Markdown body is not one).
//!
//! Both are found wherever they stand, each with its [`Location`]: which directives hold it. Where a host takes
//! configuration from is its own policy; [`Location::in_layout`] says whether a block stands at the top level or only
//! inside layout containers (sections, tabs, columns…), outside any block whose body is guidance.
//!
//! ```
//! use instruction_md::{configuration_blocks, connected_objects, read, ReadOptions};
//!
//! let r = read(
//!     ":::section{title=Tools}\n::mcp{id=cal title=Calendar src=\"https://example.org/mcp\" tools=\"events.list,availability.read\"}\n:::\n\n\
//!      :::config{id=runtime dialect=\"agentd/config\"}\nagent: { name: brief }\n:::\n",
//!     &ReadOptions::default(),
//! );
//! let objects = connected_objects(&r.document.body);
//! assert_eq!((objects[0].kind, objects[0].id, objects[0].src), ("mcp", Some("cal"), Some("https://example.org/mcp")));
//! assert_eq!(objects[0].list("tools"), ["events.list", "availability.read"]);
//! assert_eq!(objects[0].location.parents, ["section"]);
//! let config = configuration_blocks(&r.document.body);
//! assert_eq!((config[0].kind, config[0].dialect), ("config", Some("agentd/config")));
//! assert_eq!(config[0].data.unwrap()["agent"]["name"], "brief");
//! assert!(config[0].location.in_layout());
//! ```

use serde_json::Value;

use crate::registry;
use crate::types::{Attrs, Form, Node, Range};

/// Is a directive of this kind a connected object (a kind a typed reference names: the `connected` family, and
/// `resource`)?
pub fn is_connected(kind: &str) -> bool {
    kind == "resource" || registry::kind(kind).is_some_and(|k| k.family == "connected")
}

/// Does a container of this kind carry configuration (the `technical` family, with a structured body)?
pub fn carries_configuration(kind: &str) -> bool {
    registry::kind(kind).is_some_and(|k| k.family == "technical" && k.body == "yaml")
}

/// Is this kind a layout container (sections, tabs, columns…)?
pub fn is_layout(kind: &str) -> bool {
    registry::kind(kind).is_some_and(|k| k.family == "layout")
}

/// Where a directive stands in its tree.
#[derive(Clone, Debug, PartialEq)]
pub struct Location<'a> {
    /// Its lines in the source it was read from.
    pub range: Option<Range>,
    /// The kinds of the directives that hold it, outermost first; empty at the top level.
    pub parents: Vec<&'a str>,
    /// A resolved node's composition instance (`root`, `root/base`); empty for an authored tree.
    pub instance: &'a str,
}

impl Location<'_> {
    /// Does it stand at the top level or inside layout containers only — outside any block whose body is guidance
    /// (a policy, a rule, an advisory) or another object's?
    pub fn in_layout(&self) -> bool {
        self.parents.iter().all(|k| is_layout(k))
    }

    /// The line it starts on.
    pub fn line(&self) -> Option<u32> {
        self.range.map(|r| r.start)
    }
}

/// A connected object (§10): a person, role, skill, MCP server, tool, agent, service, source or resource the document
/// declares.
#[derive(Clone, Debug, PartialEq)]
pub struct ConnectedObject<'a> {
    pub node: &'a Node,
    pub kind: &'a str,
    /// `container` or `leaf`.
    pub form: Form,
    pub id: Option<&'a str>,
    pub title: Option<&'a str>,
    pub description: Option<&'a str>,
    /// What it is or where it is found: a URL, a relative path, a registry record (`src`).
    pub src: Option<&'a str>,
    /// An A2A agent's interface URL (`endpoint`).
    pub endpoint: Option<&'a str>,
    /// Every attribute as read, these included: `tools`, `allow`, `deny`, `registry`, `server`, `account` (mcp);
    /// `protocol`, `binding`, `tenant`, `skills` (agent); `trigger` (skill); `server`, `name` (tool); `role`…
    pub attrs: &'a Attrs,
    /// A container's body as written ([`Node::body_source`]): its usage guidance.
    pub body: Option<&'a str>,
    pub location: Location<'a>,
}

impl<'a> ConnectedObject<'a> {
    /// A string attribute, trimmed, when it is not empty.
    pub fn attr(&self, key: &str) -> Option<&'a str> {
        nonempty(self.attrs.get(key))
    }

    /// A list attribute (`tools`, `allow`, `deny`, `skills`): its strings, or a string's comma-separated items.
    pub fn list(&self, key: &str) -> Vec<&'a str> {
        list(self.attrs.get(key))
    }
}

/// A block that carries configuration (§9.1): a structured `config`, `workflow`, `schedule`, `sandbox`, `test`,
/// `eval`, `data` or `properties` body.
#[derive(Clone, Debug, PartialEq)]
pub struct ConfigurationBlock<'a> {
    pub node: &'a Node,
    pub kind: &'a str,
    pub id: Option<&'a str>,
    pub title: Option<&'a str>,
    /// The native dialect the body is written in (`agentd/config`, `instruction/workflow`).
    pub dialect: Option<&'a str>,
    /// The compiler or runtime profile it is for (`adapter`), and the object it configures (`target`).
    pub adapter: Option<&'a str>,
    pub target: Option<&'a str>,
    /// The native schema that validates it, and its pin (`schema`, `schema-sha256`).
    pub schema: Option<&'a str>,
    pub schema_sha256: Option<&'a str>,
    /// The body's format: yaml, json (and, for data, csv or text).
    pub format: &'a str,
    /// The body's data, when it parsed.
    pub data: Option<&'a Value>,
    /// The body as written ([`Node::body_source`]).
    pub body: Option<&'a str>,
    pub attrs: &'a Attrs,
    pub location: Location<'a>,
}

impl<'a> ConfigurationBlock<'a> {
    /// A string attribute, trimmed, when it is not empty.
    pub fn attr(&self, key: &str) -> Option<&'a str> {
        nonempty(self.attrs.get(key))
    }
}

fn nonempty(v: Option<&Value>) -> Option<&str> {
    v.and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
}

fn list(v: Option<&Value>) -> Vec<&str> {
    match v {
        Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).collect(),
        Some(Value::String(s)) => s.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(),
        _ => Vec::new(),
    }
}

/// Visits every directive of a tree in document order, with the directives that hold it (outermost first); the
/// visitor returns whether to visit the directive's children too. Markdown nodes are not visited.
///
/// ```
/// use instruction_md::{read, walk, ReadOptions};
///
/// let r = read(":::policy{id=p}\nMUST: be kind.\n:::\n", &ReadOptions::default());
/// let mut seen = Vec::new();
/// walk(&r.document.body, &mut |n, parents| {
///     seen.push((n.kind.clone(), parents.len()));
///     true
/// });
/// assert_eq!(seen, [("policy".to_string(), 0), ("must".to_string(), 1)]);
/// ```
pub fn walk<'a>(body: &'a [Node], visit: &mut dyn FnMut(&'a Node, &[&'a Node]) -> bool) {
    let mut parents: Vec<&'a Node> = Vec::new();
    walk_in(body, &mut parents, visit);
}

fn walk_in<'a>(body: &'a [Node], parents: &mut Vec<&'a Node>, visit: &mut dyn FnMut(&'a Node, &[&'a Node]) -> bool) {
    for n in body {
        if !n.is_directive() {
            continue;
        }
        if visit(n, parents) && !n.children().is_empty() {
            parents.push(n);
            walk_in(n.children(), parents, visit);
            parents.pop();
        }
    }
}

fn location<'a>(n: &'a Node, parents: &[&'a Node]) -> Location<'a> {
    Location { range: n.range, parents: parents.iter().map(|p| p.kind.as_str()).collect(), instance: &n.instance }
}

/// The connected objects of a tree (an authored or a resolved body), in document order, wherever they stand.
pub fn connected_objects(body: &[Node]) -> Vec<ConnectedObject<'_>> {
    let mut out = Vec::new();
    walk(body, &mut |n, parents| {
        if is_connected(&n.kind) {
            out.push(ConnectedObject {
                node: n,
                kind: &n.kind,
                form: n.form.unwrap_or(Form::Container),
                id: nonempty(n.attrs.get("id")),
                title: nonempty(n.attrs.get("title")),
                description: nonempty(n.attrs.get("description")),
                src: nonempty(n.attrs.get("src")),
                endpoint: nonempty(n.attrs.get("endpoint")),
                attrs: &n.attrs,
                body: n.body_source(),
                location: location(n, parents),
            });
        }
        true
    });
    out
}

/// The configuration blocks of a tree, in document order, wherever they stand (see [`Location::in_layout`]).
pub fn configuration_blocks(body: &[Node]) -> Vec<ConfigurationBlock<'_>> {
    let mut out = Vec::new();
    walk(body, &mut |n, parents| {
        if carries_configuration(&n.kind) && n.form == Some(Form::Container) {
            let attr = |k: &str| nonempty(n.attrs.get(k));
            out.push(ConfigurationBlock {
                node: n,
                kind: &n.kind,
                id: attr("id"),
                title: attr("title"),
                dialect: attr("dialect"),
                adapter: attr("adapter"),
                target: attr("target"),
                schema: attr("schema"),
                schema_sha256: attr("schema-sha256"),
                format: n.value.as_ref().map_or("yaml", |v| v.format.as_str()),
                data: n.value.as_ref().and_then(|v| v.data.as_ref()),
                body: n.body_source(),
                attrs: &n.attrs,
                location: location(n, parents),
            });
        }
        true
    });
    out
}