Skip to main content

meta_language/
global_concept_space.rs

1//! Host representation of the common concept space. Proof decisions use the
2//! verifier translated automatically from the JavaScript implementation.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt::Write as _;
6use std::sync::OnceLock;
7
8use serde_json::{Map, Value, json};
9use sha2::{Digest, Sha256};
10
11use crate::global_concept_identity_rules::{
12    accept_global_concept_history, select_global_concept_identity,
13};
14use crate::global_concept_rules::verify_global_concept_correspondence;
15
16use crate::formal_concept_definition::read_formal_concept_definition;
17use crate::grammar::feature::{
18    check_grammar_selection_included_range_data, check_grammar_selection_included_range_grammar,
19};
20use crate::grammar::interchange::{deserialize_grammar, serialize_grammar};
21use crate::grammar::{Grammar, GrammarFormat, GrammarSourceName};
22use crate::link_network::LinkNetwork;
23use crate::translation::grammar_selection_rules::read_grammar_source_default_matching;
24
25mod links;
26mod parser;
27pub use links::{global_concept_space_to_links, read_global_concept_space_links};
28pub use parser::{GlobalConceptSpaceParser, create_global_concept_space_parser};
29
30/// The closed recursive proof required before sharing a concept identity.
31pub const GLOBAL_CONCEPT_PROOF_METHOD: &str = "recursive-structural-bijection";
32
33/// One imported grammar and its qualified origin.
34#[derive(Clone, Debug)]
35pub struct GlobalConceptSource {
36    /// Stable imported source identity.
37    pub id: String,
38    /// Language of the source.
39    pub language: String,
40    /// Edition, or empty text when unspecified.
41    pub edition: String,
42    /// Complete imported grammar.
43    pub grammar: Grammar,
44}
45
46impl GlobalConceptSource {
47    /// Reads an imported source, retaining concept and source-name metadata.
48    ///
49    /// # Errors
50    /// Returns a validation error for invalid source or grammar data.
51    pub fn from_json(value: &Value) -> Result<Self, String> {
52        require_global_grammar_source_format(value["grammar"].get("sourceFormat"))?;
53        let decoded = deserialize_grammar(&value["grammar"].to_string())
54            .map_err(|error| error.to_string())?;
55        let mut grammar = Grammar::new();
56        if let Some(start) = decoded.start() {
57            grammar.set_start(start);
58        }
59        if let Some(format) = decoded.source_format() {
60            grammar.set_source_format(format);
61        }
62        grammar.set_declarations(decoded.declarations().clone());
63        grammar.set_kinds(decoded.kinds().to_vec());
64        let metadata = array(&value["grammar"]["rules"])?;
65        let rules = decoded.rules().to_vec();
66        for mut rule in rules {
67            let definition = metadata
68                .iter()
69                .find(|entry| entry["name"] == rule.name)
70                .ok_or_else(|| "missing source rule metadata".to_owned())?;
71            rule.concept = definition
72                .get("concept")
73                .and_then(Value::as_str)
74                .map(str::to_owned);
75            rule.source_names = definition
76                .get("sourceNames")
77                .map(array)
78                .transpose()?
79                .unwrap_or_default()
80                .iter()
81                .map(|alias| {
82                    Ok(GrammarSourceName {
83                        source: string(&alias["source"])?.to_owned(),
84                        name: string(&alias["name"])?.to_owned(),
85                    })
86                })
87                .collect::<Result<_, String>>()?;
88            grammar.add_rule(rule);
89        }
90        Ok(Self {
91            id: string(&value["id"])?.to_owned(),
92            language: string(&value["language"])?.to_owned(),
93            edition: value
94                .get("edition")
95                .map(string)
96                .transpose()?
97                .unwrap_or("")
98                .to_owned(),
99            grammar,
100        })
101    }
102}
103
104/// Grounded meanings, incremental identities and required sharing obligations.
105#[derive(Clone, Debug, Default)]
106pub struct GlobalConceptOptions {
107    /// Canonical semantic records; absent uses the shipped register.
108    pub records: Option<Value>,
109    /// Explicit supported operational definitions, by origin alias or record id.
110    pub formal_definitions: Option<Value>,
111    /// Previous concept space whose surviving identities remain stable.
112    pub previous: Option<Value>,
113    /// Qualified origin pairs that require a proven shared identity.
114    pub equivalences: Vec<[String; 2]>,
115}
116
117fn string(value: &Value) -> Result<&str, String> {
118    value
119        .as_str()
120        .ok_or_else(|| "expected text in global concept data".to_owned())
121}
122
123fn array(value: &Value) -> Result<&[Value], String> {
124    value
125        .as_array()
126        .map(Vec::as_slice)
127        .ok_or_else(|| "expected an array in global concept data".to_owned())
128}
129
130fn require_global_grammar_source_format(value: Option<&Value>) -> Result<(), String> {
131    value
132        .filter(|value| !value.is_null())
133        .map(|value| {
134            let format = value
135                .as_str()
136                .ok_or("a global grammar source format must be known text")?;
137            GrammarFormat::from_tag(format)
138                .ok_or_else(|| format!("unknown grammar source format {format}"))
139        })
140        .transpose()
141        .map(|_| ())
142}
143
144fn canonical(value: &Value) -> String {
145    match value {
146        Value::Array(values) => format!(
147            "[{}]",
148            values.iter().map(canonical).collect::<Vec<_>>().join(",")
149        ),
150        Value::Object(values) => {
151            let ordered: BTreeMap<_, _> = values.iter().collect();
152            format!(
153                "{{{}}}",
154                ordered
155                    .iter()
156                    .map(|(key, value)| format!("{}:{}", json!(key), canonical(value)))
157                    .collect::<Vec<_>>()
158                    .join(",")
159            )
160        }
161        _ => value.to_string(),
162    }
163}
164
165fn declarations(value: Option<&Value>) -> Value {
166    let mut context = json!({"matching":null,"settling":null,"imports":[],"modes":[],"extras":[],"conflicts":[],"precedences":[],"macros":[],"scanners":[]});
167    if let Some(Value::Object(entries)) = value {
168        for (key, value) in entries {
169            let lexical_context =
170                key == "lexers" && value.as_array().is_some_and(|entries| !entries.is_empty());
171            if (context.get(key).is_some() || lexical_context) && !value.is_null() {
172                context[key] = value.clone();
173            }
174        }
175    }
176    context
177}
178
179fn production(rule: &Value) -> Value {
180    let mut result = json!({"kind":rule["kind"],"expression":rule["expression"]});
181    for key in ["parameters", "channel", "modes", "action"] {
182        if let Some(value) = rule.get(key) {
183            result[key] = value.clone();
184        }
185    }
186    result
187}
188
189struct Node {
190    source: usize,
191    origin: Value,
192    definition: Value,
193    meaning: String,
194}
195
196struct Graph {
197    shapes: Vec<String>,
198    meanings: Vec<String>,
199    offsets: Vec<usize>,
200    edges: Vec<usize>,
201}
202
203fn shape(
204    value: &Value,
205    source: &str,
206    aliases: &BTreeMap<String, usize>,
207    edges: &mut Vec<usize>,
208) -> Value {
209    match value {
210        Value::Array(values) => Value::Array(
211            values
212                .iter()
213                .map(|value| shape(value, source, aliases, edges))
214                .collect(),
215        ),
216        Value::Object(values) => {
217            let mut shaped = Map::new();
218            let ordered: BTreeMap<_, _> = values.iter().collect();
219            for (key, entry) in ordered {
220                let value = if value["kind"] == "ref" && key == "name" && entry.is_string() {
221                    let target =
222                        aliases.get(&format!("{source}:{}", entry.as_str().unwrap_or_default()));
223                    target.map_or_else(
224                        || json!({"unresolved":source,"name":entry}),
225                        |target| {
226                            let index = edges.len();
227                            edges.push(*target);
228                            json!({"reference":index})
229                        },
230                    )
231                } else {
232                    shape(entry, source, aliases, edges)
233                };
234                shaped.insert(key.clone(), value);
235            }
236            Value::Object(shaped)
237        }
238        _ => value.clone(),
239    }
240}
241
242fn correspondence(graph: &Graph, first: usize, second: usize) -> Option<Vec<(usize, usize)>> {
243    let mut pending = vec![(first, second)];
244    let mut witness = Vec::new();
245    let mut left_map = BTreeMap::new();
246    let mut right_map = BTreeMap::new();
247    let mut at = 0;
248    while at < pending.len() {
249        let (left, right) = pending[at];
250        at += 1;
251        if left_map.contains_key(&left) || right_map.contains_key(&right) {
252            if left_map.get(&left) != Some(&right) || right_map.get(&right) != Some(&left) {
253                return None;
254            }
255            continue;
256        }
257        if graph.shapes[left] != graph.shapes[right]
258            || graph.meanings[left] != graph.meanings[right]
259        {
260            return None;
261        }
262        left_map.insert(left, right);
263        right_map.insert(right, left);
264        witness.push((left, right));
265        let count = graph.offsets[left + 1] - graph.offsets[left];
266        if count != graph.offsets[right + 1] - graph.offsets[right] {
267            return None;
268        }
269        for edge in 0..count {
270            pending.push((
271                graph.edges[graph.offsets[left] + edge],
272                graph.edges[graph.offsets[right] + edge],
273            ));
274        }
275    }
276    let number = |index: usize| serde_json::Number::from(index).as_f64().unwrap();
277    let to_numbers = |values: &[usize]| values.iter().map(|index| number(*index)).collect();
278    let verified = verify_global_concept_correspondence(
279        graph.shapes.clone(),
280        graph.meanings.clone(),
281        to_numbers(&graph.offsets),
282        to_numbers(&graph.edges),
283        witness.iter().map(|(left, _)| number(*left)).collect(),
284        witness.iter().map(|(_, right)| number(*right)).collect(),
285    );
286    verified.then_some(witness)
287}
288
289const fn representative(parents: &[usize], mut index: usize) -> usize {
290    while parents[index] != index {
291        index = parents[index];
292    }
293    index
294}
295
296/// Copies every source rule, then shares identities only after a closed proof.
297///
298/// # Errors
299/// Returns a validation error for malformed or colliding source identities.
300pub fn create_global_concept_space(
301    sources: &[GlobalConceptSource],
302    options: &GlobalConceptOptions,
303) -> Result<Value, String> {
304    let mut source_values = Vec::new();
305    for source in sources {
306        check_grammar_selection_included_range_grammar(&source.grammar)?;
307        let mut grammar: Value = serde_json::from_str(&serialize_grammar(&source.grammar))
308            .map_err(|error| error.to_string())?;
309        for (definition, rule) in grammar["rules"]
310            .as_array_mut()
311            .ok_or("missing grammar rules")?
312            .iter_mut()
313            .zip(source.grammar.rules())
314        {
315            if let Some(concept) = &rule.concept {
316                definition["concept"] = json!(concept);
317            }
318            definition["sourceNames"] = json!(
319                rule.source_names
320                    .iter()
321                    .map(|name| json!({"source":name.source,"name":name.name}))
322                    .collect::<Vec<_>>()
323            );
324        }
325        source_values.push(json!({"id":source.id,"language":source.language,"edition":source.edition,"grammar":grammar}));
326    }
327    create_global_concept_space_in(&source_values, options).map(|(space, _, _)| space)
328}
329
330/// Resolves a construct through its proven identity and preserves alternatives.
331/// Language aliases use the same catalog as ordinary public language parsing.
332#[must_use]
333pub fn translate_global_construct(
334    space: &Value,
335    alias: &str,
336    language: &str,
337    edition: Option<&str>,
338) -> Value {
339    let empty = |relation| json!({"relation":relation,"concept":null,"origins":[],"proofs":[]});
340    if space["ambiguities"]
341        .as_array()
342        .is_some_and(|entries| entries.iter().any(|entry| entry["alias"] == alias))
343    {
344        return empty("ambiguous");
345    }
346    let id = &space["mappings"][alias];
347    let Some(concept) = space["concepts"]
348        .as_array()
349        .and_then(|concepts| concepts.iter().find(|concept| concept["id"] == *id))
350    else {
351        return empty("unknown");
352    };
353    let canonical_language = |language: &str| {
354        crate::language_catalog::language_entry(language)
355            .map_or_else(|| language.to_owned(), |entry| entry.name.clone())
356    };
357    let target = canonical_language(language);
358    let origins: Vec<_> = concept["origins"]
359        .as_array()
360        .into_iter()
361        .flatten()
362        .filter(|origin| {
363            origin["language"]
364                .as_str()
365                .is_some_and(|language| canonical_language(language) == target)
366                && edition.is_none_or(|edition| origin["edition"] == edition)
367        })
368        .cloned()
369        .collect();
370    let relation = match origins.len() {
371        0 => "untranslatable",
372        1 => "translated",
373        _ => "ambiguous",
374    };
375    json!({"relation":relation,"concept":id,"origins":origins,"proofs":concept["proofs"]})
376}
377
378#[derive(Default)]
379struct ConceptRecordIndex {
380    identities: Vec<String>,
381    records_by_alias: BTreeMap<(String, String), Vec<usize>>,
382    records_by_id: BTreeMap<String, usize>,
383    formal_definitions: BTreeMap<usize, Value>,
384}
385
386fn index_concept_records(records: &[Value]) -> Result<ConceptRecordIndex, String> {
387    let mut index = ConceptRecordIndex {
388        identities: Vec::with_capacity(records.len()),
389        ..ConceptRecordIndex::default()
390    };
391    for (position, record) in records.iter().enumerate() {
392        let identity = string(&record["id"])?;
393        index.identities.push(identity.to_owned());
394        index
395            .records_by_id
396            .entry(identity.to_owned())
397            .or_insert(position);
398        for alias in array(&record["sourceAliases"])? {
399            index
400                .records_by_alias
401                .entry((
402                    string(&alias["source"])?.to_owned(),
403                    string(&alias["name"])?.to_owned(),
404                ))
405                .or_default()
406                .push(position);
407        }
408        if let Some(definition) = record.get("formalDefinition") {
409            index
410                .formal_definitions
411                .insert(position, definition.clone());
412        }
413    }
414    Ok(index)
415}
416
417fn shipped_concept_record_index() -> Result<&'static ConceptRecordIndex, String> {
418    static INDEX: OnceLock<Result<ConceptRecordIndex, String>> = OnceLock::new();
419    INDEX
420        .get_or_init(|| {
421            // Keep the lookup index and release the decoded register after indexing.
422            let records = crate::structured_data_links::read_structured_data_lino(include_str!(
423                "data/concept-records.lino"
424            ))?;
425            index_concept_records(array(&records["concepts"])?)
426        })
427        .as_ref()
428        .map_err(Clone::clone)
429}
430
431// JSON/grammar adaptation is host glue. The generated verifier is the sole
432// authority that accepts a correspondence and permits shared identities.
433fn create_global_concept_space_in(
434    sources: &[Value],
435    options: &GlobalConceptOptions,
436) -> Result<(Value, Graph, BTreeMap<String, usize>), String> {
437    for source in sources {
438        check_grammar_selection_included_range_data(&source["grammar"])?;
439    }
440    let custom_index;
441    let records = if let Some(records) = options.records.as_ref() {
442        custom_index = index_concept_records(array(records)?)?;
443        &custom_index
444    } else {
445        shipped_concept_record_index()?
446    };
447    let catalog: Value = crate::structured_data_links::read_structured_data_lino(include_str!(
448        "data/language-catalog.lino"
449    ))?;
450    let mut ordered = sources.to_vec();
451    ordered.sort_by(|first, second| {
452        first["id"]
453            .as_str()
454            .unwrap_or_default()
455            .cmp(second["id"].as_str().unwrap_or_default())
456    });
457    let mut source_ids = BTreeSet::new();
458    let mut aliases = BTreeMap::new();
459    let mut nodes = Vec::new();
460    let mut ambiguities = Vec::new();
461    let mut formal = Map::new();
462    let mut contexts = Vec::new();
463    for (source_index, source) in ordered.iter().enumerate() {
464        let id = string(&source["id"])?;
465        let language = string(&source["language"])?;
466        let edition = string(&source["edition"])?;
467        if id.is_empty() || language.is_empty() {
468            return Err(
469                "a global concept source needs an identity, language, edition and imported grammar"
470                    .to_owned(),
471            );
472        }
473        require_global_grammar_source_format(source["grammar"].get("sourceFormat"))?;
474        if !source_ids.insert(id.to_owned()) {
475            return Err(format!("duplicate global concept source {id}"));
476        }
477        let mut rules = array(&source["grammar"]["rules"])?.to_vec();
478        rules.sort_by(|first, second| {
479            first["name"]
480                .as_str()
481                .unwrap_or_default()
482                .cmp(second["name"].as_str().unwrap_or_default())
483        });
484        contexts.push(declarations(source["grammar"].get("declarations")));
485        let mut native_sources = BTreeSet::from([format!("native:{language}")]);
486        if let Some(entry) = crate::language_catalog::language_entry(language) {
487            for grammar in &entry.grammars {
488                if let Some(file) = catalog["nativeGrammars"][&grammar.id]["file"].as_str() {
489                    let basename = file.rsplit('/').next().unwrap_or(file);
490                    native_sources.insert(format!(
491                        "native:{}",
492                        basename.strip_suffix(".lino").unwrap_or(basename)
493                    ));
494                }
495            }
496        }
497        for rule in rules {
498            let name = string(&rule["name"])?;
499            let alias = format!("{id}:{name}");
500            if aliases.contains_key(&alias) {
501                return Err(format!("colliding global concept origin {alias}"));
502            }
503            let mut source_names = rule
504                .get("sourceNames")
505                .map(array)
506                .transpose()?
507                .unwrap_or_default()
508                .to_vec();
509            source_names.sort_by(|first, second| {
510                (
511                    first["source"].as_str().unwrap_or_default(),
512                    first["name"].as_str().unwrap_or_default(),
513                )
514                    .cmp(&(
515                        second["source"].as_str().unwrap_or_default(),
516                        second["name"].as_str().unwrap_or_default(),
517                    ))
518            });
519            let origin = json!({"alias":alias,"source":id,"language":language,"edition":edition,"rule":name,"concept":rule.get("concept").unwrap_or(&Value::Null),"sourceNames":source_names});
520            let mut spellings = vec![json!({"source":id,"name":name})];
521            spellings.extend(
522                native_sources
523                    .iter()
524                    .map(|source| json!({"source":source,"name":name})),
525            );
526            spellings.extend(source_names);
527            let mut matching_records = BTreeSet::new();
528            for spelling in spellings {
529                let key = (
530                    string(&spelling["source"])?.to_owned(),
531                    string(&spelling["name"])?.to_owned(),
532                );
533                if let Some(indices) = records.records_by_alias.get(&key) {
534                    matching_records.extend(indices.iter().copied());
535                }
536            }
537            let mut meanings: Vec<_> = matching_records
538                .iter()
539                .map(|index| Value::String(records.identities[*index].clone()))
540                .collect();
541            if let Some(concept) = rule.get("concept")
542                && !meanings.contains(concept)
543            {
544                meanings.push(concept.clone());
545            }
546            meanings.sort_by(|first, second| {
547                first
548                    .as_str()
549                    .unwrap_or_default()
550                    .cmp(second.as_str().unwrap_or_default())
551            });
552            if meanings.len() > 1 {
553                ambiguities.push(json!({"alias":alias,"meanings":meanings}));
554            }
555            let record = if meanings.len() == 1 {
556                records.records_by_id.get(string(&meanings[0])?)
557            } else {
558                None
559            };
560            // Catalog identifiers and prose nominate candidates, never proofs.
561            // Only a supported, checked operational graph grounds a meaning.
562            let declared = options
563                .formal_definitions
564                .as_ref()
565                .and_then(|definitions| definitions.get(&alias))
566                .filter(|definition| !definition.is_null())
567                .or_else(|| {
568                    record.and_then(|position| {
569                        options
570                            .formal_definitions
571                            .as_ref()
572                            .and_then(|definitions| {
573                                definitions.get(records.identities[*position].as_str())
574                            })
575                            .filter(|definition| !definition.is_null())
576                            .or_else(|| records.formal_definitions.get(position))
577                    })
578                });
579            let mut meaning = format!("unproved:{}", canonical(&origin));
580            if meanings.len() <= 1
581                && let Some(declared) = declared
582                && let Ok(prepared) = read_formal_concept_definition(declared)
583                && let Some(links) = declared["links"].as_str()
584                && let Ok(network) = LinkNetwork::from_lino(links)
585                && let Some(root) = declared["root"].as_u64()
586            {
587                meaning = canonical(&prepared);
588                formal.insert(
589                    alias.clone(),
590                    json!({"links":network.to_lino(),"root":root}),
591                );
592            }
593            aliases.insert(alias, nodes.len());
594            nodes.push(Node {
595                source: source_index,
596                origin,
597                definition: production(&rule),
598                meaning,
599            });
600        }
601    }
602    let mut graph = Graph {
603        shapes: Vec::new(),
604        meanings: Vec::new(),
605        offsets: vec![0],
606        edges: Vec::new(),
607    };
608    for node in &nodes {
609        let source = string(&ordered[node.source]["id"])?;
610        let mut context = contexts[node.source].clone();
611        if context["matching"].is_null() {
612            context["matching"] = json!(read_grammar_source_default_matching(
613                ordered[node.source]["grammar"]["sourceFormat"]
614                    .as_str()
615                    .unwrap_or_default()
616            ));
617        }
618        if context["settling"].is_null() {
619            context["settling"] = match context["matching"].as_str() {
620                Some("peg") => json!(["first"]),
621                Some("longest") => json!(["tokens", "precedence", "dynamic", "ambiguity"]),
622                _ => json!(["dynamic", "ambiguity"]),
623            };
624        }
625        let mut targets = Vec::new();
626        let definition = shape(&node.definition, source, &aliases, &mut targets);
627        let context = shape(&context, source, &aliases, &mut targets);
628        graph.shapes.push(canonical(
629            &json!({"definition":definition,"context":context}),
630        ));
631        graph.meanings.push(node.meaning.clone());
632        graph.edges.extend(targets);
633        graph.offsets.push(graph.edges.len());
634    }
635    let mut parents: Vec<_> = (0..nodes.len()).collect();
636    let mut buckets: Vec<Vec<usize>> = Vec::new();
637    let mut bucket_keys = BTreeMap::new();
638    for index in 0..nodes.len() {
639        let key = canonical(&json!([graph.shapes[index], graph.meanings[index]]));
640        let next = buckets.len();
641        let bucket = *bucket_keys.entry(key).or_insert(next);
642        if bucket == buckets.len() {
643            buckets.push(Vec::new());
644        }
645        buckets[bucket].push(index);
646    }
647    let mut proofs = Vec::new();
648    for bucket in buckets {
649        for (at, first) in bucket.iter().enumerate() {
650            for second in bucket.iter().skip(at + 1) {
651                if representative(&parents, *first) == representative(&parents, *second) {
652                    continue;
653                }
654                if let Some(witness) = correspondence(&graph, *first, *second) {
655                    proofs.push(json!({"method":GLOBAL_CONCEPT_PROOF_METHOD,"first":nodes[*first].origin["alias"],"second":nodes[*second].origin["alias"],"correspondence":witness.iter().map(|(left,right)| json!([nodes[*left].origin["alias"],nodes[*right].origin["alias"]])).collect::<Vec<_>>()}));
656                    for (left, right) in witness {
657                        let one = representative(&parents, left);
658                        let other = representative(&parents, right);
659                        parents[one.max(other)] = one.min(other);
660                    }
661                }
662            }
663        }
664    }
665    let mut classes: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
666    for index in 0..nodes.len() {
667        classes
668            .entry(representative(&parents, index))
669            .or_default()
670            .push(index);
671    }
672    let previous = options
673        .previous
674        .as_ref()
675        .and_then(|previous| previous.get("concepts"))
676        .filter(|concepts| !concepts.is_null())
677        .map(array)
678        .transpose()
679        .map_err(|_| "invalid global concept history".to_owned())?
680        .unwrap_or_default();
681    let reserved = previous
682        .iter()
683        .map(|concept| string(&concept["id"]).map(str::to_owned))
684        .collect::<Result<Vec<_>, _>>()
685        .map_err(|_| "invalid global concept history".to_owned())?;
686    let mut previous_aliases = Vec::new();
687    for concept in previous {
688        for origin in
689            array(&concept["origins"]).map_err(|_| "invalid global concept history".to_owned())?
690        {
691            previous_aliases.push(
692                string(&origin["alias"])
693                    .map_err(|_| "invalid global concept history".to_owned())?
694                    .to_owned(),
695            );
696        }
697    }
698    let unique_identities = reserved.iter().collect::<BTreeSet<_>>().len();
699    let unique_aliases = previous_aliases.iter().collect::<BTreeSet<_>>().len();
700    if !accept_global_concept_history(
701        &reserved,
702        &previous_aliases,
703        serde_json::Number::from(unique_identities)
704            .as_f64()
705            .unwrap(),
706        serde_json::Number::from(unique_aliases).as_f64().unwrap(),
707    ) {
708        return Err("invalid global concept history".to_owned());
709    }
710    let mut assigned = Vec::new();
711    let mut concepts = Vec::new();
712    let mut mappings = Map::new();
713    let mut redirects = Map::new();
714    for indices in classes.values() {
715        let origins: Vec<_> = indices
716            .iter()
717            .map(|index| nodes[*index].origin.clone())
718            .collect();
719        let present: BTreeSet<_> = origins
720            .iter()
721            .map(|origin| string(&origin["alias"]))
722            .collect::<Result<_, _>>()?;
723        let mut established = Vec::new();
724        for concept in previous {
725            let mut surviving: Vec<_> = array(&concept["origins"])?
726                .iter()
727                .map(|origin| string(&origin["alias"]))
728                .collect::<Result<Vec<_>, _>>()?
729                .into_iter()
730                .filter(|alias| aliases.contains_key(*alias))
731                .collect();
732            surviving.sort_unstable();
733            if surviving
734                .first()
735                .is_some_and(|alias| present.contains(alias))
736            {
737                established.push(string(&concept["id"])?.to_owned());
738            }
739        }
740        established.sort_unstable();
741        let fallback = {
742            let digest = Sha256::digest(canonical(&origins[0]).as_bytes())
743                .iter()
744                .fold(String::new(), |mut text, byte| {
745                    let _ = write!(text, "{byte:02x}");
746                    text
747                });
748            format!("global-concept.{digest}")
749        };
750        let id = select_global_concept_identity(
751            established.first().cloned().unwrap_or_default(),
752            fallback,
753            &reserved,
754            &assigned,
755        );
756        if id.is_empty() {
757            return Err("duplicate global concept identity".to_owned());
758        }
759        assigned.push(id.clone());
760        for old in established.iter().skip(1) {
761            redirects.insert(old.clone(), json!(id));
762        }
763        let proof_indices: Vec<_> = proofs
764            .iter()
765            .enumerate()
766            .filter_map(|(index, proof)| {
767                proof["correspondence"]
768                    .as_array()
769                    .is_some_and(|pairs| {
770                        pairs.iter().any(|pair| {
771                            present.contains(pair[0].as_str().unwrap_or_default())
772                                && present.contains(pair[1].as_str().unwrap_or_default())
773                        })
774                    })
775                    .then_some(index)
776            })
777            .collect();
778        let definitions: Vec<_> = indices.iter().map(|index| json!({"origin":nodes[*index].origin["alias"],"definition":nodes[*index].definition})).collect();
779        concepts.push(json!({"id":id,"origins":origins,"definition":definitions[0]["definition"],"definitions":definitions,"proofs":proof_indices}));
780        for origin in &origins {
781            mappings.insert(string(&origin["alias"])?.to_owned(), json!(id));
782        }
783    }
784    let mut failures = Vec::new();
785    for members in &options.equivalences {
786        let reason = if members.iter().any(|alias| !aliases.contains_key(alias)) {
787            Some("unknown-origin")
788        } else if mappings.get(&members[0]) != mappings.get(&members[1]) {
789            Some("no-one-to-one-proof")
790        } else {
791            None
792        };
793        if let Some(reason) = reason {
794            failures.push(json!({"members":members,"reason":reason}));
795        }
796    }
797    let sources: Vec<_> = ordered.iter().enumerate().map(|(index, source)| {
798        let mut origin = json!({"id":source["id"],"language":source["language"],"edition":source["edition"],"start":source["grammar"].get("start").unwrap_or(&Value::Null),"ruleOrder":source["grammar"]["rules"].as_array().map(|rules| rules.iter().map(|rule| rule["name"].clone()).collect::<Vec<_>>()).unwrap_or_default(),"context":contexts[index]});
799        if let Some(format) = source["grammar"].get("sourceFormat").filter(|format| !format.is_null()) {
800            origin["sourceFormat"] = format.clone();
801        }
802        origin
803    }).collect();
804    Ok((
805        json!({"schemaVersion":1,"sources":sources,"concepts":concepts,"mappings":mappings,"proofs":proofs,"failures":failures,"ambiguities":ambiguities,"redirects":redirects,"formalDefinitions":formal}),
806        graph,
807        aliases,
808    ))
809}