silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use blake3::Hasher;
use regex::Regex;
use std::sync::LazyLock;
use unicode_normalization::char::is_combining_mark;
use unicode_normalization::UnicodeNormalization;

use crate::marker::ID;

static SIGN_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r#"(?i)\(\s*§\s*<a\s+id="({ID})">{ID}</a>\s*\)|§\s*<a\s+id="({ID})">{ID}</a>|\(\s*§\s*({ID})\s*\)|§\s+({ID})\b"#
    ))
    .expect("marker regex")
});

static ALIAS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r#"<a\s+id="({ID})"\s*></a>"#)).expect("alias regex"));

/// Ids a head carries as empty anchors: what it was named before an `accept`.
pub fn aliases_in(line: &str) -> Vec<String> {
    ALIAS_RE
        .captures_iter(line)
        .map(|c| c[1].to_string())
        .collect()
}

pub fn strip_aliases(line: &str) -> String {
    ALIAS_RE.replace_all(line, "").into_owned()
}

/// Crockford base32 without i, l, o, u.
const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
const LETTERS: &[u8; 22] = b"abcdefghjkmnpqrstvwxyz";

pub fn canonicalise(carrying: &str) -> String {
    // § nk4k8tqpr.a@r5r8x
    let unaliased = strip_aliases(carrying);
    let stripped = SIGN_RE.replace_all(&unaliased, "");
    // § end nk4k8tqpr.a
    // § nk4k8tqpr.b@yyavk
    let composed: String = stripped.nfc().collect();
    let mut out = String::with_capacity(composed.len());
    for (code, part) in code_spans(&composed) {
        if code {
            out.push_str(part);
        } else {
            out.extend(fold_prose(part));
        }
    }
    out.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Prose lowercased, decomposed, its combining marks dropped, so `é` composed or not is one
/// letter `e`. Every character left that is not a letter, a digit or a space goes, the
/// emphasis and code delimiters with it.
fn fold_prose(prose: &str) -> impl Iterator<Item = char> + '_ {
    // § nk4k8tqpr.b@87zfn
    prose
        .chars()
        .flat_map(char::to_lowercase)
        .nfkd()
        .filter(|c| !is_combining_mark(*c))
        .filter(|c| c.is_alphanumeric() || *c == ' ')
}

/// The text split into prose and code spans, in order, the flag set on code. A run of
/// backticks opens a span that the next run of the same length closes, as in markdown. An
/// unclosed run is prose.
pub(crate) fn code_spans(text: &str) -> Vec<(bool, &str)> {
    let bytes = text.as_bytes();
    let run = |at: usize| bytes[at..].iter().take_while(|&&b| b == b'`').count();
    let mut out = Vec::new();
    let (mut prose, mut i) = (0, 0);
    while i < bytes.len() {
        if bytes[i] != b'`' {
            i += 1;
            continue;
        }
        let open = run(i);
        let content = i + open;
        let mut j = content;
        let mut close = None;
        while j < bytes.len() {
            if bytes[j] != b'`' {
                j += 1;
                continue;
            }
            let n = run(j);
            if n == open {
                close = Some(j);
                break;
            }
            j += n;
        }
        match close {
            Some(j) => {
                out.push((false, &text[prose..i]));
                out.push((true, &text[content..j]));
                i = j + open;
                prose = i;
            }
            None => i = content,
        }
    }
    out.push((false, &text[prose..]));
    out
}

/// Canonical text a pin binds. Lines inside a code fence keep their bytes. Every other line
/// loses its head, its own ids and anchor wraps, as the id does, and keeps case, digits, signs
/// and punctuation, since `1.5` and `15` are two obligations.
pub fn pin_canon(body: &str) -> String {
    // § k6rfj5k37.f@84ev0
    let lines: Vec<&str> = body.lines().collect();
    let fence = crate::parse::fence_mask(&lines);
    let mut out = Vec::new();
    // The prose between two fences is one run, so a clause wrapped onto two lines reads as
    // it did on one.
    let mut prose = String::new();
    let flush = |prose: &mut String, out: &mut Vec<String>| {
        let composed: String = prose.nfc().collect();
        let c = composed.split_whitespace().collect::<Vec<_>>().join(" ");
        if !c.is_empty() {
            out.push(c);
        }
        prose.clear();
    };
    for (line, fenced) in lines.iter().zip(fence) {
        if fenced {
            flush(&mut prose, &mut out);
            out.push(line.to_string());
            continue;
        }
        let unaliased = strip_aliases(line);
        let signed = SIGN_RE.replace_all(&unaliased, "");
        prose.push_str(&signed);
        prose.push('\n');
    }
    flush(&mut prose, &mut out);
    out.join("\n")
}

