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
//! What each source line of a document is, for editors that colour or fold Markdown source, and for the formatter.
//! Every class comes from the reader's own tree — its metadata ranges, its directives' opening and closing lines, its
//! rules, reasons and alerts, its comments — so an editor cannot show a line as a rule that the reader reads as prose.
//! Only inside a Markdown node does a line's own text decide (a heading, a code fence).

use std::sync::LazyLock;

use crate::js::js_trim;
use crate::pattern::Pattern;
use crate::read::{RX, ReadOptions, Reading, read};
use crate::text::literal;
use crate::types::{Form, Node};

/// A line's class: front-matter, backmatter, code, comment, heading, directive, alert, keyword, reason, data (a
/// structured body), literal (a body quoted as written) or prose.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LineInfo {
    pub class: &'static str,
    /// On keyword and reason lines: the byte offset where the label (`- **MUST[id] (if …):**`, `BECAUSE:`) ends.
    pub label_end: usize,
    /// On keyword and alert lines: the keyword as written (MUST NOT, AVOID, TIP).
    pub keyword: String,
    /// On directive lines: the kind they open, close or are.
    pub kind: String,
}

impl LineInfo {
    fn class(class: &'static str) -> LineInfo {
        LineInfo { class, ..LineInfo::default() }
    }
}

struct Rx {
    label_lead: Pattern,
    label: Pattern,
    reason: Pattern,
    fence_start: Pattern,
}

static LRX: LazyLock<Rx> = LazyLock::new(|| {
    let kw = crate::registry::keyword_names();
    let sp = crate::js::JS_SPACES;
    Rx {
        label_lead: Pattern::must(r"^(?:[ \t]*>[ \t]?)*[ \t]*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)?"),
        label: Pattern::must(&format!(r"^(?:\*\*)?(?:{kw})(?:\[[^\]{sp}]*\])?(?: \(if [^()\r\n]*\))?:(?:\*\*)?")),
        reason: Pattern::must(r"^(?:\*\*)?BECAUSE:(?:\*\*)?"),
        fence_start: Pattern::must(r"^(?:[ \t]*>)*[ \t]*(`{3,}|~{3,})"),
    }
});

/// One entry per line of the document read (as [`read`] splits it).
pub fn classify_lines(r: &Reading) -> Vec<LineInfo> {
    let mut out = vec![LineInfo::class("prose"); r.lines.len()];
    for &n in &r.comments {
        set(&mut out, n, LineInfo::class("comment"));
    }
    if let Some(fr) = r.front_range {
        span(&mut out, fr.start, fr.end, "front-matter");
    }
    if let Some(br) = r.back_range {
        span(&mut out, br.start, br.end, "backmatter");
    }
    walk(r, &r.document.body, &mut out);
    out
}

fn set(out: &mut [LineInfo], n: u32, info: LineInfo) {
    if n >= 1 && (n as usize) <= out.len() {
        out[n as usize - 1] = info;
    }
}

fn span(out: &mut [LineInfo], from: u32, to: u32, class: &'static str) {
    for n in from..=to {
        set(out, n, LineInfo::class(class));
    }
}

fn line_at(r: &Reading, n: u32) -> &str {
    if n >= 1 && (n as usize) <= r.lines.len() { &r.lines[n as usize - 1] } else { "" }
}

fn reason(r: &Reading, node: &Node, out: &mut [LineInfo]) {
    let Some(at) = node.reason else { return };
    set(out, at.start, LineInfo { label_end: label_end(line_at(r, at.start), &LRX.reason), ..LineInfo::class("reason") });
    if at.end > at.start {
        span(out, at.start + 1, at.end, "prose");
    }
}

