reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
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
//! Knowledge Graph with Oxigraph
//!
//! This module provides RDF triple store and SPARQL query capabilities
//! using Oxigraph for knowledge graph construction and reasoning.
//!
//! # Features
//! - RDF triple storage (in-memory and persistent)
//! - SPARQL 1.1 query support
//! - Ontology loading (OWL, RDFS)
//! - Graph reasoning/inference
//! - Integration with ThinkTool outputs
//!
//! Enable with: `cargo build --features knowledge-graph`

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

// Re-export Oxigraph for direct access
pub use oxigraph;

use oxigraph::io::{RdfFormat, RdfParser, RdfSerializer};
use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, QuerySolutionIter};
use oxigraph::store::Store;

/// Configuration for the knowledge graph
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeGraphConfig {
    /// Path for persistent storage (None for in-memory)
    pub storage_path: Option<PathBuf>,
    /// Default namespace prefix
    pub default_namespace: String,
    /// Additional namespace prefixes
    pub namespaces: HashMap<String, String>,
    /// Enable reasoning/inference
    pub enable_reasoning: bool,
}

impl Default for KnowledgeGraphConfig {
    fn default() -> Self {
        let mut namespaces = HashMap::new();
        namespaces.insert(
            "rdf".to_string(),
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
        );
        namespaces.insert(
            "rdfs".to_string(),
            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
        );
        namespaces.insert(
            "owl".to_string(),
            "http://www.w3.org/2002/07/owl#".to_string(),
        );
        namespaces.insert(
            "xsd".to_string(),
            "http://www.w3.org/2001/XMLSchema#".to_string(),
        );
        namespaces.insert(
            "rk".to_string(),
            "https://reasonkit.sh/ontology#".to_string(),
        );

        Self {
            storage_path: None,
            default_namespace: "https://reasonkit.sh/ontology#".to_string(),
            namespaces,
            enable_reasoning: false,
        }
    }
}

/// A simplified triple representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Triple {
    /// Subject (IRI or blank node)
    pub subject: String,
    /// Predicate (IRI)
    pub predicate: String,
    /// Object (IRI, blank node, or literal)
    pub object: String,
    /// Optional graph name
    pub graph: Option<String>,
}

impl Triple {
    /// Create a new triple
    pub fn new(
        subject: impl Into<String>,
        predicate: impl Into<String>,
        object: impl Into<String>,
    ) -> Self {
        Self {
            subject: subject.into(),
            predicate: predicate.into(),
            object: object.into(),
            graph: None,
        }
    }

    /// Create a triple with a named graph
    pub fn in_graph(mut self, graph: impl Into<String>) -> Self {
        self.graph = Some(graph.into());
        self
    }
}

/// SPARQL query result row
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryRow {
    /// Variable bindings
    pub bindings: HashMap<String, String>,
}

/// SPARQL query results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SparqlResults {
    /// Variable names
    pub variables: Vec<String>,
    /// Result rows
    pub rows: Vec<QueryRow>,
    /// Query execution time in milliseconds
    pub execution_time_ms: u64,
}

/// Knowledge graph wrapper around Oxigraph
pub struct KnowledgeGraph {
    store: Store,
    config: KnowledgeGraphConfig,
}

impl KnowledgeGraph {
    /// Create a new in-memory knowledge graph
    pub fn new() -> Result<Self> {
        Self::with_config(KnowledgeGraphConfig::default())
    }

    /// Create a knowledge graph with configuration
    pub fn with_config(config: KnowledgeGraphConfig) -> Result<Self> {
        let store = if let Some(path) = &config.storage_path {
            Store::open(path)?
        } else {
            Store::new()?
        };

        Ok(Self { store, config })
    }

    /// Open or create a persistent knowledge graph
    pub fn open(path: impl Into<PathBuf>) -> Result<Self> {
        let config = KnowledgeGraphConfig {
            storage_path: Some(path.into()),
            ..Default::default()
        };
        Self::with_config(config)
    }

