instruction-md 0.5.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
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
//! The text profile `instruction-text/1` (§14.2): the agent's representation of a document. Every generated unit — a
//! rule with its reason, a `### Label: Title` heading with its attribute line and children, an authored Markdown
//! segment — is separated from the next by exactly one blank line; an authored segment is copied unchanged except
//! that typed inline references read as `label (kind; target)`, annotations as their label, and parameters as their
//! values. Metadata and comments are never instructional body. A resolved document adds its resolved references and
//! its composition changes after the body.

use std::collections::HashSet;
use std::sync::LazyLock;

use serde_json::{Map, Value};

use crate::inline::{InlineToken, TokenType, inline_tokens};
use crate::jcs::canonical_json;
use crate::js::{JS_DOT, JS_SPACES, js_value, utf16_cmp};
use crate::pattern::Pattern;
use crate::read::Reading;
use crate::registry::{self, PRESENTATION_ATTRS, is_rule, typed_reference};
use crate::resolve::Provenance;
use crate::types::{Attrs, Document, Identity, Node, Object, Parameter};

/// Does the instance have the explicit id?
pub type Known<'a> = &'a dyn Fn(&str, &str) -> bool;

/// What the text profile knows of a tree beyond its body.
#[derive(Clone, Default)]
pub struct TextOptions<'a> {
    /// Supplied parameter values; a declared default stands in for an absent one (§12).
    pub params: Option<Object>,
    /// The document's declarations ([`Reading::parameters`]).
    pub parameters: Vec<Parameter>,
    /// Only the Markdown nodes the reader marked as parsed prose ([`Node::is_prose`]) are normalized; others are
    /// copied as written. False: every Markdown node outside an example, a verbatim body or a kind this registry does
    /// not define is.
    pub use_prose: bool,
    /// The local identities ([`Reading::identities`]): a typed reference to a missing `#id` reads `[unresolved]`.
    /// `None`: none is checked (an empty list: every `#id` is missing).
    pub identities: Option<Vec<Identity>>,
    /// For a resolved body: does the instance have the explicit id? A typed reference to `#id`, or to `#alias/id` in
    /// an included or inherited instance, that names one it does not have reads `[unresolved]`.
    pub known: Option<Known<'a>>,
}

/// An object or resource record a resolver enriched a reference with (§14.1).
#[derive(Clone, Debug, PartialEq)]
pub struct ReferenceRecord {
    pub key: String,
    pub kind: String,
    pub label: String,
    pub target: String,
    /// resolved or unresolved
    pub status: String,
    pub data: Option<Value>,
    pub source: String,
    pub sha256: String,
}

impl ReferenceRecord {
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("key".into(), self.key.clone().into());
        m.insert("kind".into(), self.kind.clone().into());
        m.insert("label".into(), self.label.clone().into());
        m.insert("target".into(), self.target.clone().into());
        m.insert("status".into(), self.status.clone().into());
        if let Some(d) = &self.data {
            m.insert("data".into(), d.clone());
        }
        if !self.source.is_empty() {
            m.insert("source".into(), self.source.clone().into());
        }
        if !self.sha256.is_empty() {
            m.insert("sha256".into(), self.sha256.clone().into());
        }
        Value::Object(m)
    }
}

struct Rx {
    param_ref: Pattern,
    reference: Pattern,
    ticks: Pattern,
}

static RX: LazyLock<Rx> = LazyLock::new(|| Rx {
    param_ref: Pattern::must(r"\$\{([A-Za-z_][A-Za-z0-9_.-]*)\}"),
    reference: Pattern::must(&format!(r#"(?:^|[ \t])ref=(?:"((?:[^"\\]|\\{JS_DOT})*)"|([^{JS_SPACES}{{}}"]+))"#)),
    ticks: Pattern::must("`+"),
});

fn rule_label(kind: &str) -> &'static str {
    match kind {
        "must" | "always" => "MUST",
        "never" => "NEVER",
        "should" => "SHOULD",
        "avoid" => "SHOULD NOT",
        "may" => "MAY",
        "guardrail" => "GUARDRAIL",
        _ => "",
    }
}

fn heading_label(kind: &str) -> Option<&'static str> {
    match kind {
        "policy" => Some("Policy"),
        "instruction" => Some("Instruction"),
        "context" => Some("Context"),
        _ => None,
    }
}

