instruction-md 0.2.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

instruction-md (Rust)

The official Rust SDK for instruction.md: the specification's first edition (instruction/1, spec: "1"). It reads a document into its authored tree with the reader's diagnostics, checks it (the inline checks too), gives the agent's text (instruction-text/1), resolves a document with its bases and includes into the resolved artifact (instruction-resolved/1), and verifies author and delivery signatures (JWS, Ed25519).

It is a port of the Go SDK (sdks/go), itself a port of the TypeScript reference (packages/spec), and is held to them by the specification's conformance cases and the reference's vectors, vendored in conformance/ (specification commit af8400f).

  • Dependencies: serde, serde_json and, for signature verification, ring only. No unsafe.
  • Features: verify (default) is verify_author, verify_delivery and signing (for tests and tooling), the only use of ring. default-features = false reads, checks, resolves and digests (its SHA-256 is its own) with no ring.
  • Every entry point takes untrusted text and never panics: a problem is a [Diagnostic] with a stable code (the codes the Go and TypeScript readers emit: unclosed-directive, invalid-attributes, reference-optional, …).
  • Edition 2024, Rust 1.96 or later.
[dependencies]
instruction-md = "0.1"

Read, check, and give the agent its text

use instruction_md::{check_reading, read, ReadOptions, Severity};

let doc = "---\nspec: \"1\"\nparameters:\n  tz: { type: string, default: UTC }\n---\n\
           ::person{id=owner title=\"Alex\"}\n\n\
           MUST (if a meeting moves): tell :person[Alex]{ref=#owner} in ${tz}.\n\
           BECAUSE: the owner plans the day around it.\n";

let reading = read(doc, &ReadOptions::default());
let diagnostics = check_reading(&reading); // the reader's and the inline checks', in source order
for d in &diagnostics {
    // d.code is stable ("unclosed-directive", …); d.line() is where; d.message is for a person
    eprintln!("{d}");
}
assert!(!diagnostics.iter().any(|d| d.severity == Severity::Error));

let text = reading.text(None); // instruction-text/1, declared defaults substituted
assert!(text.contains("MUST (if a meeting moves): tell Alex (person; #owner) in UTC."));

instruction_md::deliver(text, params) does both in one call: (agent text, diagnostics), with the lines written in Specification 1.1 (legacy_diagnostics, code instruction.md/legacy-syntax, an error: a :::!kind block reads as prose here) as the TypeScript CLI reports them. reading.changes_text() says whether the agent text differs from the source at all (plain prose and canonical rules are handed on as written).

Connected objects, configuration and workflows

use instruction_md::{configuration_blocks, connected_objects, read, ReadOptions};

let r = read(":::mcp{id=cal src=\"https://example.org/mcp\" tools=\"events.list\"}\nRead appointments.\n:::\n",
             &ReadOptions::default());
for o in connected_objects(&r.document.body) {
    // kind, id, title, src, endpoint, attrs (list("tools")…), body (its source as written), location
    assert_eq!((o.kind, o.id, o.body), ("mcp", Some("cal"), Some("Read appointments.\n")));
    assert!(o.location.in_layout()); // at the top level or inside layout containers only
}
assert!(configuration_blocks(&r.document.body).is_empty()); // config, workflow, schedule, sandbox, test, eval, data, properties

Connected objects are the kinds a typed reference names (the registry's connected family and resource); configuration blocks are the technical family's structured bodies. walk(body, visitor) visits every directive with the directives that hold it; Node::body_source() is a container's body exactly as written; split_backmatter(text) cuts a document at its backmatter's --- separator, where Reading::back_range starts.

check_reading holds every :::workflow{dialect="instruction/workflow"} body to the specification's workflow registry (src/workflow-registry.json) and graph rules, as the TypeScript and Go readers do: invalid-workflow (an unknown kind or field, a missing required field, a step that depends on nothing but is not a trigger, a missing dependency or route, a cycle, no trigger or finish, an unreachable step…), limit-exceeded (512 steps in a scope, bodies nested deeper than 4, retry.max over 20) and extension-unavailable (an alias:node kind whose alias isn't declared), each an error on the line of the key it is about. The specification lists no host events, so an event trigger's on is the host's to check. Only the scoping kinds' body or branches hold nested steps (WORKFLOW_SCOPES, workflow_scope: foreach, batch, iterate, subgraph; parallel, race, from reference/workflows.md, since the registry doesn't say); another kind's field of that name, such as an http request's body, is data. workflow_diagnostics(definition, extensions) checks a definition on its own.