pub fn mint_id(carrying: &str) -> String {
    // § nk4k8tqpr.a@9mw2t
    // silcrow:follow
    encode_hash(canonicalise(carrying).as_bytes())
}

fn encode_hash(bytes: &[u8]) -> String {
    // § nk4k8tqpr.c@vk692
    let mut hasher = Hasher::new();
    hasher.update(bytes);
    let mut xof = hasher.finalize_xof();
    let mut bits = [0u8; 6];
    xof.fill(&mut bits);
    encode_bits(&bits)
}

pub fn verify_id(carrying: &str, id: &str) -> bool {
    // § nk4k8tqpr.d@k5fmm
    if id.len() != 9 {
        return false;
    }
    mint_id(carrying) == normalise_id(id)
}

pub fn normalise_id(id: &str) -> String {
    id.chars().map(normalise_symbol).collect()
}

pub fn is_crockford_id(id: &str) -> bool {
    // § nk4k8tqpr.d@gb677
    if id.len() != 9 {
        return false;
    }
    // § end nk4k8tqpr.d
    // § n71fgy5xw@rjgf8
    let mut chars = id.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_alphabetic() || matches!(first, 'i' | 'l' | 'o' | 'u') {
        return false;
    }
    for c in chars {
        if !c.is_ascii_alphanumeric() {
            return false;
        }
        if matches!(c, 'i' | 'l' | 'o' | 'u') {
            return false;
        }
    }
    true
}

