coreason-engine 0.1.0

Coreason execution engine for deterministic computation
Documentation
// Copyright (c) 2026 CoReason, Inc
//
// This software is proprietary and dual-licensed
// Licensed under the Prosperity Public License 3.0 (the "License")
// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
// For details, see the LICENSE file
// Commercial use beyond a 30-day trial requires a separate license
//
// Source Code: <https://github.com/CoReason-AI/coreason-runtime>

//! Generalized Non-Domain-Specific Ontological Vocabulary Solver.
//!
//! Exposes hierarchical concept traversal and Context-Free Grammar (CFG)
//! compilation to support zero-hallucination, logit-constrained decoding
//! across any domain vocabulary.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct OntologicalConcept {
    pub id: String,
    pub name: String,
    pub category: String,
}

use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::visit::Bfs;

/// A non-domain-specific vocabulary solver using directed graphs.
pub struct OntologicalVocabularySolver {
    pub concepts: HashMap<String, OntologicalConcept>,
    pub graph: DiGraph<String, ()>,
    pub node_indices: HashMap<String, NodeIndex>,
}

impl OntologicalVocabularySolver {
    /// Creates a new, empty vocabulary solver.
    pub fn new() -> Self {
        Self {
            concepts: HashMap::new(),
            graph: DiGraph::new(),
            node_indices: HashMap::new(),
        }
    }

    /// Registers a concept in the ontology vocabulary.
    pub fn register_concept(&mut self, concept: OntologicalConcept) {
        self.concepts.insert(concept.id.clone(), concept.clone());
        if !self.node_indices.contains_key(&concept.id) {
            let idx = self.graph.add_node(concept.id.clone());
            self.node_indices.insert(concept.id, idx);
        }
    }

    fn get_or_add_node(&mut self, id: &str) -> NodeIndex {
        if let Some(&idx) = self.node_indices.get(id) {
            idx
        } else {
            let idx = self.graph.add_node(id.to_string());
            self.node_indices.insert(id.to_string(), idx);
            idx
        }
    }

    /// Registers a parent-child relationship in the ontology graph.
    pub fn register_relationship(&mut self, parent_id: &str, child_id: &str) {
        let p_idx = self.get_or_add_node(parent_id);
        let c_idx = self.get_or_add_node(child_id);
        self.graph.add_edge(p_idx, c_idx, ());
    }

    /// Recursively traverses hierarchy to find all parent/ancestor concepts.
    pub fn find_ancestors(&self, concept_id: &str) -> Vec<OntologicalConcept> {
        let mut ancestors = Vec::new();
        if let Some(&start_idx) = self.node_indices.get(concept_id) {
            let mut bfs = Bfs::new(&self.graph, start_idx);
            // Reverse direction to traverse up to ancestors
            let reversed_graph = petgraph::visit::Reversed(&self.graph);
            while let Some(nx) = bfs.next(reversed_graph) {
                if nx != start_idx {
                    let id = &self.graph[nx];
                    if let Some(concept) = self.concepts.get(id) {
                        ancestors.push(concept.clone());
                    }
                }
            }
        }
        ancestors
    }

    /// Recursively traverses hierarchy to find all child/descendant concepts.
    pub fn find_descendants(&self, concept_id: &str) -> Vec<OntologicalConcept> {
        let mut descendants = Vec::new();
        if let Some(&start_idx) = self.node_indices.get(concept_id) {
            let mut bfs = Bfs::new(&self.graph, start_idx);
            while let Some(nx) = bfs.next(&self.graph) {
                if nx != start_idx {
                    let id = &self.graph[nx];
                    if let Some(concept) = self.concepts.get(id) {
                        descendants.push(concept.clone());
                    }
                }
            }
        }
        descendants
    }

    /// Compiles search candidates into a standard EBNF Context-Free Grammar (CFG)
    /// to constrain autoregressive LLM output to valid concept IDs.
    pub fn compile_cfg_constraint(&self, candidate_ids: &[String]) -> String {
        if candidate_ids.is_empty() {
            return "root ::= \"empty\"".to_string();
        }

        let mut alternatives = Vec::new();
        for id in candidate_ids {
            let escaped = id.replace('"', "\\\"");
            alternatives.push(format!("\"{}\"", escaped));
        }

        let rule = alternatives.join(" | ");
        format!("root ::= concept_id\nconcept_id ::= {}", rule)
    }
}

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

    #[test]
    fn test_vocabulary_solver_registrations() {
        let mut solver = OntologicalVocabularySolver::new();

        let c1 = OntologicalConcept {
            id: "concept_root".to_string(),
            name: "Root Entity".to_string(),
            category: "generic".to_string(),
        };
        let c2 = OntologicalConcept {
            id: "concept_child".to_string(),
            name: "Child Entity".to_string(),
            category: "generic".to_string(),
        };

        solver.register_concept(c1.clone());
        solver.register_concept(c2.clone());
        solver.register_relationship("concept_root", "concept_child");

        assert_eq!(solver.concepts.len(), 2);
        assert_eq!(solver.concepts.get("concept_root"), Some(&c1));
        assert_eq!(solver.concepts.get("concept_child"), Some(&c2));
    }

    #[test]
    fn test_hierarchical_concept_traversals() {
        let mut solver = OntologicalVocabularySolver::new();

        let c1 = OntologicalConcept {
            id: "urn:coreason:entity:a".to_string(),
            name: "A".to_string(),
            category: "tda".to_string(),
        };
        let c2 = OntologicalConcept {
            id: "urn:coreason:entity:b".to_string(),
            name: "B".to_string(),
            category: "tda".to_string(),
        };
        let c3 = OntologicalConcept {
            id: "urn:coreason:entity:c".to_string(),
            name: "C".to_string(),
            category: "tda".to_string(),
        };

        solver.register_concept(c1.clone());
        solver.register_concept(c2.clone());
        solver.register_concept(c3.clone());

        // A -> B -> C
        solver.register_relationship("urn:coreason:entity:a", "urn:coreason:entity:b");
        solver.register_relationship("urn:coreason:entity:b", "urn:coreason:entity:c");

        // Descendants of A should be B and C
        let desc = solver.find_descendants("urn:coreason:entity:a");
        assert_eq!(desc.len(), 2);
        assert!(desc.contains(&c2));
        assert!(desc.contains(&c3));

        // Ancestors of C should be B and A
        let anc = solver.find_ancestors("urn:coreason:entity:c");
        assert_eq!(anc.len(), 2);
        assert!(anc.contains(&c2));
        assert!(anc.contains(&c1));
    }

    #[test]
    fn test_compile_cfg_constraint() {
        let solver = OntologicalVocabularySolver::new();
        let candidates = vec!["urn:coreason:a".to_string(), "urn:coreason:b".to_string()];

        let cfg = solver.compile_cfg_constraint(&candidates);
        assert_eq!(
            cfg,
            "root ::= concept_id\nconcept_id ::= \"urn:coreason:a\" | \"urn:coreason:b\""
        );

        let empty_cfg = solver.compile_cfg_constraint(&[]);
        assert_eq!(empty_cfg, "root ::= \"empty\"");
    }
}