const UNIT_EXCLUDED: &[&str] = &["id", "title", "class", "style"];
const RULE_EXCLUDED: &[&str] = &["id", "if", "because", "not", "class", "style"];
pub(crate) const PATCHES: &[&str] = &["replace", "extend", "remove"];

/// The text profile of a tree.
pub fn to_text(doc: &Document, opts: &TextOptions) -> String {
    text_of(&doc.body, &[], &[], opts)
}

impl Reading {
    /// The text profile of the document read — the agent text — with its own declarations, prose and identities;
    /// `params` are supplied parameter values.
    pub fn text(&self, params: Option<&Object>) -> String {
        to_text(
            &self.document,
            &TextOptions {
                params: params.cloned(),
                parameters: self.parameters.clone(),
                use_prose: true,
                identities: Some(self.identities.clone()),
                known: None,
            },
        )
    }
}

struct Ctx<'o, 'a> {
    o: &'o TextOptions<'a>,
    identities: Option<HashSet<String>>,
}

pub(crate) fn text_of(body: &[Node], records: &[ReferenceRecord], provenance: &[Provenance], o: &TextOptions) -> String {
    let ctx = Ctx { o, identities: o.identities.as_ref().map(|ids| ids.iter().map(|i| i.id.clone()).collect()) };
    let mut text = units(body, &ctx).join("\n\n");
    if !records.is_empty() {
        let mut sorted: Vec<&ReferenceRecord> = records.iter().collect();
        sorted.sort_by(|a, b| utf16_cmp(&a.key, &b.key));
        let fenced: Vec<String> = sorted.iter().map(|r| fence(&canonical_json(&r.to_json()), "json")).collect();
        text.push_str("\n\n### Resolved references\n\n");
        text.push_str(&fenced.join("\n\n"));
    }
    let changes: Vec<String> = provenance
        .iter()
        .filter(|p| PATCHES.contains(&p.operation.as_str()))
        .map(|p| {
            let mut change = format!("- {} {} (origin: {})", p.operation, p.target, p.uri);
            if !p.reason.is_empty() {
                change.push_str(" — ");
                change.push_str(&p.reason);
            }
            change
        })
        .collect();
    if !changes.is_empty() {
        text.push_str("\n\n### Composition changes\n\n");
        text.push_str(&changes.join("\n"));
    }
    format!("{}\n", text.trim_end_matches('\n'))
}

fn units(nodes: &[Node], c: &Ctx) -> Vec<String> {
    nodes.iter().map(|n| if n.is_markdown() { markdown_unit(n, c) } else { directive_unit(n, c) }).filter(|u| !u.is_empty()).collect()
}

fn markdown_unit(n: &Node, c: &Ctx) -> String {
    if !c.o.use_prose || n.prose {
        let instance = if n.instance.is_empty() { "root" } else { &n.instance };
        return trim_lf(&normalize(&n.source, c, instance)).to_string();
    }
    trim_lf(&n.source).to_string()
}

/// A body copied as written — an example's, a verbatim one, or a kind this registry does not define (its fallback).
pub(crate) fn literal(n: &Node) -> bool {
    n.kind == "example" || n.attrs.get("verbatim") == Some(&Value::Bool(true)) || registry::kind(&n.kind).is_none()
}

fn raw_children(n: &Node) -> String {
    let s: String = n.children().iter().filter(|c| c.is_markdown()).map(|c| c.source.as_str()).collect();
    trim_lf(&s).to_string()
}