pub fn is_provisional_id(id: &str) -> bool {
    id.starts_with('+')
        && id.len() > 1
        && id[1..]
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

fn normalise_symbol(c: char) -> char {
    // § n71fgy5xw.a@84z5w
    let lower = c.to_ascii_lowercase();
    match lower {
        'i' | 'l' => '1',
        'o' => '0',
        _ => lower,
    }
}

fn encode_bits(bytes: &[u8; 6]) -> String {
    // § nk4k8tqpr.c@grqds
    let mut value: u64 = 0;
    for &b in bytes {
        value = (value << 8) | u64::from(b);
    }
    value >>= 3;
    let mut out = String::with_capacity(9);
    // § n71fgy5xw@rj1va
    let first = ((value >> 40) & 0x1f) as usize % LETTERS.len();
    out.push(LETTERS[first] as char);
    let mut rest = value & ((1u64 << 40) - 1);
    for _ in 0..8 {
        let idx = (rest & 0x1f) as usize;
        out.push(ALPHABET[idx] as char);
        rest >>= 5;
    }
    // § end n71fgy5xw
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wrapping_bold_does_not_remint() {
        let plain = "Four verbs: declare, cite, retire, implements. There is no verb apply.";
        let bold =
            "**§ abcdefgh1 Four verbs: declare, cite, retire, implements. There is no verb apply.**";
        assert_eq!(mint_id(plain), mint_id(bold));
    }

    #[test]
    fn canonicalise_strips_markers_and_emphasis() {
        let raw = "The `check` verb **must** resolve (§ abcdefgh1).";
        assert_eq!(canonicalise(raw), "the check verb must resolve");
    }

    #[test]
    fn canonicalise_strips_anchor_wrap() {
        let raw = r#"Binding sentence § <a id="abcdefgh1">abcdefgh1</a>."#;
        assert_eq!(canonicalise(raw), "binding sentence");
    }

    #[test]
    fn uppercase_marker_does_not_reach_the_hash() {
        assert_eq!(
            canonicalise("The graph fails (§ ABCDEFGH1) open, § ABCDEFGH1."),
            "the graph fails open"
        );
    }

    #[test]
    fn backticks_keep_case_and_punctuation() {
        let below = "Refuse a transfer when `amount < 1000`.";
        let above = "Refuse a transfer when `amount > 1000`.";
        assert_eq!(canonicalise(below), "refuse a transfer when amount < 1000");
        assert_ne!(mint_id(below), mint_id(above));
        assert_ne!(mint_id("Run `Check`."), mint_id("Run `check`."));
        assert_eq!(mint_id("Run `check`."), mint_id("Run *check*."));
    }

    #[test]
    fn double_backticks_hold_a_backtick() {
        assert_eq!(canonicalise("Strip `` ` `` and `*`."), "strip ` and *");
        assert_eq!(canonicalise("An `unclosed tick."), "an unclosed tick");
    }

    #[test]
    fn composed_and_decomposed_mint_one_id() {
        let nfc = "Un \u{e9}nonc\u{e9} porte une lettre.";
        let nfd = "Un e\u{301}nonce\u{301} porte une lettre.";
        assert_eq!(canonicalise(nfc), "un enonce porte une lettre");
        assert_eq!(mint_id(nfc), mint_id(nfd));
        assert_eq!(canonicalise("\u{c9}T\u{c9} \u{3a9}"), "ete \u{3c9}");
    }

    #[test]
    fn mint_is_deterministic() {
        let a = mint_id("Every verb the CLI names is either shipped or a stub.");
        let b = mint_id("Every verb the CLI names is either shipped or a stub.");
        assert_eq!(a, b);
        assert_eq!(a.len(), 9);
        assert!(a.chars().next().unwrap().is_ascii_alphabetic());
    }

    #[test]
    fn mint_differs_for_different_sentences() {
        assert_ne!(
            mint_id("First carrying sentence."),
            mint_id("Second carrying sentence.")
        );
    }

    #[test]
    fn normalise_maps_crockford_homoglyphs() {
        assert_eq!(normalise_id("abc1efgh1"), "abc1efgh1");
        assert_eq!(normalise_id("abciefgh1"), "abc1efgh1");
        assert_eq!(normalise_id("abc0efgh1"), "abc0efgh1");
    }

    #[test]
    fn verify_accepts_minted_id() {
        let sentence = "The graph path must not call a network, embeddings, or a model.";
        let id = mint_id(sentence);
        assert!(verify_id(sentence, &id));
    }

    #[test]
    fn alias_anchor_does_not_remint() {
        let plain = r#"**§ <a id="abcdefgh1">abcdefgh1</a> Every write goes through the writer.**"#;
        let aliased = r#"**§ <a id="abcdefgh1">abcdefgh1</a><a id="abcdefgh2"></a> Every write goes through the writer.**"#;
        assert_eq!(mint_id(plain), mint_id(aliased));
        assert_eq!(aliases_in(aliased), vec!["abcdefgh2".to_string()]);
    }

    // BLAKE3 of "" starts af1349b9f5f9 and of "abc" 6437b3ac3846 (the published reference
    // vectors). The ids below encode those six bytes by hand: 45 bits, top five mod 22 into the
    // letters, then eight symbols least significant first.
    #[test]
    fn mint_id_equals_ids_encoded_by_hand_from_blake3_reference_vectors() {
        assert_eq!(mint_id(""), "zznfekm9w");
        assert_eq!(mint_id("**§ abcdefgh1 Abc.**"), "p8r1b7vvg");
    }

    #[test]
    fn fence_lines_keep_their_bytes() {
        let a = "Run:\n```yaml\nkey: 1\n```";
        for b in [
            "Run:\n```yaml\nkey: 1 \n```",
            "Run:\n```yaml \nkey: 1\n```",
            "Run:\n```yaml\n  key: 1\n```",
        ] {
            assert_ne!(pin_canon(a), pin_canon(b), "{b:?}");
        }
        assert_eq!(
            pin_canon("Run:  now.\n```yaml\nkey: 1\n```"),
            pin_canon(a).replace("Run:", "Run: now.")
        );
    }

    #[test]
    fn a_tilde_fence_keeps_its_bytes() {
        let a = "Run:\n~~~yaml\nkey:\n  value: 1\n~~~";
        let b = "Run:\n~~~yaml\nkey:\n    value: 1\n~~~";
        assert_ne!(pin_canon(a), pin_canon(b));
        let long = "Run:\n````\n```\n  inner\n````\nAfter  it.";
        assert!(
            pin_canon(long).contains("```\n  inner"),
            "{}",
            pin_canon(long)
        );
        assert!(pin_canon(long).ends_with("After it."));
    }

    #[test]
    fn a_clause_wrapped_onto_two_lines_keeps_its_text() {
        assert_eq!(
            pin_canon("Retry within 1.5 days,\n  then stop."),
            pin_canon("Retry within 1.5 days, then stop.")
        );
        assert_ne!(
            pin_canon("Retry within 1.5 days,\nthen stop."),
            pin_canon("Retry within 1.5 days.\nthen stop.")
        );
    }

    #[test]
    fn fence_lines_keep_punctuation() {
        let a = "Flow:\n```mermaid\nA --> B\n```";
        let b = "Flow:\n```mermaid\nA -.-> B\n```";
        assert_ne!(pin_canon(a), pin_canon(b));
    }

    #[test]
    fn pin_text_keeps_digits_signs_and_punctuation() {
        for (a, b) in [
            ("Retry within 1.5 days.", "Retry within 15 days."),
            ("Refuse when amount < 10.", "Refuse when amount > 10."),
            ("Offset by -5.", "Offset by 5."),
            ("Charge 5% more.", "Charge 5 more."),
        ] {
            assert_ne!(pin_canon(a), pin_canon(b), "{a}");
        }
        assert_eq!(pin_canon("  One   line.\t"), "One line.");
        assert_eq!(
            pin_canon("Un e\u{301}tat § abcdefgh1 fixe."),
            pin_canon("Un \u{e9}tat fixe.")
        );
    }

    #[test]
    fn the_pin_text_and_the_id_strip_the_head_and_its_id() {
        assert_eq!(
            pin_canon("**§ <a id=\"abcdefgh1\">abcdefgh1</a> Rule.**"),
            pin_canon("**§ <a id=\"abcdefgh2\">abcdefgh2</a> Rule.**")
        );
        assert_eq!(
            mint_id("Rule holds (§ abcdefgh1)."),
            mint_id("Rule holds (§ abcdefgh2).")
        );
    }

    mod props {
        use super::super::*;
        use proptest::prelude::*;

        fn prop_hash_config() -> ProptestConfig {
            ProptestConfig {
                cases: 512,
                failure_persistence: None,
                ..ProptestConfig::default()
            }
        }

        fn prop_words() -> impl Strategy<Value = Vec<String>> {
            prop::collection::vec("[A-Za-z0-9]{1,8}[.,;:]?", 1..8)
        }

        /// Every form a marker takes in a carrying line, around an id or an alias anchor.
        fn prop_marker() -> impl Strategy<Value = String> {
            (crate::marker::ID, 0..6usize).prop_map(|(id, form)| match form {
                0 => format!("§ {id}"),
                5 => format!("§ {}", id.to_ascii_uppercase()),
                1 => format!("(§ {id})"),
                2 => format!("§ <a id=\"{id}\">{id}</a>"),
                3 => format!("(§ <a id=\"{id}\">{id}</a>)"),
                _ => format!("<a id=\"{id}\"></a>"),
            })
        }

        fn prop_with_marker(words: &[String], at: usize, marker: &str) -> String {
            let mut out: Vec<&str> = words.iter().map(String::as_str).collect();
            out.insert(at % (words.len() + 1), marker);
            out.join(" ")
        }

        proptest! {
            #![proptest_config(prop_hash_config())]

            // A code span keeps its case and punctuation and loses its backticks, so a
            // second pass would fold it: the property holds on prose.
            #[test]
            fn canonicalise_is_idempotent(s in "[ -_a-~]{0,120}") {
                let once = canonicalise(&s);
                prop_assert_eq!(canonicalise(&once), once);
            }

            #[test]
            fn a_marker_does_not_remint(
                words in prop_words(),
                marker in prop_marker(),
                at in any::<usize>(),
                to in any::<usize>(),
            ) {
                let plain = words.join(" ");
                let placed = prop_with_marker(&words, at, &marker);
                let moved = prop_with_marker(&words, to, &marker);
                let bold = format!("**{placed}**");
                prop_assert_eq!(mint_id(&placed), mint_id(&plain));
                prop_assert_eq!(mint_id(&moved), mint_id(&plain));
                prop_assert_eq!(mint_id(&bold), mint_id(&plain));
            }

            #[test]
            fn a_minted_id_is_crockford(s in "[ -~]{0,120}") {
                prop_assert!(is_crockford_id(&mint_id(&s)));
            }
        }
    }
}