instruction-md 0.6.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! S29 (first edition §10.1): an allowance's own checks, what makes a changed one wider, and the fixed sentence it is
//! delivered as — the port of `packages/spec/src/allowance.ts`, held to its vectors (`vectors/allowance`). The reader
//! runs [`problems`] on the values as written (a `${parameter}` is left for later); the composer runs it again once
//! parameters resolve, checks the references, and compares an inherited allowance with what replaced it
//! ([`widenings`]).

use serde_json::Value;

/// The six periods; `once` (the default) is the allowance's whole life.
pub const PERIODS: [&str; 6] = ["day", "week", "month", "quarter", "year", "once"];
const AMOUNTS: [&str; 3] = ["max", "budget", "approve-above"];

/// One problem: its code and what to say.
pub struct Problem {
    pub code: &'static str,
    pub message: String,
}

/// A value as text, as the reference's `String(v)`: an array joined with commas; nothing for absent or empty.
fn text(v: Option<&Value>) -> Option<String> {
    let s = match v? {
        Value::Null => return None,
        Value::String(s) => s.clone(),
        Value::Array(a) => a.iter().map(plain).collect::<Vec<_>>().join(","),
        other => plain(other),
    };
    (!s.is_empty()).then_some(s)
}

fn plain(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// A list attribute as written (`a,b` or the reader's array), each member trimmed.
pub fn list(v: Option<&Value>) -> Vec<String> {
    match v {
        Some(Value::Array(a)) => a.iter().map(|x| plain(x).trim().to_string()).collect(),
        Some(Value::String(s)) => s.split(',').map(|x| x.trim().to_string()).collect(),
        None | Some(Value::Null) => Vec::new(),
        Some(other) => vec![plain(other).trim().to_string()],
    }
}

/// A `${name}` somewhere in a string value: checked once parameters resolve.
fn pending(v: &str) -> bool {
    let b = v.as_bytes();
    let mut i = 0;
    while i + 2 < b.len() {
        if b[i] == b'$' && b[i + 1] == b'{' {
            let rest = &v[i + 2..];
            if let Some(end) = rest.find('}') {
                let name = &rest[..end];
                let mut chars = name.chars();
                if chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                    && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
                {
                    return true;
                }
            }
        }
        i += 1;
    }
    false
}

/// A decimal ≥ 0 with at most 18 fractional digits.
fn decimal(v: &str) -> bool {
    let (int, frac) = match v.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (v, None),
    };
    !int.is_empty()
        && int.bytes().all(|c| c.is_ascii_digit())
        && frac.is_none_or(|f| (1..=18).contains(&f.len()) && f.bytes().all(|c| c.is_ascii_digit()))
}

fn currency(v: &str) -> bool {
    v.len() == 3 && v.bytes().all(|c| c.is_ascii_uppercase())
}

fn domain(v: &str) -> bool {
    if v.is_empty() || v.len() > 253 {
        return false;
    }
    let labels: Vec<&str> = v.split('.').collect();
    if labels.len() < 2 {
        return false;
    }
    let (last, rest) = labels.split_last().unwrap();
    let label = |l: &str| {
        let b = l.as_bytes();
        !b.is_empty()
            && b.len() <= 63
            && b[0].is_ascii_alphanumeric()
            && b[b.len() - 1].is_ascii_alphanumeric()
            && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
    };
    let lb = last.as_bytes();
    rest.iter().all(|l| label(l))
        && !lb.is_empty()
        && lb.len() <= 63
        && lb[0].is_ascii_alphabetic()
        && lb.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
}

fn merchant(v: &str) -> bool {
    let b = v.as_bytes();
    !b.is_empty() && b.len() <= 128 && b[0].is_ascii_alphanumeric() && b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b':' | b'-'))
}

fn is_date(v: &str) -> bool {
    let b = v.as_bytes();
    b.len() == 10 && b[4] == b'-' && b[7] == b'-' && b.iter().enumerate().all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit())
}