fn directive_unit(n: &Node, c: &Ctx) -> String {
    let a = &n.attrs;
    let children = || if literal(n) { raw_children(n) } else { units(n.children(), c).join("\n\n") };
    if is_rule(&n.kind) {
        let mut label = rule_label(&n.kind).to_string();
        if n.kind == "should" && a.get("not") == Some(&Value::Bool(true)) {
            label = "SHOULD NOT".into();
        }
        if let Some(Value::String(cond)) = a.get("if") {
            label = format!("{label} (if {})", interpolate(cond, c.o));
        }
        let mut t = format!("{label}: {}", children());
        if let Some(Value::String(because)) = a.get("because") {
            t.push_str("\nBECAUSE: ");
            t.push_str(&interpolate(because, c.o));
        }
        let rest = attribute_line(a, RULE_EXCLUDED, &[]);
        if !rest.is_empty() {
            t.push('\n');
            t.push_str(&rest);
        }
        return t;
    }
    let label = if n.kind == "example" && a.get("avoid") == Some(&Value::Bool(true)) {
        "Counterexample".to_string()
    } else if n.kind == "example" {
        "Example".to_string()
    } else if let Some(h) = heading_label(&n.kind) {
        h.to_string()
    } else {
        n.kind.clone()
    };
    let title = match (a.get("title"), a.get("id")) {
        (Some(Value::String(t)), _) if !t.is_empty() => t.clone(),
        (_, Some(Value::String(id))) => id.clone(),
        _ => n.kind.clone(),
    };
    let mut parts = vec![format!("### {label}: {title}")];
    let more: &[&str] = if n.kind == "example" {
        &["avoid"]
    } else if registry::kind(&n.kind).is_some_and(|k| k.family == "layout") {
        PRESENTATION_ATTRS
    } else {
        &[]
    };
    // (S29 §6: an allowance's limits in one fixed sentence, its amounts as they resolved)
    let line = if n.kind == "allowance" {
        // (a reader's text, unresolved, gives an allowance's ${parameters} their declared values, as it does prose's)
        let mut amounts = a.clone();
        for k in ["max", "budget", "approve-above", "times", "from", "until", "currency", "per"] {
            if let Some(Value::String(v)) = a.get(k) {
                amounts.insert(k.into(), Value::String(interpolate(v, c.o)));
            }
        }
        crate::allowance::sentence(&amounts, a.get("title").and_then(Value::as_str), a.get("id").and_then(Value::as_str))
    } else {
        attribute_line(a, UNIT_EXCLUDED, more)
    };
    if !line.is_empty() {
        parts.push(line);
    }
    if let Some(v) = &n.value {
        parts.push(fence(&v.source, &v.format));
    } else if n.kind == "example" {
        parts.push(fence(&raw_children(n), "markdown"));
    } else {
        let c = children();
        if !c.is_empty() {
            parts.push(c);
        }
    }
    parts.join("\n\n")
}