Resolve: bases, includes and parameters

use std::collections::HashMap;
use instruction_md::{resolve, ResolveOptions, Source};

let load = |uri: &str| -> Option<Source> {
    // the host loads sources (a file, a registry, an editor's workspace); the resolver fetches nothing itself
    std::fs::read_to_string(uri).ok().map(|text| Source { uri: uri.to_string(), text, version: String::new() })
};
let r = resolve("---\nextends:\n  - { uri: base.md, as: base }\n---\nMUST: be brief.\n",
                &ResolveOptions { uri: "instruction.md".into(), load: Some(&load), ..ResolveOptions::default() });
// r.ok: no error; r.text: the agent text; r.resolved: the instruction-resolved/1 artifact (to_json(), resolved_digest)

resolve_with takes sources already loaded (a map by resolved URI), resolve_tree resolves JSON trees.

Verify a signed read

use instruction_md::{verify_delivery, DeliveryVerifyOptions, Jwk};

fn admit(delivery_jws: &str, delivered_text: &str, delivery_keys: &[Jwk], publisher_keys: &[Jwk]) -> bool {
    let r = verify_delivery(
        delivery_jws,
        delivered_text.as_bytes(),
        delivery_keys,
        publisher_keys,
        &DeliveryVerifyOptions { aud: "principal://usr_1".into(), ..DeliveryVerifyOptions::default() },
    );
    if !r.ok {
        // r.code is stable ("digest-mismatch", "expired", "bad-signature"… VERIFY_CODES); r.reason is for a person
        eprintln!("refused ({}): {}", r.code, r.reason);
    }
    // when ok: r.claims are the delivery's, r.author the embedded author attestation's, both verified
    r.ok
}

The delivery signature binds the delivered text's digest, the audience, the resolution manifest and the embedded author signature, whose digest must be the resolved document's; delivered capabilities may not exceed the author's. Resolved::manifest() is what a delivery signs of its resolution (Manifest::to_json() is the manifest claim). verify_author checks an author signature over the authored bytes; public_jwk makes a JWK of a raw 32-byte Ed25519 key, and SigningKey + sign_jws sign (for tests and tooling).

For agentd: agentd-instruction → instruction-md

agentd-instruction reads the 1.1 syntax; this crate reads instruction/1. Where a concept carried over, its equivalent:

