instruction_md/objects.rs
1//! A typed view of what a document declares beyond its guidance: its connected objects (§10) and the blocks that
2//! carry configuration (§9.1), found by the registry's families, with a walker over a tree's directives.
3//!
4//! - A **connected object** is a directive of a kind a typed reference can name (§11.1): the registry's `connected`
5//! family (`person`, `role`, `skill`, `mcp`, `tool`, `agent`, `service`, `source`) and `resource`.
6//! - A **configuration block** is a container of the registry's `technical` family with a structured (YAML) body:
7//! `config`, `workflow`, `schedule`, `sandbox`, `test`, `eval`, `data`, `properties` — data for an explicit compile
8//! or export, never instructions to the model (a `script`'s Markdown body is not one).
9//!
10//! Both are found wherever they stand, each with its [`Location`]: which directives hold it. Where a host takes
11//! configuration from is its own policy; [`Location::in_layout`] says whether a block stands at the top level or only
12//! inside layout containers (sections, tabs, columns…), outside any block whose body is guidance.
13//!
14//! ```
15//! use instruction_md::{configuration_blocks, connected_objects, read, ReadOptions};
16//!
17//! let r = read(
18//! ":::section{title=Tools}\n::mcp{id=cal title=Calendar src=\"https://example.org/mcp\" tools=\"events.list,availability.read\"}\n:::\n\n\
19//! :::config{id=runtime dialect=\"agentd/config\"}\nagent: { name: brief }\n:::\n",
20//! &ReadOptions::default(),
21//! );
22//! let objects = connected_objects(&r.document.body);
23//! assert_eq!((objects[0].kind, objects[0].id, objects[0].src), ("mcp", Some("cal"), Some("https://example.org/mcp")));
24//! assert_eq!(objects[0].list("tools"), ["events.list", "availability.read"]);
25//! assert_eq!(objects[0].location.parents, ["section"]);
26//! let config = configuration_blocks(&r.document.body);
27//! assert_eq!((config[0].kind, config[0].dialect), ("config", Some("agentd/config")));
28//! assert_eq!(config[0].data.unwrap()["agent"]["name"], "brief");
29//! assert!(config[0].location.in_layout());
30//! ```
31
32use serde_json::Value;
33
34use crate::registry;
35use crate::types::{Attrs, Form, Node, Range};
36
37/// Is a directive of this kind a connected object (a kind a typed reference names: the `connected` family, and
38/// `resource`)?
39pub fn is_connected(kind: &str) -> bool {
40 kind == "resource" || registry::kind(kind).is_some_and(|k| k.family == "connected")
41}
42
43/// Does a container of this kind carry configuration (the `technical` family, with a structured body)?
44pub fn carries_configuration(kind: &str) -> bool {
45 registry::kind(kind).is_some_and(|k| k.family == "technical" && k.body == "yaml")
46}
47
48/// Is this kind a layout container (sections, tabs, columns…)?
49pub fn is_layout(kind: &str) -> bool {
50 registry::kind(kind).is_some_and(|k| k.family == "layout")
51}
52
53/// Where a directive stands in its tree.
54#[derive(Clone, Debug, PartialEq)]
55pub struct Location<'a> {
56 /// Its lines in the source it was read from.
57 pub range: Option<Range>,
58 /// The kinds of the directives that hold it, outermost first; empty at the top level.
59 pub parents: Vec<&'a str>,
60 /// A resolved node's composition instance (`root`, `root/base`); empty for an authored tree.
61 pub instance: &'a str,
62}
63
64impl Location<'_> {
65 /// Does it stand at the top level or inside layout containers only — outside any block whose body is guidance
66 /// (a policy, a rule, an advisory) or another object's?
67 pub fn in_layout(&self) -> bool {
68 self.parents.iter().all(|k| is_layout(k))
69 }
70
71 /// The line it starts on.
72 pub fn line(&self) -> Option<u32> {
73 self.range.map(|r| r.start)
74 }
75}
76
77/// A connected object (§10): a person, role, skill, MCP server, tool, agent, service, source or resource the document
78/// declares.
79#[derive(Clone, Debug, PartialEq)]
80pub struct ConnectedObject<'a> {
81 pub node: &'a Node,
82 pub kind: &'a str,
83 /// `container` or `leaf`.
84 pub form: Form,
85 pub id: Option<&'a str>,
86 pub title: Option<&'a str>,
87 pub description: Option<&'a str>,
88 /// What it is or where it is found: a URL, a relative path, a registry record (`src`).
89 pub src: Option<&'a str>,
90 /// An A2A agent's interface URL (`endpoint`).
91 pub endpoint: Option<&'a str>,
92 /// Every attribute as read, these included: `tools`, `allow`, `deny`, `registry`, `server`, `account` (mcp);
93 /// `protocol`, `binding`, `tenant`, `skills` (agent); `trigger` (skill); `server`, `name` (tool); `role`…
94 pub attrs: &'a Attrs,
95 /// A container's body as written ([`Node::body_source`]): its usage guidance.
96 pub body: Option<&'a str>,
97 pub location: Location<'a>,
98}
99
100impl<'a> ConnectedObject<'a> {
101 /// A string attribute, trimmed, when it is not empty.
102 pub fn attr(&self, key: &str) -> Option<&'a str> {
103 nonempty(self.attrs.get(key))
104 }
105
106 /// A list attribute (`tools`, `allow`, `deny`, `skills`): its strings, or a string's comma-separated items.
107 pub fn list(&self, key: &str) -> Vec<&'a str> {
108 list(self.attrs.get(key))
109 }
110}
111
112/// A block that carries configuration (§9.1): a structured `config`, `workflow`, `schedule`, `sandbox`, `test`,
113/// `eval`, `data` or `properties` body.
114#[derive(Clone, Debug, PartialEq)]
115pub struct ConfigurationBlock<'a> {
116 pub node: &'a Node,
117 pub kind: &'a str,
118 pub id: Option<&'a str>,
119 pub title: Option<&'a str>,
120 /// The native dialect the body is written in (`agentd/config`, `instruction/workflow`).
121 pub dialect: Option<&'a str>,
122 /// The compiler or runtime profile it is for (`adapter`), and the object it configures (`target`).
123 pub adapter: Option<&'a str>,
124 pub target: Option<&'a str>,
125 /// The native schema that validates it, and its pin (`schema`, `schema-sha256`).
126 pub schema: Option<&'a str>,
127 pub schema_sha256: Option<&'a str>,
128 /// The body's format: yaml, json (and, for data, csv or text).
129 pub format: &'a str,
130 /// The body's data, when it parsed.
131 pub data: Option<&'a Value>,
132 /// The body as written ([`Node::body_source`]).
133 pub body: Option<&'a str>,
134 pub attrs: &'a Attrs,
135 pub location: Location<'a>,
136}
137
138impl<'a> ConfigurationBlock<'a> {
139 /// A string attribute, trimmed, when it is not empty.
140 pub fn attr(&self, key: &str) -> Option<&'a str> {
141 nonempty(self.attrs.get(key))
142 }
143}
144
145fn nonempty(v: Option<&Value>) -> Option<&str> {
146 v.and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
147}
148
149fn list(v: Option<&Value>) -> Vec<&str> {
150 match v {
151 Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).collect(),
152 Some(Value::String(s)) => s.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(),
153 _ => Vec::new(),
154 }
155}
156
157/// Visits every directive of a tree in document order, with the directives that hold it (outermost first); the
158/// visitor returns whether to visit the directive's children too. Markdown nodes are not visited.
159///
160/// ```
161/// use instruction_md::{read, walk, ReadOptions};
162///
163/// let r = read(":::policy{id=p}\nMUST: be kind.\n:::\n", &ReadOptions::default());
164/// let mut seen = Vec::new();
165/// walk(&r.document.body, &mut |n, parents| {
166/// seen.push((n.kind.clone(), parents.len()));
167/// true
168/// });
169/// assert_eq!(seen, [("policy".to_string(), 0), ("must".to_string(), 1)]);
170/// ```
171pub fn walk<'a>(body: &'a [Node], visit: &mut dyn FnMut(&'a Node, &[&'a Node]) -> bool) {
172 let mut parents: Vec<&'a Node> = Vec::new();
173 walk_in(body, &mut parents, visit);
174}
175
176fn walk_in<'a>(body: &'a [Node], parents: &mut Vec<&'a Node>, visit: &mut dyn FnMut(&'a Node, &[&'a Node]) -> bool) {
177 for n in body {
178 if !n.is_directive() {
179 continue;
180 }
181 if visit(n, parents) && !n.children().is_empty() {
182 parents.push(n);
183 walk_in(n.children(), parents, visit);
184 parents.pop();
185 }
186 }
187}
188
189fn location<'a>(n: &'a Node, parents: &[&'a Node]) -> Location<'a> {
190 Location { range: n.range, parents: parents.iter().map(|p| p.kind.as_str()).collect(), instance: &n.instance }
191}
192
193/// The connected objects of a tree (an authored or a resolved body), in document order, wherever they stand.
194pub fn connected_objects(body: &[Node]) -> Vec<ConnectedObject<'_>> {
195 let mut out = Vec::new();
196 walk(body, &mut |n, parents| {
197 if is_connected(&n.kind) {
198 out.push(ConnectedObject {
199 node: n,
200 kind: &n.kind,
201 form: n.form.unwrap_or(Form::Container),
202 id: nonempty(n.attrs.get("id")),
203 title: nonempty(n.attrs.get("title")),
204 description: nonempty(n.attrs.get("description")),
205 src: nonempty(n.attrs.get("src")),
206 endpoint: nonempty(n.attrs.get("endpoint")),
207 attrs: &n.attrs,
208 body: n.body_source(),
209 location: location(n, parents),
210 });
211 }
212 true
213 });
214 out
215}
216
217/// The configuration blocks of a tree, in document order, wherever they stand (see [`Location::in_layout`]).
218pub fn configuration_blocks(body: &[Node]) -> Vec<ConfigurationBlock<'_>> {
219 let mut out = Vec::new();
220 walk(body, &mut |n, parents| {
221 if carries_configuration(&n.kind) && n.form == Some(Form::Container) {
222 let attr = |k: &str| nonempty(n.attrs.get(k));
223 out.push(ConfigurationBlock {
224 node: n,
225 kind: &n.kind,
226 id: attr("id"),
227 title: attr("title"),
228 dialect: attr("dialect"),
229 adapter: attr("adapter"),
230 target: attr("target"),
231 schema: attr("schema"),
232 schema_sha256: attr("schema-sha256"),
233 format: n.value.as_ref().map_or("yaml", |v| v.format.as_str()),
234 data: n.value.as_ref().and_then(|v| v.data.as_ref()),
235 body: n.body_source(),
236 attrs: &n.attrs,
237 location: location(n, parents),
238 });
239 }
240 true
241 });
242 out
243}