    /// Add a triple to the graph
    pub fn add_triple(&self, triple: &Triple) -> Result<()> {
        let subject = self.parse_subject(&triple.subject)?;
        let predicate = NamedNode::new(&triple.predicate)?;
        let object = self.parse_object(&triple.object)?;

        let quad = if let Some(graph_name) = &triple.graph {
            Quad::new(subject, predicate, object, NamedNode::new(graph_name)?)
        } else {
            Quad::new(subject, predicate, object, GraphName::DefaultGraph)
        };

        self.store.insert(&quad)?;
        Ok(())
    }

    /// Add multiple triples
    pub fn add_triples(&self, triples: &[Triple]) -> Result<()> {
        for triple in triples {
            self.add_triple(triple)?;
        }
        Ok(())
    }

    /// Remove a triple from the graph
    pub fn remove_triple(&self, triple: &Triple) -> Result<()> {
        let subject = self.parse_subject(&triple.subject)?;
        let predicate = NamedNode::new(&triple.predicate)?;
        let object = self.parse_object(&triple.object)?;

        let quad = if let Some(graph_name) = &triple.graph {
            Quad::new(subject, predicate, object, NamedNode::new(graph_name)?)
        } else {
            Quad::new(subject, predicate, object, GraphName::DefaultGraph)
        };

        self.store.remove(&quad)?;
        Ok(())
    }

    /// Execute a SPARQL SELECT query
    pub fn query(&self, sparql: &str) -> Result<SparqlResults> {
        let start = std::time::Instant::now();
        let query_with_prefixes = self.add_prefixes(sparql);

        let results = self.store.query(&query_with_prefixes)?;

        match results {
            QueryResults::Solutions(solutions) => {
                let variables: Vec<String> = solutions
                    .variables()
                    .iter()
                    .map(|v| v.as_str().to_string())
                    .collect();

                let rows = self.collect_solutions(solutions)?;

                Ok(SparqlResults {
                    variables,
                    rows,
                    execution_time_ms: start.elapsed().as_millis() as u64,
                })
            }
            _ => anyhow::bail!("Expected SELECT query results"),
        }
    }

    /// Execute a SPARQL ASK query
    pub fn ask(&self, sparql: &str) -> Result<bool> {
        let query_with_prefixes = self.add_prefixes(sparql);
        let results = self.store.query(&query_with_prefixes)?;

        match results {
            QueryResults::Boolean(b) => Ok(b),
            _ => anyhow::bail!("Expected ASK query results"),
        }
    }

    /// Execute a SPARQL UPDATE
    pub fn update(&self, sparql: &str) -> Result<()> {
        let update_with_prefixes = self.add_prefixes(sparql);
        self.store.update(&update_with_prefixes)?;
        Ok(())
    }

    /// Load RDF data from a string
    pub fn load_rdf(&self, data: &str, format: RdfFormat) -> Result<()> {
        for quad_result in RdfParser::from_format(format).for_reader(data.as_bytes()) {
            let quad = quad_result?;
            self.store.insert(&quad)?;
        }

        Ok(())
    }

    /// Export graph as RDF
    pub fn export_rdf(&self, format: RdfFormat) -> Result<String> {
        let mut writer = RdfSerializer::from_format(format).for_writer(Vec::new());
        for quad in self.store.iter() {
            writer.serialize_quad(&quad?)?;
        }
        Ok(String::from_utf8(writer.finish()?)?)
    }

    /// Get triple count
    pub fn len(&self) -> Result<usize> {
        Ok(self.store.len()?)
    }

    /// Check if graph is empty
    pub fn is_empty(&self) -> Result<bool> {
        Ok(self.store.is_empty()?)
    }

    /// Clear all triples
    pub fn clear(&self) -> Result<()> {
        self.store.clear()?;
        Ok(())
    }