/// Days from 1970-01-01 to a civil date (Howard Hinnant's algorithm).
fn days(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

fn num(s: &str) -> Option<i64> {
    (!s.is_empty() && s.bytes().all(|c| c.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}

/// Milliseconds since the epoch of a date or an RFC 3339 date-time; `None` when it is neither. A date alone is a whole
/// day: from its start (`from`), or through its end (`until`, before 00:00 the next day).
pub fn instant(v: &str, until: bool) -> Option<i64> {
    if v.len() < 10 || !is_date(&v[..10]) {
        return None;
    }
    let (y, mo, d) = (num(&v[0..4])?, num(&v[5..7])?, num(&v[8..10])?);
    if !(1..=12).contains(&mo) || !(1..=31).contains(&d) {
        return None;
    }
    let day_ms = days(y, mo, d) * 86_400_000;
    if v.len() == 10 {
        return Some(day_ms + if until { 86_400_000 } else { 0 });
    }
    let t = &v[10..];
    let t = t.strip_prefix('T').or_else(|| t.strip_prefix('t'))?;
    if t.len() < 5 || t.as_bytes()[2] != b':' {
        return None;
    }
    let (h, mi) = (num(&t[0..2])?, num(&t[3..5])?);
    let mut rest = &t[5..];
    let mut s = 0;
    let mut ms = 0;
    if let Some(r) = rest.strip_prefix(':') {
        if r.len() < 2 {
            return None;
        }
        s = num(&r[0..2])?;
        rest = &r[2..];
        if let Some(r) = rest.strip_prefix('.') {
            let n = r.bytes().take_while(u8::is_ascii_digit).count();
            if n == 0 {
                return None;
            }
            let frac = &r[..n];
            ms = num(&format!("{:0<3}", &frac[..n.min(3)]))?;
            rest = &r[n..];
        }
    }
    let offset = match rest {
        "" => 0,
        "Z" | "z" => 0,
        o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) && o.as_bytes()[3] == b':' => {
            let m = num(&o[1..3])? * 60 + num(&o[4..6])?;
            if o.starts_with('+') { -m } else { m }
        }
        _ => return None,
    };
    if h > 23 || mi > 59 || s > 60 {
        return None;
    }
    Some(day_ms + ((h * 60 + mi + offset) * 60 + s) * 1000 + ms)
}

fn amount(v: &str) -> Option<f64> {
    decimal(v).then(|| v.parse().ok()).flatten()
}

/// What is wrong with one allowance's values, in the reference's order. `${…}` values are skipped.
pub fn problems(a: &serde_json::Map<String, Value>) -> Vec<Problem> {
    let mut out = Vec::new();
    let mut add = |code: &'static str, message: String| out.push(Problem { code, message });
    if text(a.get("budget")).is_none() {
        add("allowance-unbounded", "an allowance needs budget=… (it would limit nothing)".into());
    }
    let mut vals = [None, None, None];
    for (i, k) in AMOUNTS.iter().enumerate() {
        let Some(v) = text(a.get(*k)) else { continue };
        if pending(&v) {
            continue;
        }
        if !decimal(&v) {
            add("allowance-amount-invalid", format!("{k}={v} is not a decimal ≥ 0 with at most 18 fractional digits"));
            continue;
        }
        vals[i] = amount(&v);
    }
    let [max, budget, above] = vals;
    match text(a.get("currency")) {
        None => add("allowance-currency-invalid", "currency=… (an ISO 4217 code) names what its amounts are in".into()),
        Some(c) if !pending(&c) && !currency(&c) => add("allowance-currency-invalid", format!("currency={c} is not an uppercase ISO 4217 code")),
        _ => {}
    }
    if let Some(per) = text(a.get("per"))
        && !pending(&per)
        && !PERIODS.contains(&per.as_str())
    {
        add("allowance-per-unknown", format!("per={per} is one of {}", PERIODS.join(", ")));
    }
    if let Some(times) = text(a.get("times"))
        && !pending(&times)
        && !(times.bytes().all(|c| c.is_ascii_digit()) && !times.starts_with('0') && !times.is_empty())
    {
        add("allowance-amount-invalid", format!("times={times} is a whole number ≥ 1"));
    }
    if let (Some(m), Some(b)) = (max, budget)
        && m > b
    {
        add("allowance-max-over-budget", format!("max ({m}) is above budget ({b})"));
    }
    if let (Some(x), Some(m)) = (above, max.or(budget))
        && x > m
    {
        add("allowance-approve-above-over-max", format!("approve-above ({x}) is above {} ({m})", if max.is_some() { "max" } else { "budget" }));
    }
    let from = text(a.get("from"));
    let until = text(a.get("until"));
    for (k, v, edge) in [("from", &from, false), ("until", &until, true)] {
        if let Some(v) = v
            && !pending(v)
            && instant(v, edge).is_none()
        {
            add("allowance-amount-invalid", format!("{k}={v} is a date or a date-time (RFC 3339)"));
        }
    }
    if let (Some(f), Some(u)) = (&from, &until)
        && !pending(f)
        && !pending(u)
        && let (Some(fi), Some(ui)) = (instant(f, false), instant(u, true))
        && ui <= fi
    {
        add("allowance-window-inverted", format!("until ({u}) is before from ({f})"));
    }
    if a.contains_key("payees") {
        let ps = list(a.get("payees"));
        if ps.is_empty() || ps.iter().any(|p| if let Some(r) = p.strip_prefix('&') { r.is_empty() } else { !(domain(p) || merchant(p)) }) {
            add("allowance-payees-invalid", format!("payees={}: each is a domain, a merchant id or an &service reference", ps.join(",")));
        }
    }
    out
}

fn decimal_of(v: Option<&Value>) -> Option<f64> {
    text(v).filter(|s| decimal(s)).and_then(|s| s.parse().ok())
}

fn set(v: Option<&Value>) -> Vec<String> {
    list(v).into_iter().filter(|s| !s.is_empty()).collect()
}

fn subset(a: &[String], b: &[String]) -> bool {
    a.iter().all(|x| b.contains(x))
}

/// What `after` widens of `before` (S29 §5): each attribute named, empty when it only narrows.
pub fn widenings(before: &serde_json::Map<String, Value>, after: &serde_json::Map<String, Value>) -> Vec<&'static str> {
    let mut out = Vec::new();
    for k in ["max", "budget", "approve-above"] {
        if let Some(b) = decimal_of(before.get(k))
            && decimal_of(after.get(k)).is_none_or(|x| x > b)
        {
            out.push(k);
        }
    }
    if let Some(b) = decimal_of(before.get("times"))
        && decimal_of(after.get("times")).is_none_or(|x| x > b)
    {
        out.push("times");
    }
    let per = |m: &serde_json::Map<String, Value>| text(m.get("per")).unwrap_or_else(|| "once".into());
    if per(before) != per(after) {
        out.push("per");
    }
    if text(before.get("currency")) != text(after.get("currency")) {
        out.push("currency");
    }
    if !subset(&set(after.get("wallet")), &set(before.get("wallet"))) {
        out.push("wallet");
    }
    for k in ["payees", "categories"] {
        if before.contains_key(k) && (!after.contains_key(k) || !subset(&set(after.get(k)), &set(before.get(k)))) {
            out.push(k);
        }
    }
    let at = |m: &serde_json::Map<String, Value>, k: &str, until: bool| text(m.get(k)).and_then(|v| instant(&v, until));
    if text(before.get("from")).is_some() && at(after, "from", false).is_none_or(|a| at(before, "from", false).is_some_and(|b| a < b)) {
        out.push("from");
    }
    if text(before.get("until")).is_some() && at(after, "until", true).is_none_or(|a| at(before, "until", true).is_some_and(|b| a > b)) {
        out.push("until");
    }
    if let Some(b) = text(before.get("approver"))
        && text(after.get("approver")).as_deref() != Some(b.as_str())
    {
        out.push("approver");
    }
    out
}

/// The fixed sentence an allowance is delivered as (S29 §6), its amounts as they resolved.
pub fn sentence(a: &serde_json::Map<String, Value>, title: Option<&str>, id: Option<&str>) -> String {
    let mut parts: Vec<String> = Vec::new();
    let cur = text(a.get("currency")).unwrap_or_default();
    let wallets = set(a.get("wallet"));
    if !wallets.is_empty() {
        parts.push(format!("pay from {}{}", wallets.join(", "), if cur.is_empty() { String::new() } else { format!(" in {cur}") }));
    }
    let per = text(a.get("per")).unwrap_or_else(|| "once".into());
    let span = if per == "once" { "in total".to_string() } else { format!("per calendar {per} (UTC)") };
    let mut limits = Vec::new();
    if let Some(m) = text(a.get("max")) {
        limits.push(format!("at most {m} per payment"));
    }
    if let Some(b) = text(a.get("budget")) {
        limits.push(format!("{b} {span}"));
    }
    if !limits.is_empty() {
        parts.push(limits.join(" and "));
    }
    if let Some(t) = text(a.get("times")) {
        parts.push(format!("at most {t} payments {}", if per == "once" { "in total".to_string() } else { format!("per {per}") }));
    }
    if a.contains_key("payees") {
        parts.push(format!("only to {}", list(a.get("payees")).join(", ")));
    }
    if a.contains_key("categories") {
        parts.push(format!("only for {}", list(a.get("categories")).join(", ")));
    }
    if let Some(above) = text(a.get("approve-above")) {
        let who = text(a.get("approver")).unwrap_or_else(|| "the host's approver".into());
        parts.push(format!("ask {who} before any payment above {above}"));
    }
    let from = text(a.get("from"));
    let until = text(a.get("until"));
    if from.is_some() || until.is_some() {
        let mut w = Vec::new();
        if let Some(f) = from {
            w.push(format!("from {f}"));
        }
        if let Some(u) = until {
            w.push(format!("{} {u}", if is_date(&u) { "through" } else { "until" }));
        }
        parts.push(format!("{} (UTC)", w.join(" ")));
    }
    format!(
        "Allowance {}{}: {}.",
        title.map(|t| format!("\"{t}\" ")).unwrap_or_default(),
        id.map(|i| format!("(#{i})")).unwrap_or_default(),
        parts.join("; ")
    )
}

/// A protocol value: a short or reverse-domain name, then optionally "/" and its versions (S28).
pub fn protocol_ok(v: &str) -> bool {
    let short = |s: &str| {
        let b = s.as_bytes();
        !b.is_empty() && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
    };
    let part = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-');
    let versions = |s: &str| !s.is_empty() && s.split(',').all(|x| !x.is_empty() && x.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-'));
    let mut segs = v.split('/');
    let first = segs.next().unwrap_or("");
    if first.contains('.') {
        // reverse-domain: a.b/name, then optionally /versions
        let labels: Vec<&str> = first.split('.').collect();
        if labels.len() < 2 || !labels.iter().all(|l| part(l)) {
            return false;
        }
        let Some(name) = segs.next() else { return false };
        if !part(name) {
            return false;
        }
        match (segs.next(), segs.next()) {
            (None, _) => true,
            (Some(vs), None) => versions(vs),
            _ => false,
        }
    } else {
        if !short(first) {
            return false;
        }
        match (segs.next(), segs.next()) {
            (None, _) => true,
            (Some(vs), None) => versions(vs),
            _ => false,
        }
    }
}

/// The attributes that may be parameters; a value still holding `${…}` after resolution names no amount.
pub const PARAMETER_KEYS: [&str; 8] = ["max", "budget", "approve-above", "times", "from", "until", "currency", "per"];

/// Values still holding `${…}` once parameters resolved: a limit nobody set (an error, not a silent skip).
pub fn unresolved(a: &serde_json::Map<String, Value>) -> Vec<Problem> {
    PARAMETER_KEYS
        .iter()
        .filter_map(|k| match a.get(*k) {
            Some(Value::String(v)) if pending(v) => Some(Problem {
                code: "allowance-amount-invalid",
                message: format!("{k}={v} has no value: its parameter is not given and has no default"),
            }),
            _ => None,
        })
        .collect()
}

/// An allowance as a host reads it: its values typed, lists split, amounts as written (decimal strings, never
/// floats: a host keeps them exactly).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Allowance {
    pub id: Option<String>,
    pub title: Option<String>,
    pub wallets: Vec<String>,
    pub currency: Option<String>,
    pub max: Option<String>,
    pub budget: Option<String>,
    /// One of [`PERIODS`] as written; `once` when absent.
    pub per: String,
    pub times: Option<u64>,
    pub payees: Option<Vec<String>>,
    pub categories: Option<Vec<String>>,
    pub from: Option<String>,
    pub until: Option<String>,
    pub approve_above: Option<String>,
    pub approver: Option<String>,
}

/// An allowance node's attributes, typed.
pub fn typed(a: &serde_json::Map<String, Value>) -> Allowance {
    let t = |k: &str| text(a.get(k));
    let opt_list = |k: &str| a.contains_key(k).then(|| list(a.get(k)).into_iter().filter(|x| !x.is_empty()).collect());
    Allowance {
        id: t("id"),
        title: t("title"),
        wallets: list(a.get("wallet")).into_iter().filter(|x| !x.is_empty()).collect(),
        currency: t("currency"),
        max: t("max"),
        budget: t("budget"),
        per: t("per").unwrap_or_else(|| "once".into()),
        times: t("times").filter(|v| !v.starts_with('0') && v.bytes().all(|c| c.is_ascii_digit())).and_then(|v| v.parse().ok()),
        payees: opt_list("payees"),
        categories: opt_list("categories"),
        from: t("from"),
        until: t("until"),
        approve_above: t("approve-above"),
        approver: t("approver"),
    }
}