ic-ontology 0.1.1

Machine-readable cryptographic ontology for agent discovery and selection
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! Serializing the ontology for consumption outside Rust.
//!
//! Four formats, because agents arrive through different doors:
//!
//! | format | consumer |
//! |---|---|
//! | [`to_json`] | an LLM tool call, a CI check, `jq` |
//! | [`to_json_ld`] | a knowledge graph or RDF triple store |
//! | [`to_turtle`] | a SPARQL endpoint or an OWL reasoner |
//! | [`to_json_schema`] | a validator, or a tool-use schema generator |
//!
//! The writers are hand-rolled rather than derived from `serde`, which keeps
//! the whole workspace dependency-free. They are only ever fed static registry
//! data, but they still escape properly — [`escape_json`] is exercised directly
//! by the tests so that a future entry containing a quote or newline cannot
//! produce malformed output.

use crate::registry::REGISTRY;
use crate::types::{
    Class, Entry, FipsStatus, ImplStatus, Performance, Purpose, Relation, Severity, Unit,
};

/// The vocabulary IRI that JSON-LD and Turtle exports resolve terms against.
pub const VOCAB: &str = "https://nervosys.github.io/IronCrypto/ontology#";

/// Escape a string for inclusion in a JSON document.
pub fn escape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 8);
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out
}

fn json_string_array(items: impl Iterator<Item = String>) -> String {
    let mut out = String::from("[");
    for (i, item) in items.enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push('"');
        out.push_str(&item);
        out.push('"');
    }
    out.push(']');
    out
}

/// How an entry's relations are written out.
#[derive(Clone, Copy, PartialEq)]
enum Edges {
    /// A `relations` array of `{relation, target}` objects: the shape of the
    /// plain JSON export and of the published schema.
    Nested,
    /// One property per relation, keyed by the relation's vocabulary term.
    ///
    /// For JSON-LD, where the document is going into a triple store. The nested
    /// shape would put the relation's name in a literal on a blank node, so
    /// `ac:specializes` would not be a predicate anything could query, and the
    /// Turtle export of the same registry states exactly that predicate.
    Direct,
}

/// Render one entry as a JSON object.
pub fn entry_to_json(e: &Entry) -> String {
    entry_to_json_with(e, Edges::Nested)
}