    /// Get all triples matching a pattern (None = wildcard)
    pub fn find(
        &self,
        subject: Option<&str>,
        predicate: Option<&str>,
        object: Option<&str>,
    ) -> Result<Vec<Triple>> {
        let mut results = Vec::new();

        for quad in self.store.iter() {
            let quad = quad?;

            let subject_str = self.term_to_string(&quad.subject.clone().into());
            let s_match = subject.map_or(true, |s| subject_str.as_str() == s);
            let p_match = predicate.map_or(true, |p| quad.predicate.as_str() == p);
            let o_match = object.map_or(true, |o| self.term_to_string(&quad.object) == o);

            if s_match && p_match && o_match {
                results.push(Triple {
                    subject: subject_str,
                    predicate: quad.predicate.as_str().to_string(),
                    object: self.term_to_string(&quad.object),
                    graph: match quad.graph_name {
                        GraphName::DefaultGraph => None,
                        GraphName::NamedNode(n) => Some(n.as_str().to_string()),
                        GraphName::BlankNode(b) => Some(format!("_:{}", b.as_str())),
                    },
                });
            }
        }

        Ok(results)
    }

    // Helper methods

    fn parse_subject(&self, s: &str) -> Result<Subject> {
        if let Some(stripped) = s.strip_prefix("_:") {
            Ok(BlankNode::new(stripped)?.into())
        } else {
            Ok(NamedNode::new(s)?.into())
        }
    }

    fn parse_object(&self, o: &str) -> Result<Term> {
        if let Some(stripped) = o.strip_prefix("_:") {
            Ok(BlankNode::new(stripped)?.into())
        } else if o.starts_with("http://") || o.starts_with("https://") || o.starts_with("urn:") {
            Ok(NamedNode::new(o)?.into())
        } else {
            // Treat as literal
            Ok(Literal::new_simple_literal(o).into())
        }
    }

    fn term_to_string(&self, term: &Term) -> String {
        match term {
            Term::NamedNode(n) => n.as_str().to_string(),
            Term::BlankNode(b) => format!("_:{}", b.as_str()),
            Term::Literal(l) => l.value().to_string(),
            Term::Triple(_) => "[triple]".to_string(),
        }
    }

    fn add_prefixes(&self, sparql: &str) -> String {
        let mut prefixes = String::new();
        for (prefix, uri) in &self.config.namespaces {
            prefixes.push_str(&format!("PREFIX {}: <{}>\n", prefix, uri));
        }
        format!("{}{}", prefixes, sparql)
    }

    fn collect_solutions(&self, solutions: QuerySolutionIter) -> Result<Vec<QueryRow>> {
        let mut rows = Vec::new();
        for solution in solutions {
            let solution = solution?;
            let mut bindings = HashMap::new();
            for (var, term) in solution.iter() {
                bindings.insert(var.as_str().to_string(), self.term_to_string(term));
            }
            rows.push(QueryRow { bindings });
        }
        Ok(rows)
    }
}

impl Default for KnowledgeGraph {
    fn default() -> Self {
        Self::new().expect("Failed to create default knowledge graph")
    }
}

/// Builder for constructing triples with ReasonKit ontology
pub struct OntologyBuilder {
    namespace: String,
    triples: Vec<Triple>,
}