fn walk(r: &Reading, nodes: &[Node], out: &mut [LineInfo]) {
    for node in nodes {
        let Some(rg) = node.range else { continue };
        if node.is_markdown() {
            classify_markdown(r, rg.start, rg.end, out);
            continue;
        }
        if matches!(node.form, Some(Form::Keyword | Form::Alert)) {
            walk(r, node.children(), out);
            let keyword = node.keyword.clone().unwrap_or_default();
            if node.form == Some(Form::Alert) {
                set(out, rg.start, LineInfo { keyword, ..LineInfo::class("alert") });
            } else {
                set(
                    out,
                    rg.start,
                    LineInfo { label_end: label_end(line_at(r, rg.start), &LRX.label), keyword, ..LineInfo::class("keyword") },
                );
            }
            reason(r, node, out);
            continue;
        }
        // a container or a leaf: its fences, then what lies between them
        let mut last = rg.start;
        if node.form == Some(Form::Container) && rg.end > rg.start && RX.close.is_match(line_at(r, rg.end)) {
            last = rg.end;
        }
        if node.form == Some(Form::Container) {
            if node.value.is_some() {
                if last > rg.start + 1 {
                    span(out, rg.start + 1, last - 1, "data");
                }
            } else if literal(node) {
                if last > rg.start + 1 {
                    span(out, rg.start + 1, last - 1, "literal");
                }
            } else {
                walk(r, node.children(), out);
            }
            reason(r, node, out);
        }
        set(out, rg.start, LineInfo { kind: node.kind.clone(), ..LineInfo::class("directive") });
        if last != rg.start {
            set(out, last, LineInfo { kind: node.kind.clone(), ..LineInfo::class("directive") });
        }
    }
}

/// Classes a Markdown node's lines: code fences and what they hold, ATX headings, the rest prose (comments kept).
fn classify_markdown(r: &Reading, from: u32, to: u32, out: &mut [LineInfo]) {
    let mut open = String::new();
    let mut n = from;
    while n <= to && (n as usize) <= out.len() {
        let line = &r.lines[n as usize - 1];
        let f = LRX.fence_start.captures(line);
        let i = n as usize - 1;
        n += 1;
        if !open.is_empty() {
            out[i] = LineInfo::class("code");
            if let Some(f) = &f {
                let run = f.get(line, 1).unwrap_or("");
                let whole = f.get(line, 0).unwrap_or("");
                if run.as_bytes()[0] == open.as_bytes()[0] && run.len() >= open.len() && js_trim(line) == js_trim(whole) {
                    open.clear();
                }
            }
            continue;
        }
        if let Some(f) = &f {
            open = f.get(line, 1).unwrap_or("```").to_string();
            out[i] = LineInfo::class("code");
            continue;
        }
        if out[i].class == "comment" {
            continue;
        }
        if RX.heading.is_match(line) {
            out[i] = LineInfo::class("heading");
        }
    }
}

fn label_end(line: &str, label: &Pattern) -> usize {
    let lead = LRX.label_lead.find_str(line).unwrap_or("");
    lead.len() + label.find_str(&line[lead.len()..]).map_or(0, str::len)
}

/// The conservative formatter: what an editor may change without changing what a reader or an agent receives — LF
/// line endings, one final newline, and no trailing whitespace on a directive's own lines (an opener, a closer, a
/// leaf), which the text profile regenerates rather than copies. Prose, code, structured bodies and metadata are left
/// as written: a trailing space in Markdown can be a line break, and a YAML edit can change a value.
pub fn format(text: &str) -> String {
    let bom = if text.starts_with('\u{feff}') { "\u{feff}" } else { "" };
    let r = read(text, &ReadOptions::default());
    let classes = classify_lines(&r);
    let lines: Vec<&str> = r
        .lines
        .iter()
        .enumerate()
        .map(|(i, l)| if classes[i].class == "directive" { l.trim_end_matches([' ', '\t']) } else { l.as_str() })
        .collect();
    let joined = lines.join("\n");
    let body = joined.trim_end_matches('\n');
    if body.is_empty() {
        return bom.to_string();
    }
    format!("{bom}{body}\n")
}