fn entry_to_json_with(e: &Entry, edges: Edges) -> String {
    let mut out = String::new();
    out.push('{');
    out.push_str(&format!(r#""id":"{}","#, escape_json(e.id)));
    out.push_str(&format!(r#""name":"{}","#, escape_json(e.name)));
    out.push_str(&format!(r#""summary":"{}","#, escape_json(e.summary)));
    out.push_str(&format!(r#""class":"{}","#, e.class.id()));
    out.push_str(&format!(r#""family":"{}","#, escape_json(e.family)));
    out.push_str(&format!(r#""fipsStatus":"{}","#, e.fips.id()));
    out.push_str(&format!(r#""implementationStatus":"{}","#, e.status.id()));
    out.push_str(&format!(r#""performance":"{}","#, e.performance.id()));
    out.push_str(&format!(
        r#""approvedModeUsable":{},"#,
        e.approved_mode_ok()
    ));
    out.push_str(&format!(
        r#""strength":{{"classicalBits":{},"quantumBits":{}}},"#,
        e.strength.classical, e.strength.quantum
    ));
    out.push_str(&format!(
        r#""aliases":{},"#,
        json_string_array(e.aliases.iter().map(|a| escape_json(a)))
    ));
    out.push_str(&format!(
        r#""purposes":{},"#,
        json_string_array(e.purposes.iter().map(|p| p.id().to_string()))
    ));
    out.push_str(&format!(
        r#""standards":{},"#,
        json_string_array(e.standards.iter().map(|s| escape_json(s)))
    ));

    out.push_str(r#""parameters":["#);
    for (i, p) in e.params.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&format!(
            r#"{{"name":"{}","unit":"{}","min":{},"max":{},"recommended":{},"note":"{}"}}"#,
            escape_json(p.name),
            p.unit.id(),
            p.min,
            p.max,
            p.recommended,
            escape_json(p.note)
        ));
    }
    out.push_str("],");

    out.push_str(r#""constraints":["#);
    for (i, c) in e.constraints.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&format!(
            r#"{{"id":"{}","severity":"{}","requirement":"{}","consequence":"{}"}}"#,
            escape_json(c.id),
            c.severity.id(),
            escape_json(c.requirement),
            escape_json(c.consequence)
        ));
    }
    out.push_str("],");

    match edges {
        Edges::Nested => {
            out.push_str(r#""relations":["#);
            for (i, edge) in e.edges.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&format!(
                    r#"{{"relation":"{}","target":"{}"}}"#,
                    edge.relation.id(),
                    escape_json(edge.target)
                ));
            }
            out.push_str("],");
        }
        Edges::Direct => {
            // Several edges can share a relation, so the values are collected
            // per term; `@container: @set` in the context keeps a single one
            // from expanding differently to a pair.
            for relation in Relation::ALL {
                let targets: Vec<&str> = e
                    .edges
                    .iter()
                    .filter(|edge| edge.relation == *relation)
                    .map(|edge| edge.target)
                    .collect();
                if targets.is_empty() {
                    continue;
                }
                out.push_str(&format!(r#""{}":["#, term(relation.id())));
                for (i, t) in targets.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    out.push_str(&format!(r#""{}""#, escape_json(t)));
                }
                out.push_str("],");
            }
        }
    }

    out.push_str(&format!(r#""rustPath":"{}","#, escape_json(e.rust_path)));
    out.push_str(&format!(r#""example":"{}","#, escape_json(e.example)));
    out.push_str(&format!(r#""notes":"{}""#, escape_json(e.notes)));
    out.push('}');
    out
}

/// The whole registry as a JSON document.
pub fn to_json() -> String {
    let mut out = String::from("{\"version\":\"");
    out.push_str(env!("CARGO_PKG_VERSION"));
    out.push_str("\",\"vocabulary\":\"");
    out.push_str(VOCAB);
    out.push_str("\",\"algorithms\":[");
    for (i, e) in REGISTRY.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&entry_to_json(e));
    }
    out.push_str("]}");
    out
}

/// The registry as JSON-LD, for loading into a knowledge graph.
///
/// The `@context` maps every ontology term onto the [`VOCAB`] IRI and declares
/// each relation as a property whose values are node references, so
/// `built-on` becomes an edge a query can traverse rather than a literal
/// string. This is the one place the JSON-LD departs from [`to_json`]: that
/// export nests relations in a `relations` array, which is the better shape to
/// read and the wrong one to load, since it would hang the relation's name off
/// a blank node as a literal. The triples here are the ones [`to_turtle`]
/// states.
pub fn to_json_ld() -> String {
    let mut out = String::from("{\"@context\":{");
    out.push_str(&format!(r#""@vocab":"{VOCAB}","#));
    // `@id` values resolve against the base IRI, never against `@vocab`. With
    // no base declared, an entry's identity depended on the URL the document
    // was fetched from, so the same registry loaded from two places produced
    // two disjoint graphs -- and neither matched the Turtle export, which names
    // entries under `ac:` absolutely. Declaring the base fixes both.
    out.push_str(&format!(r#""@base":"{VOCAB}","#));
    out.push_str(r#""id":"@id","#);
    out.push_str(r#""algorithms":{"@id":"member","@container":"@set"},"#);
    // Each relation is a property whose value is a node, not a string. Without
    // this the target would expand to a literal and the edge would not exist.
    for relation in Relation::ALL {
        out.push_str(&format!(
            r#""{}":{{"@type":"@id","@container":"@set"}},"#,
            term(relation.id())
        ));
    }
    out.push_str(r#""class":{"@type":"@vocab"},"#);
    out.push_str(r#""purposes":{"@type":"@vocab","@container":"@set"},"#);
    out.push_str(r#""fipsStatus":{"@type":"@vocab"}"#);
    out.push_str("},\"@type\":\"AlgorithmRegistry\",\"algorithms\":[");
    for (i, e) in REGISTRY.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        let body = entry_to_json_with(e, Edges::Direct);
        // Splice in the node type after the opening brace.
        out.push('{');
        out.push_str("\"@type\":\"Algorithm\",");
        out.push_str(&body[1..]);
    }
    out.push_str("]}");
    out
}

/// The registry as RDF 1.1 Turtle.
///
/// Emitted so the ontology can be loaded into a SPARQL endpoint or reasoned
/// over with OWL tooling, which is the usual meaning of "ontology" outside the
/// Rust world.
pub fn to_turtle() -> String {
    let mut out = String::new();
    out.push_str(&format!("@prefix ac: <{VOCAB}> .\n"));
    out.push_str("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n");
    out.push_str("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n");
    out.push_str("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n");

    // Class hierarchy.
    out.push_str("ac:Algorithm a rdfs:Class ;\n    rdfs:label \"Cryptographic algorithm\" .\n\n");
    for c in Class::ALL {
        out.push_str(&format!(
            "ac:{} a rdfs:Class ;\n    rdfs:subClassOf ac:Algorithm .\n",
            term(c.id())
        ));
    }
    out.push('\n');
    for p in Purpose::ALL {
        out.push_str(&format!(
            "ac:{} a ac:Purpose ;\n    rdfs:label \"{}\" .\n",
            term(p.id()),
            p.id()
        ));
    }
    out.push('\n');

    for e in REGISTRY {
        out.push_str(&format!(
            "ac:{} a ac:{} ;\n",
            local_name(e.id),
            term(e.class.id())
        ));
        out.push_str(&format!("    rdfs:label \"{}\" ;\n", escape_json(e.name)));
        out.push_str(&format!(
            "    rdfs:comment \"{}\" ;\n",
            escape_json(e.summary)
        ));
        out.push_str(&format!("    ac:family \"{}\" ;\n", escape_json(e.family)));
        out.push_str(&format!("    ac:fipsStatus ac:{} ;\n", term(e.fips.id())));
        out.push_str(&format!(
            "    ac:implementationStatus ac:{} ;\n",
            term(e.status.id())
        ));
        out.push_str(&format!(
            "    ac:classicalBits \"{}\"^^xsd:integer ;\n",
            e.strength.classical
        ));
        out.push_str(&format!(
            "    ac:quantumBits \"{}\"^^xsd:integer ",
            e.strength.quantum
        ));
        for p in e.purposes {
            out.push_str(&format!(";\n    ac:servesPurpose ac:{} ", term(p.id())));
        }
        for edge in e.edges {
            out.push_str(&format!(
                ";\n    ac:{} ac:{} ",
                term(edge.relation.id()),
                local_name(edge.target)
            ));
        }
        out.push_str(".\n\n");
    }
    out
}

/// Convert a kebab-case identifier into a Turtle-safe camel-ish local name.
/// The Turtle local name for an entry, which is its identifier unchanged.
///
/// Distinct from [`term`], which camel-cases. That is right for a vocabulary
/// term -- `block-cipher` reads better as `ac:blockCipher` -- and wrong for an
/// identifier, where the segments are usually digits and there is nothing to
/// capitalise: `sha2-256` collapsed to `sha2256`, irreversibly, for 58 of the
/// 75 entries.
///
/// Nothing required it. `-` is in Turtle's `PN_CHARS` and is legal anywhere in
/// a local name except the first position, and the registry's identifiers are
/// constrained to `^[a-z0-9][a-z0-9._-]*$`, so they are already valid as they
/// stand. The assertion holds them to the part of that grammar this uses.
fn local_name(id: &str) -> &str {
    debug_assert!(
        id.chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
            && id
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "_-.".contains(c))
            && !id.ends_with('.'),
        "{id} is not a valid Turtle local name"
    );
    id
}

fn term(id: &str) -> String {
    let mut out = String::with_capacity(id.len());
    let mut upper_next = false;
    for c in id.chars() {
        match c {
            '-' | '.' | '/' => upper_next = true,
            c if upper_next => {
                out.extend(c.to_uppercase());
                upper_next = false;
            }
            c => out.push(c),
        }
    }
    out
}

/// A JSON Schema describing the shape of [`to_json`] output.
///
/// Emitted so an agent framework can validate ontology documents, and so a
/// tool-use schema can be generated from the same source of truth the library
/// uses at runtime.
pub fn to_json_schema() -> String {
    let classes = json_string_array(Class::ALL.iter().map(|c| c.id().to_string()));
    let purposes = json_string_array(Purpose::ALL.iter().map(|p| p.id().to_string()));
    // Derived rather than written out. `implementationStatus` was inline and
    // went stale when `Experimental` was added, so the published schema
    // rejected the four entries carrying that status -- the unverified ones,
    // which are exactly the entries a consumer most needs described.
    let fips_statuses = json_string_array(FipsStatus::ALL.iter().map(|v| v.id().to_string()));
    let impl_statuses = json_string_array(ImplStatus::ALL.iter().map(|v| v.id().to_string()));
    let performances = json_string_array(Performance::ALL.iter().map(|v| v.id().to_string()));
    let severities = json_string_array(Severity::ALL.iter().map(|v| v.id().to_string()));
    let units = json_string_array(Unit::ALL.iter().map(|v| v.id().to_string()));
    let relations = json_string_array(Relation::ALL.iter().map(|v| v.id().to_string()));
    format!(
        r##"{{"$schema":"https://json-schema.org/draft/2020-12/schema",
"$id":"{VOCAB}schema.json",
"title":"IronCrypto algorithm registry",
"type":"object",
"required":["version","algorithms"],
"properties":{{
 "version":{{"type":"string"}},
 "vocabulary":{{"type":"string","format":"uri"}},
 "algorithms":{{"type":"array","items":{{"$ref":"#/$defs/algorithm"}}}}
}},
"$defs":{{
 "algorithm":{{
  "type":"object",
  "required":["id","name","class","purposes","fipsStatus","implementationStatus","strength"],
  "properties":{{
   "id":{{"type":"string","pattern":"^[a-z0-9][a-z0-9._-]*$"}},
   "name":{{"type":"string"}},
   "summary":{{"type":"string"}},
   "class":{{"enum":{classes}}},
   "family":{{"type":"string"}},
   "purposes":{{"type":"array","items":{{"enum":{purposes}}},"minItems":1}},
   "strength":{{"type":"object","required":["classicalBits","quantumBits"],
     "properties":{{"classicalBits":{{"type":"integer","minimum":0}},
                   "quantumBits":{{"type":"integer","minimum":0}}}}}},
   "fipsStatus":{{"enum":{fips_statuses}}},
   "implementationStatus":{{"enum":{impl_statuses}}},
   "approvedModeUsable":{{"type":"boolean"}},
   "performance":{{"enum":{performances}}},
   "aliases":{{"type":"array","items":{{"type":"string"}}}},
   "standards":{{"type":"array","items":{{"type":"string"}}}},
   "parameters":{{"type":"array","items":{{"$ref":"#/$defs/parameter"}}}},
   "constraints":{{"type":"array","items":{{"$ref":"#/$defs/constraint"}}}},
   "relations":{{"type":"array","items":{{"$ref":"#/$defs/relation"}}}},
   "rustPath":{{"type":"string"}},
   "example":{{"type":"string"}},
   "notes":{{"type":"string"}}
  }}
 }},
 "parameter":{{"type":"object","required":["name","unit","min","max"],
  "properties":{{"name":{{"type":"string"}},"unit":{{"enum":{units}}},
   "min":{{"type":"integer"}},"max":{{"type":"integer"}},
   "recommended":{{"type":"integer"}},"note":{{"type":"string"}}}}}},
 "constraint":{{"type":"object","required":["id","severity","requirement","consequence"],
  "properties":{{"id":{{"type":"string"}},
   "severity":{{"enum":{severities}}},
   "requirement":{{"type":"string"}},"consequence":{{"type":"string"}}}}}},
 "relation":{{"type":"object","required":["relation","target"],
  "properties":{{"relation":{{"enum":{relations}}},
   "target":{{"type":"string"}}}}}}
}}}}"##
    )
}

/// A human-readable Markdown table of the registry.
pub fn to_markdown() -> String {
    let mut out = String::from("# IronCrypto algorithm registry\n\n");
    out.push_str("| ID | Class | Strength (classical/quantum) | FIPS | Status | Rust path |\n");
    out.push_str("|---|---|---|---|---|---|\n");
    for e in REGISTRY {
        out.push_str(&format!(
            "| `{}` | {} | {}/{} | {} | {} | {} |\n",
            e.id,
            e.class.id(),
            e.strength.classical,
            e.strength.quantum,
            e.fips.id(),
            e.status.id(),
            if e.rust_path.is_empty() {
                "—".to_string()
            } else {
                format!("`{}`", e.rust_path)
            }
        ));
    }
    out
}

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

    /// A minimal structural JSON check: balanced braces and brackets outside of
    /// strings, and no unescaped control characters inside them.
    fn json_is_well_formed(s: &str) -> bool {
        let mut depth_obj = 0i32;
        let mut depth_arr = 0i32;
        let mut in_string = false;
        let mut escaped = false;
        for c in s.chars() {
            if in_string {
                if escaped {
                    escaped = false;
                } else if c == '\\' {
                    escaped = true;
                } else if c == '"' {
                    in_string = false;
                } else if (c as u32) < 0x20 {
                    return false;
                }
                continue;
            }
            match c {
                '"' => in_string = true,
                '{' => depth_obj += 1,
                '}' => depth_obj -= 1,
                '[' => depth_arr += 1,
                ']' => depth_arr -= 1,
                _ => {}
            }
            if depth_obj < 0 || depth_arr < 0 {
                return false;
            }
        }
        !in_string && depth_obj == 0 && depth_arr == 0
    }

    #[test]
    fn json_export_is_well_formed() {
        let json = to_json();
        assert!(json_is_well_formed(&json), "malformed JSON");
        assert!(json.contains(r#""id":"aes-256-gcm""#));
        assert!(json.contains(r#""fipsStatus":"approved""#));
    }

    #[test]
    fn json_ld_export_is_well_formed_and_typed() {
        let jsonld = to_json_ld();
        assert!(json_is_well_formed(&jsonld), "malformed JSON-LD");
        assert!(jsonld.contains("\"@context\""));
        assert!(jsonld.contains("\"@type\":\"Algorithm\""));
        assert!(jsonld.contains(VOCAB));
    }

    #[test]
    fn json_schema_is_well_formed() {
        let schema = to_json_schema();
        assert!(json_is_well_formed(&schema), "malformed JSON Schema");
        assert!(schema.contains("\"$defs\""));
        assert!(schema.contains("aead"));
    }

    #[test]
    fn schema_enumerates_every_vocabulary_term() {
        let schema = to_json_schema();
        for c in Class::ALL {
            assert!(schema.contains(c.id()), "schema omits class {}", c.id());
        }
        for p in Purpose::ALL {
            assert!(schema.contains(p.id()), "schema omits purpose {}", p.id());
        }
    }

    #[test]
    fn turtle_export_declares_every_entry() {
        let ttl = to_turtle();
        assert!(ttl.starts_with("@prefix ac:"));
        for e in REGISTRY {
            // Built from `e.id` directly, not from whatever the exporter did to
            // it. The previous version of this test called `term(e.id)`, so it
            // reproduced the exporter's renaming and agreed with it.
            assert!(
                ttl.contains(&format!("\nac:{} a ac:", e.id)),
                "turtle omits {} (or names it something else)",
                e.id
            );
        }
        // Every statement block must terminate.
        assert!(ttl.matches(" .\n").count() + ttl.matches(".\n\n").count() > 0);
    }

    /// The Turtle and JSON-LD exports must give an entry the same IRI.
    ///
    /// They are two serializations of one registry, and the point of emitting
    /// both is that a consumer can load either, or both, and get one graph. For
    /// a while they agreed on nothing: Turtle named SHA-256 `ac:sha2256`,
    /// having dropped the hyphens from `sha2-256`, while JSON-LD left `sha2-256`
    /// to resolve against a base IRI the document never declared -- so its
    /// identity depended on where the file was fetched from.
    ///
    /// Each side is resolved here the way its own specification says to, from
    /// the registry identifier, and the two are required to meet.
    #[test]
    fn the_two_rdf_exports_agree_on_every_iri() {
        let ttl = to_turtle();
        let jsonld = to_json_ld();

        // Turtle: `ac:` is bound to VOCAB by the @prefix directive, so the
        // subject `ac:<local>` denotes VOCAB + local.
        let prefix_line = format!("@prefix ac: <{VOCAB}> .");
        assert!(
            ttl.starts_with(&prefix_line),
            "the ac: prefix is not bound to the vocabulary"
        );

        // JSON-LD: `id` is aliased to `@id`, and an `@id` resolves against
        // `@base`, which must therefore be the vocabulary for the two to meet.
        assert!(
            jsonld.contains(&format!(r#""@base":"{VOCAB}""#)),
            "the JSON-LD declares no base, so entry IRIs depend on where the \
             document was fetched from"
        );
        assert!(
            jsonld.contains(r#""id":"@id""#),
            "the JSON-LD no longer aliases id to @id"
        );

        // The JSON-LD is one document; an assertion that some target appears
        // somewhere in it would pass for an edge attached to the wrong entry.
        // Split it into node objects so each entry is checked against its own.
        let nodes: Vec<&str> = jsonld.split(r#"{"@type":"Algorithm","#).skip(1).collect();
        assert_eq!(
            nodes.len(),
            REGISTRY.len(),
            "the JSON-LD does not have one node per entry"
        );

        let mut checked = 0;
        for e in REGISTRY {
            let iri = format!("{VOCAB}{}", e.id);
            let node = nodes
                .iter()
                .find(|n| n.starts_with(&format!(r#""id":"{}","#, e.id)))
                .unwrap_or_else(|| panic!("the JSON-LD has no node for {}", e.id));

            // Turtle states it as a subject.
            assert!(
                ttl.contains(&format!("\nac:{} a ac:", e.id)),
                "turtle does not name {} as {iri}",
                e.id
            );
            // JSON-LD states it as the entry's id, which resolves to the same.
            assert!(
                node.starts_with(&format!(r#""id":"{}","#, e.id)),
                "the JSON-LD does not name {} as {iri}",
                e.id
            );

            // And both must state the same edge: same predicate, same object.
            // The two write it differently -- Turtle as a predicate, JSON-LD as
            // a property whose values are node references -- but they expand to
            // the same triple, which is the whole reason for emitting both.
            for edge in e.edges {
                let predicate = term(edge.relation.id());
                assert!(
                    ttl.contains(&format!("ac:{predicate} ac:{}", edge.target)),
                    "turtle does not state {} --{predicate}-> {}",
                    e.id,
                    edge.target
                );
                let property = format!(r#""{predicate}":["#);
                let values = node
                    .split_once(property.as_str())
                    .and_then(|(_, rest)| rest.split_once(']'))
                    .map(|(values, _)| values)
                    .unwrap_or_else(|| panic!("the JSON-LD node for {} has no {predicate}", e.id));
                assert!(
                    values
                        .split(',')
                        .any(|v| v.trim_matches('"') == edge.target),
                    "the JSON-LD does not state {} --{predicate}-> {}",
                    e.id,
                    edge.target
                );
                checked += 1;
            }
            checked += 1;
        }

        // A floor, so an empty registry or an export that stopped emitting
        // entries fails here rather than passing quietly.
        assert!(
            checked > 100,
            "only {checked} identifiers compared across the two exports"
        );
    }

    #[test]
    fn identifiers_survive_both_serializations_intact() {
        // `term` camel-cases, which is what a vocabulary term wants.
        assert_eq!(term("block-cipher"), "blockCipher");
        assert_eq!(term("allowed-as-component"), "allowedAsComponent");
        assert_eq!(term("hash"), "hash");

        // An identifier is left alone, because its segments are usually digits
        // and camel-casing them just deletes the separator: `sha2-256` became
        // `sha2256`, and nothing can turn that back.
        assert_eq!(local_name("sha2-256"), "sha2-256");
        assert_eq!(local_name("aes-256-gcm"), "aes-256-gcm");
        assert_eq!(local_name("3des"), "3des");

        for e in REGISTRY {
            // Turtle's PN_LOCAL, restricted to the characters these use: a
            // leading alphanumeric, then alphanumerics and `_-.`, not ending in
            // a dot. Wider than the previous rule, which allowed neither `-`
            // nor `.` and so forced the renaming.
            let mut chars = e.id.chars();
            assert!(
                chars
                    .next()
                    .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'),
                "{} cannot start a Turtle local name",
                e.id
            );
            assert!(
                e.id.chars()
                    .all(|c| c.is_ascii_alphanumeric() || "_-.".contains(c)),
                "{} contains a character Turtle would need escaped",
                e.id
            );
            assert!(!e.id.ends_with('.'), "{} ends in a dot", e.id);
        }
    }

    #[test]
    fn escaping_handles_the_characters_that_break_json() {
        assert_eq!(escape_json(r#"a"b"#), r#"a\"b"#);
        assert_eq!(escape_json("a\\b"), "a\\\\b");
        assert_eq!(escape_json("a\nb"), "a\\nb");
        assert_eq!(escape_json("a\tb"), "a\\tb");
        assert_eq!(escape_json("a\u{1}b"), "a\\u0001b");
        assert_eq!(escape_json("plain"), "plain");
    }

    /// Entries contain newlines in their examples; the export must survive them.
    #[test]
    fn multiline_examples_do_not_break_the_json() {
        let e = crate::query::get("aes-256-gcm").unwrap();
        assert!(e.example.contains('\n'), "test needs a multi-line example");
        let json = entry_to_json(e);
        assert!(json_is_well_formed(&json));
        assert!(!json.contains("\n"), "raw newline leaked into JSON");
    }

    #[test]
    fn markdown_lists_every_entry() {
        let md = to_markdown();
        for e in REGISTRY {
            assert!(md.contains(e.id), "markdown omits {}", e.id);
        }
    }
}