/// `Attributes: {…}` in RFC 8785 form, or "" when nothing meaningful is left.
fn attribute_line(a: &Attrs, excluded: &[&str], more: &[&str]) -> String {
    let kept: Map<String, Value> = a
        .iter()
        .filter(|(k, _)| !excluded.contains(&k.as_str()) && !more.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    if kept.is_empty() {
        return String::new();
    }
    format!("Attributes: {}", canonical_json(&Value::Object(kept)))
}

/// Puts literal text in a code fence: a backtick run longer than any inside it, at least three.
fn fence(text: &str, lang: &str) -> String {
    let longest = RX.ticks.find_iter(text).iter().map(|(a, b)| b - a).max().unwrap_or(0);
    let marker = "`".repeat(3.max(longest + 1));
    let body = if text.ends_with('\n') { text.to_string() } else { format!("{text}\n") };
    format!("{marker}{lang}\n{body}{marker}")
}

fn trim_lf(s: &str) -> &str {
    s.trim_matches('\n')
}

// ---- prose: typed references, annotations and parameters ----

/// A Markdown source with its inline forms in their text representation (§14.2 table).
fn normalize(source: &str, c: &Ctx, instance: &str) -> String {
    let tokens = inline_tokens(source);
    rewrite(source, 0, source.len(), &tokens, None, c, instance)
}

/// Writes source[from..to] with the tokens inside it in their text form; skip is a token not to rewrite (the
/// directive whose label this is).
fn rewrite(source: &str, from: usize, to: usize, tokens: &[InlineToken], skip: Option<usize>, c: &Ctx, instance: &str) -> String {
    let mut out = String::new();
    let mut at = from;
    for (i, t) in tokens.iter().enumerate() {
        // nested inside one already rewritten, or outside this range
        if Some(i) == skip || t.start < at || t.end > to {
            continue;
        }
        out.push_str(&source[at..t.start]);
        out.push_str(&token_text(source, tokens, i, c, instance));
        at = t.end;
    }
    out.push_str(&source[at..to]);
    out
}

fn token_text(source: &str, tokens: &[InlineToken], i: usize, c: &Ctx, instance: &str) -> String {
    let t = &tokens[i];
    let written = &source[t.start..t.end];
    match t.token_type {
        TokenType::Param => return param_text(&t.name, c.o).unwrap_or_else(|| written.to_string()),
        TokenType::Directive => {}
        _ => return written.to_string(),
    }
    let label = rewrite(source, t.label_start, t.label_end, tokens, Some(i), c, instance);
    if typed_reference(&t.kind) || t.kind == "ref" || t.kind == "cite" {
        let Some(target) = ref_of(t.attributes.as_deref()) else {
            return written.to_string();
        };
        let mut text = format!("{label} ({}; {target})", t.kind);
        if unresolved_target(&target, c, instance) {
            text.push_str(" [unresolved]");
        }
        return text;
    }
    label
}

/// A local target (#id, or #alias/id in a composed instance) that the document does not have.
fn unresolved_target(target: &str, c: &Ctx, instance: &str) -> bool {
    let Some(rest) = target.strip_prefix('#') else { return false };
    let path: Vec<&str> = rest.split('/').collect();
    let id = path[path.len() - 1];
    let path = &path[..path.len() - 1];
    if let Some(known) = c.o.known {
        let mut within = instance.to_string();
        if !path.is_empty() {
            within.push('/');
            within.push_str(&path.join("/"));
        }
        return !known(&within, id);
    }
    c.identities.as_ref().is_some_and(|ids| path.is_empty() && !ids.contains(id))
}

/// The ref attribute an inline directive's attribute list holds.
fn ref_of(attributes: Option<&str>) -> Option<String> {
    let attributes = attributes.filter(|a| !a.is_empty())?;
    let m = RX.reference.captures(attributes)?;
    if let Some(quoted) = m.get(attributes, 1) {
        return serde_json::from_str::<String>(&format!("\"{quoted}\"")).ok();
    }
    m.get(attributes, 2).map(str::to_string)
}

/// A parameter's value as text; `None` to leave `${name}` as written (§12).
fn param_text(name: &str, o: &TextOptions) -> Option<String> {
    if let Some(v) = o.params.as_ref().and_then(|p| p.get(name)) {
        return value_text(v);
    }
    o.parameters.iter().find(|p| p.name == name).and_then(|p| p.default.as_ref()).and_then(value_text)
}

/// How a value reads in text (§12): strings and list items with their Markdown punctuation escaped, booleans and
/// numbers as JSON scalars, lists joined with ", "; `None` for no value (null).
pub fn value_text(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        Value::Array(list) => Some(list.iter().map(|x| escape_value(&js_value(Some(x)))).collect::<Vec<_>>().join(", ")),
        Value::String(s) => Some(escape_value(s)),
        v => Some(canonical_json(v)),
    }
}

/// Substitutes parameters in a rule's condition or reason: the same values, as data.
fn interpolate(s: &str, o: &TextOptions) -> String {
    RX.param_ref.replace_all(s, |m| {
        let whole = m.get(s, 0).unwrap_or("");
        let name = m.get(s, 1).unwrap_or("");
        param_text(name, o).unwrap_or_else(|| whole.to_string())
    })
}

/// Substitutes parameters with values (a resolution's), as data.
pub(crate) fn interpolate_values(s: &str, values: &Object) -> String {
    RX.param_ref.replace_all(s, |m| {
        let whole = m.get(s, 0).unwrap_or("");
        let name = m.get(s, 1).unwrap_or("");
        values.get(name).and_then(value_text).unwrap_or_else(|| whole.to_string())
    })
}

/// A value inserts data, never syntax — the punctuation that could open Markdown or Instruction forms is escaped.
fn escape_value(v: &str) -> String {
    let mut out = String::with_capacity(v.len());
    for c in v.chars() {
        if "\\`*_{}[]<>|~$".contains(c) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}