impl OntologyBuilder {
    /// Create a new ontology builder
    pub fn new(namespace: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            triples: Vec::new(),
        }
    }

    /// Create with ReasonKit namespace
    pub fn reasonkit() -> Self {
        Self::new("https://reasonkit.sh/ontology#")
    }

    /// Add a class definition
    pub fn class(mut self, name: &str, label: &str, description: &str) -> Self {
        let class_iri = format!("{}{}", self.namespace, name);
        self.triples.push(Triple::new(
            &class_iri,
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            "http://www.w3.org/2002/07/owl#Class",
        ));
        self.triples.push(Triple::new(
            &class_iri,
            "http://www.w3.org/2000/01/rdf-schema#label",
            label,
        ));
        self.triples.push(Triple::new(
            &class_iri,
            "http://www.w3.org/2000/01/rdf-schema#comment",
            description,
        ));
        self
    }

    /// Add a subclass relationship
    pub fn subclass(mut self, child: &str, parent: &str) -> Self {
        let child_iri = format!("{}{}", self.namespace, child);
        let parent_iri = format!("{}{}", self.namespace, parent);
        self.triples.push(Triple::new(
            child_iri,
            "http://www.w3.org/2000/01/rdf-schema#subClassOf",
            parent_iri,
        ));
        self
    }

    /// Add a property definition
    pub fn property(mut self, name: &str, label: &str, domain: &str, range: &str) -> Self {
        let prop_iri = format!("{}{}", self.namespace, name);
        let domain_iri = format!("{}{}", self.namespace, domain);
        let range_iri = format!("{}{}", self.namespace, range);

        self.triples.push(Triple::new(
            &prop_iri,
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            "http://www.w3.org/2002/07/owl#ObjectProperty",
        ));
        self.triples.push(Triple::new(
            &prop_iri,
            "http://www.w3.org/2000/01/rdf-schema#label",
            label,
        ));
        self.triples.push(Triple::new(
            &prop_iri,
            "http://www.w3.org/2000/01/rdf-schema#domain",
            domain_iri,
        ));
        self.triples.push(Triple::new(
            &prop_iri,
            "http://www.w3.org/2000/01/rdf-schema#range",
            range_iri,
        ));
        self
    }

    /// Build and return the triples
    pub fn build(self) -> Vec<Triple> {
        self.triples
    }
}

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

    #[test]
    fn test_config_default() {
        let config = KnowledgeGraphConfig::default();
        assert!(config.namespaces.contains_key("rdf"));
        assert!(config.namespaces.contains_key("rk"));
    }

    #[test]
    fn test_triple_creation() {
        let triple = Triple::new(
            "https://example.org/subject",
            "https://example.org/predicate",
            "https://example.org/object",
        );
        assert!(triple.graph.is_none());

        let triple_with_graph = triple.in_graph("https://example.org/graph");
        assert!(triple_with_graph.graph.is_some());
    }

    #[test]
    fn test_knowledge_graph_basic() {
        let kg = KnowledgeGraph::new().unwrap();

        let triple = Triple::new(
            "https://reasonkit.sh/entity/1",
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            "https://reasonkit.sh/ontology#ThinkTool",
        );

        kg.add_triple(&triple).unwrap();
        assert_eq!(kg.len().unwrap(), 1);

        kg.remove_triple(&triple).unwrap();
        assert!(kg.is_empty().unwrap());
    }

    #[test]
    fn test_sparql_query() {
        let kg = KnowledgeGraph::new().unwrap();

        kg.add_triple(&Triple::new(
            "https://reasonkit.sh/tool/gigathink",
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            "https://reasonkit.sh/ontology#ThinkTool",
        ))
        .unwrap();

        kg.add_triple(&Triple::new(
            "https://reasonkit.sh/tool/gigathink",
            "http://www.w3.org/2000/01/rdf-schema#label",
            "GigaThink",
        ))
        .unwrap();

        let results = kg.query("SELECT ?s WHERE { ?s a rk:ThinkTool }").unwrap();
        assert_eq!(results.rows.len(), 1);
    }

    #[test]
    fn test_ontology_builder() {
        let triples = OntologyBuilder::reasonkit()
            .class("ThinkTool", "ThinkTool", "A reasoning tool")
            .class("GigaThink", "GigaThink", "Expansive creative thinking")
            .subclass("GigaThink", "ThinkTool")
            .build();

        assert!(triples.len() >= 7); // 3 per class + 1 subclass
    }
}