agentd-instruction instruction-md Note
parse(text) -> Result<Document, Vec<Refusal>> read(text, &ReadOptions) -> Reading reading.document is the tree; reading.diagnostics (plus check_reading for the inline checks) replace the Err; reading.has_errors()
Refusal { line, code, message } Diagnostic { code, severity, message, range, uri, … } same stable codes as the Go/TS readers; d.line() is range.start; warnings too, not only refusals
deliver(&doc, &ctx) -> Delivery { text, manifest } reading.text(params), or resolve(...) -> Resolution { text, resolved, ok, diagnostics } deliver(text, params) is the one-call shortcut
Context { params, resolve_include, .. } ResolveOptions { params, load, uri, .. }, TextOptions { params, .. } instruction/1 has no grants, facts or variants
Manifest (§7.4) Resolved::manifest() -> Manifest format, status, document (the authored digest and version), dependencies (the includes and bases), resolved_digest; no facts or variants in instruction/1
digest(&[u8]) digest(&[u8]) sha256:<hex>
author_digest(&[u8]) author_digest(&[u8]) the stored bytes as they are: in instruction/1 no signature: line is left out
front_matter_id(&[u8]) front_matter_id(&[u8]) read from the front matter by the YAML reader
doc::Node, doc::Block Node (node_type: Markdown or Directive) a block is a directive node: kind, form, attrs, children, value, range
doc::Form Form (Container, Leaf, Keyword, Alert) no sets or sections in instruction/1
doc::BodyKind KindSpec::body (markdown, yaml, none) and StructuredValue::format (yaml, json, csv, text, html, code) from registry().kind(name)
doc::Disposition is_connected, carries_configuration, is_layout by the registry's families: connected_objects, configuration_blocks, walk
doc::all_families() all_families() the registry's families
doc::lookup(kind), registry() registry::kind(kind), registry() the vendored registry.json, typed
tree_json(&doc) Document::to_json() the tree instruction.schema.json validates
validate(&doc, &ctx) check_reading(&reading)
yaml::parse(src) -> Result<Value, YamlError> parse_yaml(src) -> Result<Value, String> YAML 1.2 Core Schema, JSON-compatible values only
sign::verify_author, sign::verify_delivery, sign::verify_document verify_author, verify_delivery keys as JWKs (public_jwk(raw, kid)); results are VerifyResult { ok, code, claims, author, reason }
sign::Claims VerifyResult::claims (a JSON object)

Not in this crate

  • The follower and its MCP transport (the Go SDK's follow.go, mcphttp.go): following an instruction a registry serves, and reporting what was applied. They need an HTTP client; this crate does no I/O.
  • The upgrade from the 1.1 syntax (this crate reports its lines, legacy_diagnostics; the conversion is the TypeScript package's), the editor's fixes and the extension manifests' binding.

How it differs from the Go SDK

  • The YAML reader is this crate's own (Go wraps gopkg.in/yaml.v3): the values and every refusal the specification names (repeated keys, anchors and aliases, tags, non-string keys, non-finite numbers, a second document) are the reference's, with its messages; a syntax error's wording is this reader's. Where yaml.v3 (a YAML 1.1 reader) and the TypeScript reference's YAML 1.2 reader disagree, this crate reads as the reference does: ? inside a plain scalar in a flow collection ({ uri: https://example.org/?q }) and key:[…] in a flow mapping are values, and a flow collection's or quoted scalar's continuation lines must be indented past their block collection.
  • The inline tokenizer is a hand-written scanner with micromark's precedence (Go ports micromark itself): code spans, escapes, autolinks, raw HTML, link destinations and titles, definitions, tables and GFM autolink literals hide the forms, as there; it passes every inline vector and the read vectors.
  • Patterns use this crate's small regular-expression engine (a Pike VM over the specification's patterns), linear in its input.
  • Guards for hostile input: directives nest at most 128 deep (deeper openers stay prose, with an invalid-nesting diagnostic), YAML nests at most 256 deep, and directive labels are scanned for nested forms 32 deep.
  • Offsets (InlineToken::start, …) are byte offsets into the source, as in Go.

Tests

cargo test                    # the conformance cases and vectors, the reader, resolution, signatures, no-panic
cargo test -- --nocapture     # with each conformance suite's count
NO_PANIC_ROUNDS=2000 cargo test --release --test no_panic   # a longer randomized search
cargo test --no-default-features                            # without signature verification (and ring)

conformance/ holds copies of the specification's conformance cases, schemas and samples and of the reference's vectors (see conformance/README.md); tests/data/home holds the repository's home examples with the agent text and tree the Go SDK gives for them.

Licence

Licensed under either of the MIT licence or the Apache License, Version 2.0, at your option. Unless you say otherwise, a contribution you submit for inclusion in this crate is licensed as above, without other terms. This crate is permissively licensed although the repository around it is not (see NOTICE). The embedded registry (src/registry.json) is the specification's, under CC BY 4.0 (see NOTICE).