1use crate::application::{FieldType, ScalarType};
2use crate::graph::Graph;
3use crate::parser::ast::TargetFormat;
4use crate::policy::{Policy, PolicyKind, PolicyModality};
5use crate::primitives::Instance;
6use crate::projection::{find_projection_override, ProjectionRegistry};
7use percent_encoding::{percent_decode_str, utf8_percent_encode, AsciiSet, CONTROLS};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::collections::BTreeMap;
11use std::str::FromStr;
12
13#[derive(Debug, Clone)]
14pub enum KgError {
15 SerializationError(String),
16 UnsupportedFormat(String),
17}
18
19impl std::fmt::Display for KgError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 KgError::SerializationError(msg) => {
23 write!(f, "Knowledge graph serialization error: {}", msg)
24 }
25 KgError::UnsupportedFormat(fmt) => write!(f, "Unsupported format: {}", fmt),
26 }
27 }
28}
29
30impl std::error::Error for KgError {}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct Triple {
34 pub subject: String,
35 pub predicate: String,
36 pub object: String,
37}
38
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct ShaclShape {
41 pub target_class: String,
42 pub properties: Vec<ShaclProperty>,
43}
44
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub struct ShaclProperty {
47 pub path: String,
48 pub datatype: Option<String>,
49 pub min_count: Option<u32>,
50 pub max_count: Option<u32>,
51 pub min_exclusive: Option<String>,
52}
53
54#[derive(Debug, Clone)]
55pub struct KnowledgeGraph {
56 pub triples: Vec<Triple>,
57 pub shapes: Vec<ShaclShape>,
58}
59
60const URI_ENCODE_SET: &AsciiSet = &CONTROLS
61 .add(b' ')
62 .add(b':')
63 .add(b'/')
64 .add(b'#')
65 .add(b'?')
66 .add(b'&')
67 .add(b'=')
68 .add(b'+')
69 .add(b'$')
70 .add(b',')
71 .add(b'@')
72 .add(b';');
73
74fn split_turtle_segments(line: &str) -> Vec<(String, Option<char>)> {
79 let mut segments = Vec::new();
80 let mut current = String::new();
81 let mut in_literal = false;
82 let mut in_iri = false;
83 let mut escape = false;
84 let mut bracket_depth: usize = 0;
85 for c in line.chars() {
86 if in_literal {
87 current.push(c);
88 if escape {
89 escape = false;
90 } else if c == '\\' {
91 escape = true;
92 } else if c == '"' {
93 in_literal = false;
94 }
95 continue;
96 }
97 if in_iri {
98 current.push(c);
99 if c == '>' {
100 in_iri = false;
101 }
102 continue;
103 }
104 match c {
105 '"' => {
106 in_literal = true;
107 current.push(c);
108 }
109 '<' => {
110 in_iri = true;
111 current.push(c);
112 }
113 '[' => {
114 bracket_depth += 1;
115 current.push(c);
116 }
117 ']' => {
118 bracket_depth = bracket_depth.saturating_sub(1);
119 current.push(c);
120 }
121 ';' if bracket_depth == 0 => {
122 segments.push((current.trim_end().to_string(), Some(';')));
123 current = String::new();
124 }
125 _ => current.push(c),
126 }
127 }
128 let trimmed = current.trim_end().to_string();
129 let terminator = trimmed
130 .chars()
131 .rev()
132 .find(|c| !c.is_whitespace())
133 .filter(|c| *c == '.' || *c == ';' || *c == ',');
134 let core = match terminator {
135 Some(t) => {
136 let stripped = trimmed.trim_end();
137 stripped[..stripped.len() - t.len_utf8()]
138 .trim_end()
139 .to_string()
140 }
141 None => trimmed,
142 };
143 if !core.is_empty() || terminator.is_some() {
144 segments.push((core, terminator));
145 }
146 segments
147}
148
149fn split_top_level_commas(tokens: &[String]) -> Vec<String> {
153 let joined = tokens.join(" ");
154 let mut objects = Vec::new();
155 let mut current = String::new();
156 let mut in_literal = false;
157 let mut in_iri = false;
158 let mut escape = false;
159 for c in joined.chars() {
160 if in_literal {
161 current.push(c);
162 if escape {
163 escape = false;
164 } else if c == '\\' {
165 escape = true;
166 } else if c == '"' {
167 in_literal = false;
168 }
169 continue;
170 }
171 if in_iri {
172 current.push(c);
173 if c == '>' {
174 in_iri = false;
175 }
176 continue;
177 }
178 match c {
179 '"' => {
180 in_literal = true;
181 current.push(c);
182 }
183 '<' => {
184 in_iri = true;
185 current.push(c);
186 }
187 ',' => {
188 let obj = current.trim().to_string();
189 if !obj.is_empty() {
190 objects.push(obj);
191 }
192 current = String::new();
193 }
194 _ => current.push(c),
195 }
196 }
197 let obj = current.trim().to_string();
198 if !obj.is_empty() {
199 objects.push(obj);
200 }
201 objects
202}
203
204fn push_expanded_triple(kg: &mut KnowledgeGraph, subject: &str, predicate: &str, object: &str) {
207 let norm_p = if predicate == "a" {
208 "rdf:type".to_string()
209 } else {
210 KnowledgeGraph::shorten_token(predicate)
211 };
212 kg.triples.push(Triple {
213 subject: KnowledgeGraph::shorten_token(subject),
214 predicate: norm_p,
215 object: KnowledgeGraph::shorten_token(object),
216 });
217}
218
219fn parse_shape_property_attrs(attrs: &[(String, String)]) -> Option<ShaclProperty> {
224 let mut path = String::new();
225 let mut datatype: Option<String> = None;
226 let mut min_count: Option<u32> = None;
227 let mut max_count: Option<u32> = None;
228 let mut min_exclusive: Option<String> = None;
229 for (pred, obj) in attrs {
230 match pred.as_str() {
231 "sh:path" => path = obj.trim().to_string(),
232 "sh:datatype" => datatype = Some(obj.trim().to_string()),
233 "sh:minCount" => {
234 if let Ok(n) = obj.trim().parse::<u32>() {
235 min_count = Some(n);
236 }
237 }
238 "sh:maxCount" => {
239 if let Ok(n) = obj.trim().parse::<u32>() {
240 max_count = Some(n);
241 }
242 }
243 "sh:minExclusive" => min_exclusive = Some(obj.trim().to_string()),
244 _ => {}
245 }
246 }
247 if path.is_empty() {
248 return None;
249 }
250 Some(ShaclProperty {
251 path,
252 datatype,
253 min_count,
254 max_count,
255 min_exclusive,
256 })
257}
258
259fn tokenize_triple_line(line: &str) -> Vec<String> {
260 let mut tokens = Vec::new();
261 let mut buffer = String::new();
262 let mut in_literal = false;
263 let mut escape = false;
264
265 for c in line.chars() {
266 if in_literal {
267 buffer.push(c);
268 if escape {
269 escape = false;
270 } else if c == '\\' {
271 escape = true;
272 } else if c == '"' {
273 in_literal = false;
274 }
275 continue;
276 }
277
278 match c {
279 '"' => {
280 in_literal = true;
281 buffer.push(c);
282 }
283 c if c.is_whitespace() => {
284 if !buffer.is_empty() {
285 tokens.push(buffer.clone());
286 buffer.clear();
287 }
288 }
289 _ => {
290 buffer.push(c);
291 }
292 }
293 }
294
295 if !buffer.is_empty() {
296 tokens.push(buffer);
297 }
298
299 tokens
300}
301
302fn extract_local_name(token: &str) -> String {
303 let trimmed = token.trim();
304 let stripped = trimmed.trim_matches(|c| c == '<' || c == '>');
305 stripped
306 .rsplit(|c| ['#', ':'].contains(&c))
307 .next()
308 .unwrap_or(stripped)
309 .to_string()
310}
311
312fn extract_literal_value(token: &str) -> String {
313 let trimmed = token.trim();
314 if let Some(stripped) = trimmed.strip_prefix('"') {
315 if let Some(end_quote) = stripped.find('"') {
316 return stripped[..end_quote].to_string();
317 }
318 return stripped.trim_end_matches('"').to_string();
319 }
320
321 if let Some(idx) = trimmed.find("^^") {
322 return trimmed[..idx].trim().to_string();
323 }
324 trimmed.to_string()
325}
326
327impl KnowledgeGraph {
328 pub fn new() -> Self {
329 Self {
330 triples: Vec::new(),
331 shapes: Vec::new(),
332 }
333 }
334
335 pub fn from_graph(graph: &Graph) -> Result<Self, KgError> {
336 let mut kg = Self::new();
337
338 let registry = ProjectionRegistry::new(graph);
339 let projections = registry.find_projections_for_target(&TargetFormat::Kg);
340 let projection = projections.first().copied();
341
342 for entity in graph.all_entities() {
343 let mut rdf_class = "sea:Entity".to_string();
344 let mut prop_map = std::collections::HashMap::new();
345
346 if let Some(proj) = projection {
347 if let Some(rule) = find_projection_override(proj, "Entity", entity.name()) {
348 if let Some(cls) = rule.fields.get("rdf_class").and_then(|v| v.as_str()) {
349 if Self::is_valid_rdf_term(cls) {
350 rdf_class = cls.to_string();
351 } else {
352 eprintln!("Warning: Invalid RDF term for rdf_class, skipping: {}", cls);
353 }
354 }
355 if let Some(props) = rule.fields.get("properties").and_then(|v| v.as_object()) {
356 for (k, v) in props {
357 if let Some(v_str) = v.as_str() {
358 if Self::is_valid_rdf_term(v_str) {
359 prop_map.insert(k.clone(), v_str.to_string());
360 } else {
361 eprintln!(
362 "Warning: Invalid RDF term for property '{}', skipping: {}",
363 k, v_str
364 );
365 }
366 }
367 }
368 }
369 }
370 }
371
372 kg.triples.push(Triple {
373 subject: format!("sea:{}", Self::uri_encode(entity.name())),
374 predicate: "rdf:type".to_string(),
375 object: rdf_class,
376 });
377
378 let label_pred = prop_map
379 .get("name")
380 .cloned()
381 .unwrap_or_else(|| "rdfs:label".to_string());
382 kg.triples.push(Triple {
383 subject: format!("sea:{}", Self::uri_encode(entity.name())),
384 predicate: label_pred,
385 object: format!("\"{}\"", Self::escape_turtle_literal(entity.name())),
386 });
387
388 let ns_pred = prop_map
389 .get("namespace")
390 .cloned()
391 .unwrap_or_else(|| "sea:namespace".to_string());
392 kg.triples.push(Triple {
393 subject: format!("sea:{}", Self::uri_encode(entity.name())),
394 predicate: ns_pred,
395 object: format!("\"{}\"", Self::escape_turtle_literal(entity.namespace())),
396 });
397 }
398
399 for role in graph.all_roles() {
400 kg.triples.push(Triple {
401 subject: format!("sea:{}", Self::uri_encode(role.name())),
402 predicate: "rdf:type".to_string(),
403 object: "sea:Role".to_string(),
404 });
405
406 kg.triples.push(Triple {
407 subject: format!("sea:{}", Self::uri_encode(role.name())),
408 predicate: "rdfs:label".to_string(),
409 object: format!("\"{}\"", Self::escape_turtle_literal(role.name())),
410 });
411
412 kg.triples.push(Triple {
413 subject: format!("sea:{}", Self::uri_encode(role.name())),
414 predicate: "sea:namespace".to_string(),
415 object: format!("\"{}\"", Self::escape_turtle_literal(role.namespace())),
416 });
417 }
418
419 for resource in graph.all_resources() {
420 kg.triples.push(Triple {
421 subject: format!("sea:{}", Self::uri_encode(resource.name())),
422 predicate: "rdf:type".to_string(),
423 object: "sea:Resource".to_string(),
424 });
425
426 kg.triples.push(Triple {
427 subject: format!("sea:{}", Self::uri_encode(resource.name())),
428 predicate: "rdfs:label".to_string(),
429 object: format!("\"{}\"", Self::escape_turtle_literal(resource.name())),
430 });
431
432 kg.triples.push(Triple {
433 subject: format!("sea:{}", Self::uri_encode(resource.name())),
434 predicate: "sea:unit".to_string(),
435 object: format!(
436 "\"{}\"",
437 Self::escape_turtle_literal(&resource.unit().to_string())
438 ),
439 });
440 }
441
442 for pattern in graph.all_patterns() {
443 let subject = format!("sea:pattern_{}", Self::uri_encode(pattern.name()));
444
445 kg.triples.push(Triple {
446 subject: subject.clone(),
447 predicate: "rdf:type".to_string(),
448 object: "sea:Pattern".to_string(),
449 });
450
451 kg.triples.push(Triple {
452 subject: subject.clone(),
453 predicate: "rdfs:label".to_string(),
454 object: format!("\"{}\"", Self::escape_turtle_literal(pattern.name())),
455 });
456
457 kg.triples.push(Triple {
458 subject: subject.clone(),
459 predicate: "sea:namespace".to_string(),
460 object: format!("\"{}\"", Self::escape_turtle_literal(pattern.namespace())),
461 });
462
463 kg.triples.push(Triple {
464 subject,
465 predicate: "sea:regex".to_string(),
466 object: format!("\"{}\"", Self::escape_turtle_literal(pattern.regex())),
467 });
468 }
469
470 for relation in graph.all_relations() {
471 let relation_subject = format!("sea:{}", Self::uri_encode(relation.name()));
472
473 kg.triples.push(Triple {
474 subject: relation_subject.clone(),
475 predicate: "rdf:type".to_string(),
476 object: "sea:Relation".to_string(),
477 });
478
479 kg.triples.push(Triple {
480 subject: relation_subject.clone(),
481 predicate: "rdfs:label".to_string(),
482 object: format!("\"{}\"", Self::escape_turtle_literal(relation.name())),
483 });
484
485 if let Some(subject_role) = graph.get_role(relation.subject_role()) {
486 kg.triples.push(Triple {
487 subject: relation_subject.clone(),
488 predicate: "sea:subjectRole".to_string(),
489 object: format!("sea:{}", Self::uri_encode(subject_role.name())),
490 });
491 }
492
493 if let Some(object_role) = graph.get_role(relation.object_role()) {
494 kg.triples.push(Triple {
495 subject: relation_subject.clone(),
496 predicate: "sea:objectRole".to_string(),
497 object: format!("sea:{}", Self::uri_encode(object_role.name())),
498 });
499 }
500
501 kg.triples.push(Triple {
502 subject: relation_subject.clone(),
503 predicate: "sea:predicate".to_string(),
504 object: format!("\"{}\"", Self::escape_turtle_literal(relation.predicate())),
505 });
506
507 if let Some(flow_id) = relation.via_flow() {
508 if let Some(resource) = graph.get_resource(flow_id) {
509 kg.triples.push(Triple {
510 subject: relation_subject.clone(),
511 predicate: "sea:via".to_string(),
512 object: format!("sea:{}", Self::uri_encode(resource.name())),
513 });
514 } else {
515 kg.triples.push(Triple {
516 subject: relation_subject.clone(),
517 predicate: "sea:via".to_string(),
518 object: format!("\"{}\"", flow_id),
519 });
520 }
521 }
522 }
523
524 for flow in graph.all_flows() {
525 let flow_id = format!("sea:flow_{}", Self::uri_encode(&flow.id().to_string()));
526
527 kg.triples.push(Triple {
528 subject: flow_id.clone(),
529 predicate: "rdf:type".to_string(),
530 object: "sea:Flow".to_string(),
531 });
532
533 if let Some(from_entity) = graph.get_entity(flow.from_id()) {
534 kg.triples.push(Triple {
535 subject: flow_id.clone(),
536 predicate: "sea:from".to_string(),
537 object: format!("sea:{}", Self::uri_encode(from_entity.name())),
538 });
539 }
540
541 if let Some(to_entity) = graph.get_entity(flow.to_id()) {
542 kg.triples.push(Triple {
543 subject: flow_id.clone(),
544 predicate: "sea:to".to_string(),
545 object: format!("sea:{}", Self::uri_encode(to_entity.name())),
546 });
547 }
548
549 if let Some(resource) = graph.get_resource(flow.resource_id()) {
550 kg.triples.push(Triple {
551 subject: flow_id.clone(),
552 predicate: "sea:hasResource".to_string(),
553 object: format!("sea:{}", Self::uri_encode(resource.name())),
554 });
555 }
556
557 let quantity_str = flow.quantity().to_string();
559 Self::validate_turtle_decimal(&quantity_str).map_err(|e| {
560 KgError::SerializationError(format!("Invalid quantity format: {}", e))
561 })?;
562
563 kg.triples.push(Triple {
564 subject: flow_id.clone(),
565 predicate: "sea:quantity".to_string(),
566 object: format!("\"{}\"^^xsd:decimal", quantity_str),
567 });
568 }
569
570 for instance in graph.all_entity_instances() {
575 let subject = Self::entity_instance_iri(instance);
576
577 kg.triples.push(Triple {
578 subject: subject.clone(),
579 predicate: "rdf:type".to_string(),
580 object: "sea:EntityInstance".to_string(),
581 });
582
583 kg.triples.push(Triple {
587 subject: subject.clone(),
588 predicate: "sea:instanceOf".to_string(),
589 object: format!("sea:{}", Self::uri_encode(instance.entity_type())),
590 });
591
592 kg.triples.push(Triple {
593 subject: subject.clone(),
594 predicate: "rdfs:label".to_string(),
595 object: format!("\"{}\"", Self::escape_turtle_literal(instance.name())),
596 });
597
598 kg.triples.push(Triple {
599 subject: subject.clone(),
600 predicate: "sea:namespace".to_string(),
601 object: format!("\"{}\"", Self::escape_turtle_literal(instance.namespace())),
602 });
603
604 let contract = graph
607 .find_entity_by_name_and_namespace(instance.entity_type(), instance.namespace())
608 .and_then(|entity_id| graph.entity_contract(&entity_id));
609
610 let ordered: BTreeMap<&str, &Value> = instance
613 .fields()
614 .iter()
615 .map(|(key, value)| (key.as_str(), value))
616 .collect();
617
618 for (key, value) in ordered {
619 let declared = contract.and_then(|contract| {
620 contract
621 .fields
622 .iter()
623 .find(|field| field.name == key)
624 .map(|field| &field.field_type)
625 });
626 let Some(object) = Self::instance_field_object(value, declared) else {
627 continue;
628 };
629 kg.triples.push(Triple {
630 subject: subject.clone(),
631 predicate: format!("sea:{}", Self::uri_encode(key)),
632 object,
633 });
634 }
635 }
636
637 for policy in graph.all_policies() {
642 let subject = Self::policy_iri(policy);
643
644 kg.triples.push(Triple {
645 subject: subject.clone(),
646 predicate: "rdf:type".to_string(),
647 object: "sea:Policy".to_string(),
648 });
649
650 let mut literals: Vec<(&str, String)> = vec![
651 ("rdfs:label", policy.name.clone()),
652 ("sea:namespace", policy.namespace.clone()),
653 ("sea:version", policy.version.to_string()),
654 (
655 "sea:modality",
656 match policy.modality {
657 PolicyModality::Obligation => "obligation",
658 PolicyModality::Prohibition => "prohibition",
659 PolicyModality::Permission => "permission",
660 }
661 .to_string(),
662 ),
663 (
664 "sea:policyKind",
665 match policy.kind {
666 PolicyKind::Constraint => "constraint",
667 PolicyKind::Derivation => "derivation",
668 PolicyKind::Obligation => "obligation",
669 }
670 .to_string(),
671 ),
672 ("sea:expression", policy.normalized_expression().to_string()),
673 ];
674 if let Some(rationale) = policy.rationale.as_ref() {
675 literals.push(("sea:rationale", rationale.clone()));
676 }
677
678 for (predicate, literal) in literals {
679 kg.triples.push(Triple {
680 subject: subject.clone(),
681 predicate: predicate.to_string(),
682 object: format!("\"{}\"", Self::escape_turtle_literal(&literal)),
683 });
684 }
685
686 kg.triples.push(Triple {
687 subject: subject.clone(),
688 predicate: "sea:priority".to_string(),
689 object: format!("\"{}\"^^xsd:integer", policy.priority),
690 });
691
692 let mut tags: Vec<&str> = policy.tags.iter().map(String::as_str).collect();
694 tags.sort_unstable();
695 tags.dedup();
696 for tag in tags {
697 kg.triples.push(Triple {
698 subject: subject.clone(),
699 predicate: "sea:tag".to_string(),
700 object: format!("\"{}\"", Self::escape_turtle_literal(tag)),
701 });
702 }
703 }
704
705 kg.shapes.push(ShaclShape {
706 target_class: "sea:Flow".to_string(),
707 properties: vec![
708 ShaclProperty {
709 path: "sea:quantity".to_string(),
710 datatype: Some("xsd:decimal".to_string()),
711 min_count: None,
712 max_count: None,
713 min_exclusive: Some("0".to_string()),
714 },
715 ShaclProperty {
716 path: "sea:hasResource".to_string(),
717 datatype: None,
718 min_count: Some(1),
719 max_count: Some(1),
720 min_exclusive: None,
721 },
722 ShaclProperty {
723 path: "sea:from".to_string(),
724 datatype: None,
725 min_count: Some(1),
726 max_count: Some(1),
727 min_exclusive: None,
728 },
729 ShaclProperty {
730 path: "sea:to".to_string(),
731 datatype: None,
732 min_count: Some(1),
733 max_count: Some(1),
734 min_exclusive: None,
735 },
736 ],
737 });
738
739 kg.shapes.push(ShaclShape {
740 target_class: "sea:Entity".to_string(),
741 properties: vec![ShaclProperty {
742 path: "rdfs:label".to_string(),
743 datatype: Some("xsd:string".to_string()),
744 min_count: Some(1),
745 max_count: Some(1),
746 min_exclusive: None,
747 }],
748 });
749
750 Ok(kg)
751 }
752
753 pub fn to_turtle(&self) -> String {
754 let mut turtle = String::new();
755
756 turtle.push_str("@prefix sea: <http://domainforge.ai/sea#> .\n");
757 turtle.push_str("@prefix owl: <http://www.w3.org/2002/07/owl#> .\n");
758 turtle.push_str("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n");
759 turtle.push_str("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n");
760 turtle.push_str("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n");
761 turtle.push_str("@prefix sh: <http://www.w3.org/ns/shacl#> .\n");
762 turtle.push('\n');
763
764 turtle.push_str("# Ontology\n");
765 turtle.push_str("sea:Entity a owl:Class ;\n");
766 turtle.push_str(" rdfs:label \"Entity\" ;\n");
767 turtle.push_str(
768 " rdfs:comment \"Business actor, location, or organizational unit\" .\n\n",
769 );
770
771 turtle.push_str("sea:Resource a owl:Class ;\n");
772 turtle.push_str(" rdfs:label \"Resource\" ;\n");
773 turtle.push_str(" rdfs:comment \"Quantifiable subject of value\" .\n\n");
774
775 turtle.push_str("sea:Flow a owl:Class ;\n");
776 turtle.push_str(" rdfs:label \"Flow\" ;\n");
777 turtle.push_str(" rdfs:comment \"Transfer of resource between entities\" .\n\n");
778
779 turtle.push_str("sea:hasResource a owl:ObjectProperty ;\n");
780 turtle.push_str(" rdfs:domain sea:Flow ;\n");
781 turtle.push_str(" rdfs:range sea:Resource .\n\n");
782
783 turtle.push_str("sea:from a owl:ObjectProperty ;\n");
784 turtle.push_str(" rdfs:domain sea:Flow ;\n");
785 turtle.push_str(" rdfs:range sea:Entity .\n\n");
786
787 turtle.push_str("sea:to a owl:ObjectProperty ;\n");
788 turtle.push_str(" rdfs:domain sea:Flow ;\n");
789 turtle.push_str(" rdfs:range sea:Entity .\n\n");
790
791 turtle.push_str("sea:EntityInstance a owl:Class ;\n");
792 turtle.push_str(" rdfs:label \"EntityInstance\" ;\n");
793 turtle.push_str(
794 " rdfs:comment \"Declared instance of an entity with field values\" .\n\n",
795 );
796
797 turtle.push_str("sea:Policy a owl:Class ;\n");
798 turtle.push_str(" rdfs:label \"Policy\" ;\n");
799 turtle.push_str(" rdfs:comment \"Declared rule over the model; expression is stated, not enforced here\" .\n\n");
800
801 turtle.push_str("sea:instanceOf a owl:ObjectProperty ;\n");
802 turtle.push_str(" rdfs:domain sea:EntityInstance ;\n");
803 turtle.push_str(" rdfs:range sea:Entity .\n\n");
804
805 turtle.push_str("# Instances\n");
806 for triple in &self.triples {
807 turtle.push_str(&format!(
808 "{} {} {} .\n",
809 triple.subject, triple.predicate, triple.object
810 ));
811 }
812
813 turtle.push_str("\n# SHACL Shapes\n");
814 for shape in &self.shapes {
815 turtle.push_str(&format!(
816 "sea:{}Shape a sh:NodeShape ;\n",
817 shape.target_class.replace("sea:", "")
818 ));
819 turtle.push_str(&format!(" sh:targetClass {} ;\n", shape.target_class));
820
821 for (i, prop) in shape.properties.iter().enumerate() {
822 turtle.push_str(" sh:property [\n");
823 turtle.push_str(&format!(" sh:path {} ;\n", prop.path));
824
825 if let Some(dt) = &prop.datatype {
826 turtle.push_str(&format!(" sh:datatype {} ;\n", dt));
827 }
828 if let Some(min) = prop.min_count {
829 turtle.push_str(&format!(" sh:minCount {} ;\n", min));
830 }
831 if let Some(max) = prop.max_count {
832 turtle.push_str(&format!(" sh:maxCount {} ;\n", max));
833 }
834 if let Some(min_ex) = &prop.min_exclusive {
835 turtle.push_str(&format!(" sh:minExclusive {} ;\n", min_ex));
836 }
837
838 if i < shape.properties.len() - 1 {
839 turtle.push_str(" ] ;\n");
840 } else {
841 turtle.push_str(" ] .\n");
842 }
843 }
844 turtle.push('\n');
845 }
846
847 turtle
848 }
849
850 #[allow(clippy::while_let_on_iterator)]
854 pub fn from_turtle(turtle: &str) -> Result<Self, KgError> {
855 let mut kg = Self::new();
856 let mut carry_subject: Option<String> = None;
859 let mut carry_predicate: Option<String> = None;
860 let mut prev_terminator: Option<char> = None;
861 for line in turtle.lines() {
862 let trimmed = line.trim();
863 if trimmed.is_empty() || trimmed.starts_with('@') || trimmed.starts_with('#') {
864 continue;
865 }
866 for (core, terminator) in split_turtle_segments(trimmed) {
867 let tokens = tokenize_triple_line(&core);
868 match prev_terminator {
869 Some(',') => {
871 if tokens.len() == 1 {
872 if let (Some(s), Some(p)) =
873 (carry_subject.clone(), carry_predicate.clone())
874 {
875 push_expanded_triple(&mut kg, &s, &p, &tokens[0]);
876 }
877 } else {
878 carry_subject = None;
879 carry_predicate = None;
880 }
881 }
882 Some(';') => {
884 if tokens.len() >= 2 {
885 if let Some(s) = carry_subject.clone() {
886 let p = tokens[0].clone();
887 for obj in split_top_level_commas(&tokens[1..]) {
888 push_expanded_triple(&mut kg, &s, &p, &obj);
889 }
890 carry_predicate = Some(p);
891 }
892 } else {
893 carry_subject = None;
894 carry_predicate = None;
895 }
896 }
897 _ => {
899 if tokens.len() >= 3 {
900 let s = tokens[0].clone();
901 let p = tokens[1].clone();
902 for obj in split_top_level_commas(&tokens[2..]) {
903 push_expanded_triple(&mut kg, &s, &p, &obj);
904 }
905 carry_subject = Some(s);
906 carry_predicate = Some(p);
907 } else {
908 carry_subject = None;
909 carry_predicate = None;
910 }
911 }
912 }
913 prev_terminator = terminator;
914 }
915 }
916 let mut lines_iter = turtle.lines();
919 while let Some(line) = lines_iter.next() {
920 let l = line.trim();
921 if l.contains("a sh:NodeShape") {
922 let mut block = l.to_string();
924 if !l.ends_with('.') {
925 while let Some(next_line) = lines_iter.next() {
926 block.push(' ');
927 block.push_str(next_line.trim());
928 if next_line.trim().ends_with('.') {
929 break;
930 }
931 }
932 }
933
934 let normalized_block = block
936 .replace("http://www.w3.org/ns/shacl#", "sh:")
937 .replace("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:")
938 .replace("http://www.w3.org/2000/01/rdf-schema#", "rdfs:")
939 .replace("http://www.w3.org/2001/XMLSchema#", "xsd:")
940 .replace("http://domainforge.ai/sea#", "sea:");
941
942 let target_class = if let Some(pos) = normalized_block.find("sh:targetClass") {
944 let rest = &normalized_block[pos + "sh:targetClass".len()..];
945 let tok = rest
946 .split_whitespace()
947 .next()
948 .unwrap_or("")
949 .trim()
950 .trim_end_matches(';')
951 .to_string();
952 tok
953 } else {
954 continue; };
956
957 let mut shape = ShaclShape {
958 target_class,
959 properties: Vec::new(),
960 };
961
962 let mut start_idx = 0;
964 while let Some(idx) = normalized_block[start_idx..].find("sh:property") {
965 let local_idx = start_idx + idx;
966 if let Some(open_br) = normalized_block[local_idx..].find('[') {
968 let open_idx = local_idx + open_br + 1;
969 if let Some(close_br) = normalized_block[open_idx..].find(']') {
970 let close_idx = open_idx + close_br;
971 let prop_block = &normalized_block[open_idx..close_idx];
972 let mut path = String::new();
974 let mut datatype: Option<String> = None;
975 let mut min_count: Option<u32> = None;
976 let mut max_count: Option<u32> = None;
977 let mut min_exclusive: Option<String> = None;
978
979 for tok in prop_block.split(';') {
980 let tok = tok.trim();
981 if tok.is_empty() {
982 continue;
983 }
984 if let Some(s) = tok.strip_prefix("sh:path") {
985 path = s.trim().to_string();
986 } else if let Some(s) = tok.strip_prefix("sh:datatype") {
987 datatype = Some(s.trim().to_string());
988 } else if let Some(s) = tok.strip_prefix("sh:minCount") {
989 let val = s.trim();
990 if let Ok(n) = val.parse::<u32>() {
991 min_count = Some(n);
992 }
993 } else if let Some(s) = tok.strip_prefix("sh:maxCount") {
994 let val = s.trim();
995 if let Ok(n) = val.parse::<u32>() {
996 max_count = Some(n);
997 }
998 } else if let Some(s) = tok.strip_prefix("sh:minExclusive") {
999 let val = s.trim();
1000 min_exclusive = Some(val.to_string());
1001 }
1002 }
1003
1004 if !path.is_empty() {
1005 shape.properties.push(ShaclProperty {
1006 path,
1007 datatype,
1008 min_count,
1009 max_count,
1010 min_exclusive,
1011 });
1012 }
1013 start_idx = close_idx + 1;
1014 continue;
1015 }
1016 }
1017 start_idx = local_idx + 1;
1018 }
1019
1020 if !shape.properties.is_empty() {
1021 kg.shapes.push(shape);
1022 }
1023 }
1024 }
1025 let mut bnode_attrs: std::collections::HashMap<String, Vec<(String, String)>> =
1030 std::collections::HashMap::new();
1031 for t in &kg.triples {
1032 if t.subject.starts_with("_:") {
1033 bnode_attrs
1034 .entry(t.subject.clone())
1035 .or_default()
1036 .push((t.predicate.clone(), t.object.clone()));
1037 }
1038 }
1039 for t in &kg.triples {
1040 if t.predicate == "rdf:type" && t.object == "sh:NodeShape" {
1041 let target_class = match kg
1042 .triples
1043 .iter()
1044 .find(|x| x.subject == t.subject && x.predicate == "sh:targetClass")
1045 {
1046 Some(target) => target.object.clone(),
1047 None => continue,
1048 };
1049 let mut shape = ShaclShape {
1050 target_class,
1051 properties: Vec::new(),
1052 };
1053 for prop_ref in kg
1054 .triples
1055 .iter()
1056 .filter(|x| x.subject == t.subject && x.predicate == "sh:property")
1057 {
1058 if let Some(attrs) = bnode_attrs.get(&prop_ref.object) {
1059 if let Some(property) = parse_shape_property_attrs(attrs) {
1060 shape.properties.push(property);
1061 }
1062 }
1063 }
1064 if !shape.properties.is_empty()
1065 && !kg.shapes.iter().any(|s| {
1066 s.target_class == shape.target_class && s.properties == shape.properties
1067 })
1068 {
1069 kg.shapes.push(shape);
1070 }
1071 }
1072 }
1073 Ok(kg)
1074 }
1075
1076 pub fn to_graph(&self) -> Result<crate::graph::Graph, KgError> {
1088 use crate::graph::Graph;
1089 use crate::primitives::{Entity, Flow, Resource};
1090 use crate::units::unit_from_string;
1091 use rust_decimal::Decimal;
1092
1093 let mut graph = Graph::new();
1094
1095 let mut namespace_map: std::collections::HashMap<String, String> =
1096 std::collections::HashMap::new();
1097 for t in &self.triples {
1098 if t.predicate == "sea:namespace" {
1099 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1100 let name = percent_decode_str(name_encoded)
1101 .decode_utf8_lossy()
1102 .to_string();
1103 let ns = extract_literal_value(&t.object);
1104 namespace_map.insert(name, ns);
1105 }
1106 }
1107
1108 let mut unit_map: std::collections::HashMap<String, String> =
1109 std::collections::HashMap::new();
1110 for t in &self.triples {
1111 if t.predicate == "sea:unit" {
1112 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1113 let name = percent_decode_str(name_encoded)
1114 .decode_utf8_lossy()
1115 .to_string();
1116 let unit_str = extract_literal_value(&t.object);
1117 unit_map.insert(name, unit_str);
1118 }
1119 }
1120
1121 for t in &self.triples {
1122 if t.predicate == "rdf:type" && t.object == "sea:Entity" {
1123 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1124 let name = percent_decode_str(name_encoded)
1125 .decode_utf8_lossy()
1126 .to_string();
1127 let namespace = namespace_map
1128 .get(&name)
1129 .cloned()
1130 .unwrap_or_else(|| "default".to_string());
1131 let entity = Entity::new_with_namespace(name, namespace);
1132 graph
1133 .add_entity(entity)
1134 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1135 }
1136 if t.predicate == "rdf:type" && t.object == "sea:Resource" {
1137 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1138 let name = percent_decode_str(name_encoded)
1139 .decode_utf8_lossy()
1140 .to_string();
1141 let namespace = namespace_map
1142 .get(&name)
1143 .cloned()
1144 .unwrap_or_else(|| "default".to_string());
1145 let unit =
1146 unit_from_string(unit_map.get(&name).map(|s| s.as_str()).unwrap_or("units"));
1147 let resource = Resource::new_with_namespace(name, unit, namespace);
1148 graph
1149 .add_resource(resource)
1150 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1151 }
1152 }
1153
1154 for t in &self.triples {
1155 if t.predicate == "rdf:type" && t.object == "sea:Flow" {
1156 let flow_subject = t.subject.clone();
1157 let mut from: Option<String> = None;
1158 let mut to: Option<String> = None;
1159 let mut resource_name: Option<String> = None;
1160 let mut quantity: Option<Decimal> = None;
1161
1162 for p in &self.triples {
1163 if p.subject != flow_subject {
1164 continue;
1165 }
1166 match p.predicate.as_str() {
1167 "sea:from" => {
1168 from = Some(extract_local_name(&p.object));
1169 }
1170 "sea:to" => {
1171 to = Some(extract_local_name(&p.object));
1172 }
1173 "sea:hasResource" => {
1174 resource_name = Some(extract_local_name(&p.object));
1175 }
1176 "sea:quantity" => {
1177 let lexical = extract_literal_value(&p.object);
1178 let parsed = Decimal::from_str(&lexical).map_err(|e| {
1179 KgError::SerializationError(format!(
1180 "Invalid quantity literal '{}': {}",
1181 p.object, e
1182 ))
1183 })?;
1184 quantity = Some(parsed);
1185 }
1186 _ => {}
1187 }
1188 }
1189
1190 if let (Some(from_name), Some(to_name), Some(res_name), Some(quantity_val)) =
1191 (from, to, resource_name, quantity)
1192 {
1193 let from_decoded = percent_decode_str(&from_name)
1194 .decode_utf8_lossy()
1195 .to_string();
1196 let to_decoded = percent_decode_str(&to_name).decode_utf8_lossy().to_string();
1197 let res_decoded = percent_decode_str(&res_name)
1198 .decode_utf8_lossy()
1199 .to_string();
1200
1201 let from_id = graph.find_entity_by_name(&from_decoded).ok_or_else(|| {
1202 KgError::SerializationError(format!("Unknown entity: {}", from_decoded))
1203 })?;
1204 let to_id = graph.find_entity_by_name(&to_decoded).ok_or_else(|| {
1205 KgError::SerializationError(format!("Unknown entity: {}", to_decoded))
1206 })?;
1207 let res_id = graph.find_resource_by_name(&res_decoded).ok_or_else(|| {
1208 KgError::SerializationError(format!("Unknown resource: {}", res_decoded))
1209 })?;
1210
1211 let flow = Flow::new(res_id, from_id, to_id, quantity_val);
1212 graph
1213 .add_flow(flow)
1214 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1215 }
1216 }
1217 }
1218
1219 Ok(graph)
1220 }
1221
1222 pub fn validate_shacl(&self) -> Result<Vec<crate::policy::Violation>, KgError> {
1223 use crate::policy::{Severity, Violation};
1224
1225 if self.shapes.is_empty() {
1227 return Ok(Vec::new());
1228 }
1229
1230 let mut violations: Vec<Violation> = Vec::new();
1231
1232 fn parse_literal_and_datatype(obj: &str) -> (String, Option<String>) {
1235 let s = obj.trim();
1236 if !s.starts_with('"') {
1237 return (s.to_string(), None);
1238 }
1239
1240 let bytes = s.as_bytes();
1242 let mut end_quote = None;
1243 let mut i = 1;
1244 while i < bytes.len() {
1245 if bytes[i] == b'\\' {
1246 i += 2;
1248 continue;
1249 }
1250 if bytes[i] == b'"' {
1251 end_quote = Some(i);
1252 break;
1253 }
1254 i += 1;
1255 }
1256
1257 if let Some(end) = end_quote {
1258 let lex = &s[1..end];
1259 let rest = s[end + 1..].trim();
1260 let dtype = rest.strip_prefix("^^").map(|s| s.trim().to_string());
1261 (lex.to_string(), dtype)
1262 } else {
1263 (s.trim_matches('"').to_string(), None)
1265 }
1266 }
1267
1268 for shape in &self.shapes {
1270 match shape.target_class.as_str() {
1271 "sea:Flow" | "sea:Entity" | "sea:Resource" => {}
1272 other => {
1273 return Err(KgError::SerializationError(format!(
1274 "Unsupported SHACL target class: {}",
1275 other
1276 )))
1277 }
1278 }
1279
1280 let mut subjects: Vec<String> = Vec::new();
1282 for t in &self.triples {
1283 if t.predicate == "rdf:type" && t.object == shape.target_class {
1284 subjects.push(t.subject.clone());
1285 }
1286 }
1287
1288 for subject in subjects {
1289 for prop in &shape.properties {
1290 let count = self
1292 .triples
1293 .iter()
1294 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1295 .count() as u32;
1296
1297 if let Some(min) = prop.min_count {
1298 if count < min {
1299 let msg = format!(
1300 "SHACL violation: subject {} missing required property {} (min_count={} found={})",
1301 subject, prop.path, min, count
1302 );
1303 violations.push(Violation::new(format!("SHACL:{}", shape.target_class), msg, Severity::Error).with_context(serde_json::json!({"subject": subject, "predicate": prop.path, "expected_min": min, "found": count})));
1304 }
1305 }
1306
1307 if let Some(max) = prop.max_count {
1308 if count > max {
1309 let msg = format!(
1310 "SHACL violation: subject {} has {} occurrences of {} (max_count={} found={})",
1311 subject, count, prop.path, max, count
1312 );
1313 violations.push(Violation::new(format!("SHACL:{}", shape.target_class), msg, Severity::Error).with_context(serde_json::json!({"subject": subject, "predicate": prop.path, "expected_max": max, "found": count})));
1314 }
1315 }
1316
1317 if let Some(dt) = &prop.datatype {
1319 for tr in self
1320 .triples
1321 .iter()
1322 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1323 {
1324 let obj = tr.object.trim();
1325 let (_lex, dtype_opt) = parse_literal_and_datatype(obj);
1326 if let Some(dtype) = dtype_opt {
1328 if &dtype != dt {
1329 let msg = format!(
1330 "SHACL violation: subject {} property {} expected datatype {} but found {}",
1331 subject, prop.path, dt, dtype
1332 );
1333 violations.push(Violation::new(format!("SHACL:{}", shape.target_class), msg, Severity::Error).with_context(serde_json::json!({"subject": subject, "predicate": prop.path, "expected_type": dt, "found_type": dtype})));
1334 }
1335 } else if dt != "xsd:string" {
1336 let msg = format!(
1338 "SHACL violation: subject {} property {} expected datatype {} but found untyped literal {}",
1339 subject, prop.path, dt, obj
1340 );
1341 violations.push(Violation::new(format!("SHACL:{}", shape.target_class), msg, Severity::Error).with_context(serde_json::json!({"subject": subject, "predicate": prop.path, "expected_type": dt, "found": obj})));
1342 }
1343 }
1344 }
1345
1346 if let Some(min_ex) = &prop.min_exclusive {
1351 if prop.datatype.as_deref() == Some("xsd:decimal") {
1352 let threshold =
1353 rust_decimal::Decimal::from_str(&extract_literal_value(min_ex))
1354 .map_err(|e| {
1355 KgError::SerializationError(format!(
1356 "Invalid minExclusive threshold '{}': {}",
1357 min_ex, e
1358 ))
1359 })?;
1360 for tr in self
1361 .triples
1362 .iter()
1363 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1364 {
1365 let obj = tr.object.trim();
1366 let lex = extract_literal_value(obj);
1367 if let Ok(val) = rust_decimal::Decimal::from_str(&lex) {
1368 if val <= threshold {
1369 let msg = format!(
1370 "SHACL violation: subject {} property {} must be > {} but found {}",
1371 subject, prop.path, threshold, val
1372 );
1373 violations.push(Violation::new(format!("SHACL:{}", shape.target_class), msg, Severity::Error).with_context(serde_json::json!({"subject": subject, "predicate": prop.path, "threshold": threshold.to_string(), "found": val.to_string()})));
1374 }
1375 }
1376 }
1377 }
1378 }
1379 }
1380 }
1381 }
1382
1383 Ok(violations)
1384 }
1385
1386 pub fn to_rdf_xml(&self) -> String {
1387 let mut xml = String::new();
1388
1389 xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1390 xml.push_str("<rdf:RDF\n");
1391 xml.push_str(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
1392 xml.push_str(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n");
1395 xml.push_str(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n");
1396 xml.push_str(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n");
1397 xml.push_str(" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n");
1400 xml.push_str(" xmlns:sea=\"http://domainforge.ai/sea#\"\n");
1401 xml.push_str(" xmlns:sh=\"http://www.w3.org/ns/shacl#\">\n\n");
1402
1403 for triple in &self.triples {
1404 let subject = Self::clean_uri(&triple.subject);
1405 let predicate_name = triple.predicate.clone();
1409 let object = &triple.object;
1410
1411 if object.starts_with('"') {
1412 let (literal_value, suffix) = Self::parse_typed_literal(object);
1413 let escaped_value = Self::escape_xml(&literal_value);
1414
1415 xml.push_str(&format!(" <rdf:Description rdf:about=\"{}\">\n", subject));
1416
1417 match suffix {
1418 Some(TypedLiteralSuffix::Datatype(datatype)) => {
1419 let datatype_uri = Self::clean_uri(&datatype);
1420 xml.push_str(&format!(
1421 " <{} rdf:datatype=\"{}\">{}</{}>\n",
1422 predicate_name, datatype_uri, escaped_value, predicate_name
1423 ));
1424 }
1425 Some(TypedLiteralSuffix::Language(lang)) => {
1426 xml.push_str(&format!(
1427 " <{} xml:lang=\"{}\">{}</{}>\n",
1428 predicate_name, lang, escaped_value, predicate_name
1429 ));
1430 }
1431 None => {
1432 xml.push_str(&format!(
1433 " <{}>{}</{}>\n",
1434 predicate_name, escaped_value, predicate_name
1435 ));
1436 }
1437 }
1438
1439 xml.push_str(" </rdf:Description>\n\n");
1440 } else {
1441 let cleaned_object = Self::clean_uri(object);
1442 xml.push_str(&format!(" <rdf:Description rdf:about=\"{}\">\n", subject));
1443 xml.push_str(&format!(
1444 " <{} rdf:resource=\"{}\"/>\n",
1445 predicate_name, cleaned_object
1446 ));
1447 xml.push_str(" </rdf:Description>\n\n");
1448 }
1449 }
1450 xml.push('\n');
1451 for shape in &self.shapes {
1453 xml.push_str(&Self::write_shacl_shapes_xml(shape));
1454 }
1455
1456 xml.push_str("</rdf:RDF>\n");
1457 xml
1458 }
1459
1460 fn write_shacl_shapes_xml(shape: &ShaclShape) -> String {
1461 let mut xml = String::new();
1462 let shape_name = shape.target_class.replace("sea:", "") + "Shape";
1463 xml.push_str(&format!(
1464 " <sh:NodeShape rdf:about=\"http://domainforge.ai/sea#{}\">\n",
1465 shape_name
1466 ));
1467 xml.push_str(&format!(
1468 " <sh:targetClass rdf:resource=\"http://domainforge.ai/sea#{}\"/>\n",
1469 shape.target_class.replace("sea:", "")
1470 ));
1471 for prop in &shape.properties {
1472 xml.push_str(" <sh:property>\n");
1473 xml.push_str(" <rdf:Description>\n");
1474 let (ns, local) = if let Some(rest) = prop.path.strip_prefix("sea:") {
1476 ("http://domainforge.ai/sea#", rest)
1477 } else if let Some(rest) = prop.path.strip_prefix("rdfs:") {
1478 ("http://www.w3.org/2000/01/rdf-schema#", rest)
1479 } else {
1480 ("http://domainforge.ai/sea#", prop.path.as_str())
1481 };
1482 xml.push_str(&format!(
1483 " <sh:path rdf:resource=\"{}{}\"/>\n",
1484 ns, local
1485 ));
1486 if let Some(dt) = &prop.datatype {
1487 let dt_uri = if dt.starts_with("xsd:") {
1488 dt.replace("xsd:", "http://www.w3.org/2001/XMLSchema#")
1489 } else {
1490 dt.clone()
1491 };
1492 xml.push_str(&format!(
1493 " <sh:datatype rdf:resource=\"{}\"/>\n",
1494 dt_uri
1495 ));
1496 }
1497 if let Some(min) = prop.min_count {
1498 xml.push_str(&format!(" <sh:minCount>{}</sh:minCount>\n", min));
1499 }
1500 if let Some(max) = prop.max_count {
1501 xml.push_str(&format!(" <sh:maxCount>{}</sh:maxCount>\n", max));
1502 }
1503 if let Some(min_ex) = &prop.min_exclusive {
1504 xml.push_str(&format!(" <sh:minExclusive rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\">{}</sh:minExclusive>\n", min_ex));
1505 }
1506 xml.push_str(" </rdf:Description>\n");
1507 xml.push_str(" </sh:property>\n");
1508 }
1509 xml.push_str(" </sh:NodeShape>\n\n");
1510 xml
1511 }
1512
1513 pub fn escape_turtle_literal(input: &str) -> String {
1514 let mut escaped = String::with_capacity(input.len());
1515 for ch in input.chars() {
1516 match ch {
1517 '\\' => escaped.push_str("\\\\"),
1518 '"' => escaped.push_str("\\\""),
1519 '\n' => escaped.push_str("\\n"),
1520 '\r' => escaped.push_str("\\r"),
1521 '\t' => escaped.push_str("\\t"),
1522 '\x08' => escaped.push_str("\\b"), '\x0C' => escaped.push_str("\\f"), other => escaped.push(other),
1525 }
1526 }
1527 escaped
1528 }
1529
1530 fn uri_encode(s: &str) -> String {
1531 utf8_percent_encode(s, URI_ENCODE_SET).to_string()
1532 }
1533
1534 fn entity_instance_iri(instance: &Instance) -> String {
1543 format!("sea:instance_{}", Self::uri_encode(instance.name()))
1544 }
1545
1546 fn policy_iri(policy: &Policy) -> String {
1547 format!("sea:policy_{}", Self::uri_encode(&policy.name))
1548 }
1549
1550 fn xsd_datatype(field_type: &FieldType) -> &'static str {
1554 match field_type {
1555 FieldType::Scalar { scalar } => match scalar {
1556 ScalarType::String | ScalarType::Uuid => "xsd:string",
1557 ScalarType::Int => "xsd:integer",
1558 ScalarType::Decimal => "xsd:decimal",
1559 ScalarType::Bool => "xsd:boolean",
1560 ScalarType::Timestamp => "xsd:dateTime",
1561 },
1562 FieldType::Quantity { .. } => "xsd:decimal",
1563 FieldType::EntityRef { .. } | FieldType::Enum { .. } | FieldType::List { .. } => {
1564 "xsd:string"
1565 }
1566 }
1567 }
1568
1569 fn instance_field_object(value: &Value, declared: Option<&FieldType>) -> Option<String> {
1572 if value.is_null() {
1573 return None;
1574 }
1575
1576 let literal = match value {
1577 Value::String(text) => text.clone(),
1578 Value::Bool(flag) => flag.to_string(),
1579 Value::Number(number) => number.to_string(),
1580 other => other.to_string(),
1583 };
1584
1585 let datatype = match declared {
1586 Some(field_type) => Self::xsd_datatype(field_type),
1587 None => match value {
1588 Value::Bool(_) => "xsd:boolean",
1589 Value::Number(_) => "xsd:decimal",
1590 _ => "xsd:string",
1591 },
1592 };
1593
1594 if datatype == "xsd:integer" {
1604 if let Value::Number(number) = value {
1605 match number.as_f64() {
1606 Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18 => {
1607 return Some(format!(
1608 "\"{}\"^^xsd:integer",
1609 Self::escape_turtle_literal(&(f as i64).to_string())
1610 ));
1611 }
1612 _ => {
1613 return Some(format!(
1614 "\"{}\"^^xsd:string",
1615 Self::escape_turtle_literal(&literal)
1616 ));
1617 }
1618 }
1619 }
1620 }
1621
1622 if datatype == "xsd:decimal" && Self::validate_turtle_decimal(&literal).is_err() {
1626 return Some(format!(
1627 "\"{}\"^^xsd:string",
1628 Self::escape_turtle_literal(&literal)
1629 ));
1630 }
1631
1632 Some(format!(
1633 "\"{}\"^^{}",
1634 Self::escape_turtle_literal(&literal),
1635 datatype
1636 ))
1637 }
1638
1639 fn validate_turtle_decimal(decimal_str: &str) -> Result<(), String> {
1640 let trimmed = decimal_str.trim();
1642
1643 if trimmed
1645 .chars()
1646 .any(|ch| matches!(ch, '"' | '\'' | '\\' | '\n' | '\r' | '\t'))
1647 {
1648 return Err("Decimal contains invalid characters".to_string());
1649 }
1650
1651 if trimmed.is_empty() {
1653 return Err("Decimal is empty".to_string());
1654 }
1655
1656 let mut has_digit = false;
1658 let mut chars = trimmed.chars().peekable();
1659
1660 if matches!(chars.peek(), Some('+') | Some('-')) {
1662 chars.next();
1663 }
1664
1665 while let Some(ch) = chars.next() {
1667 if ch.is_ascii_digit() {
1668 has_digit = true;
1669 } else if ch == '.' {
1670 if !chars.next().is_some_and(|c| c.is_ascii_digit()) {
1672 return Err("Invalid decimal format".to_string());
1673 }
1674 for c in chars.by_ref() {
1675 if !c.is_ascii_digit() {
1676 return Err("Invalid decimal format".to_string());
1677 }
1678 }
1679 break;
1680 } else {
1681 return Err("Invalid decimal format".to_string());
1682 }
1683 }
1684
1685 if !has_digit {
1686 return Err("Invalid decimal format".to_string());
1687 }
1688
1689 Ok(())
1690 }
1691
1692 fn clean_uri(uri: &str) -> String {
1693 if uri.contains(':') {
1694 let parts: Vec<&str> = uri.splitn(2, ':').collect();
1695 if parts.len() == 2 {
1696 let (prefix, name) = (parts[0], parts[1]);
1697
1698 let standard_prefixes = [
1700 ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
1701 ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
1702 ("xsd", "http://www.w3.org/2001/XMLSchema#"),
1703 ("owl", "http://www.w3.org/2002/07/owl#"),
1704 ("sh", "http://www.w3.org/ns/shacl#"),
1705 ("sea", "http://domainforge.ai/sea#"),
1706 ];
1707
1708 for (std_prefix, namespace) in &standard_prefixes {
1709 if prefix == *std_prefix {
1710 return format!("{}{}", namespace, name);
1711 }
1712 }
1713
1714 return format!("http://domainforge.ai/{}#{}", prefix, name);
1716 }
1717 }
1718 uri.to_string()
1719 }
1720
1721 fn shorten_token(token: &str) -> String {
1722 let t = token.trim();
1723 let value = if t.starts_with('<') && t.ends_with('>') {
1725 &t[1..t.len() - 1]
1726 } else {
1727 t
1728 };
1729
1730 if value.contains("^^<http://www.w3.org/2001/XMLSchema#") {
1732 if let Some(pos) = value.find("^^<http://www.w3.org/2001/XMLSchema#") {
1734 let (lit, rest) = value.split_at(pos);
1735 if rest.contains("decimal") {
1736 return format!("{}^^xsd:decimal", lit.trim());
1737 } else if rest.contains("string") {
1738 return format!("{}^^xsd:string", lit.trim());
1739 }
1740 }
1741 }
1742
1743 let mappings = [
1745 ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:"),
1746 ("http://www.w3.org/2000/01/rdf-schema#", "rdfs:"),
1747 ("http://www.w3.org/2001/XMLSchema#", "xsd:"),
1748 ("http://www.w3.org/2002/07/owl#", "owl:"),
1749 ("http://www.w3.org/ns/shacl#", "sh:"),
1750 ("http://domainforge.ai/sea#", "sea:"),
1751 ("http://domainforge.ai/rdfs#", "rdfs:"),
1752 ];
1753
1754 for (ns, prefix) in &mappings {
1755 if let Some(stripped) = value.strip_prefix(ns) {
1756 return format!("{}{}", prefix, stripped);
1757 }
1758 }
1759
1760 t.to_string()
1762 }
1763
1764 pub fn escape_xml(input: &str) -> String {
1765 let mut escaped = String::with_capacity(input.len());
1766 for ch in input.chars() {
1767 match ch {
1768 '&' => escaped.push_str("&"),
1769 '<' => escaped.push_str("<"),
1770 '>' => escaped.push_str(">"),
1771 '"' => escaped.push_str("""),
1772 '\'' => escaped.push_str("'"),
1773 other => escaped.push(other),
1774 }
1775 }
1776 escaped
1777 }
1778
1779 fn parse_escaped_value<I>(chars: &mut I) -> String
1780 where
1781 I: Iterator<Item = char>,
1782 {
1783 let mut value = String::new();
1784 let mut escaped = false;
1785
1786 for ch in chars.by_ref() {
1787 if escaped {
1788 let resolved = match ch {
1789 'n' => '\n',
1790 't' => '\t',
1791 'r' => '\r',
1792 '"' => '"',
1793 '\\' => '\\',
1794 other => {
1795 value.push('\\');
1796 other
1797 }
1798 };
1799 value.push(resolved);
1800 escaped = false;
1801 continue;
1802 }
1803
1804 match ch {
1805 '\\' => escaped = true,
1806 '"' => break,
1807 other => value.push(other),
1808 }
1809 }
1810
1811 value
1812 }
1813
1814 fn parse_typed_literal(literal: &str) -> (String, Option<TypedLiteralSuffix>) {
1815 if !literal.starts_with('"') {
1816 return (literal.to_string(), None);
1817 }
1818
1819 let mut chars = literal.chars();
1820 chars.next();
1821 let value = Self::parse_escaped_value(&mut chars);
1822
1823 let remainder: String = chars.collect();
1824 let trimmed = remainder.trim();
1825
1826 let suffix = if let Some(rest) = trimmed.strip_prefix("^^") {
1827 let datatype = rest.trim();
1828 if datatype.is_empty() {
1829 None
1830 } else {
1831 Some(TypedLiteralSuffix::Datatype(datatype.to_string()))
1832 }
1833 } else if let Some(rest) = trimmed.strip_prefix('@') {
1834 let language = rest.trim();
1835 if language.is_empty() {
1836 None
1837 } else {
1838 Some(TypedLiteralSuffix::Language(language.to_string()))
1839 }
1840 } else {
1841 None
1842 };
1843
1844 (value, suffix)
1845 }
1846
1847 fn is_valid_rdf_term(term: &str) -> bool {
1850 if term.contains('"') || term.contains('<') || term.contains('>') || term.contains('\\') {
1852 return false;
1853 }
1854
1855 if term.chars().any(|c| c.is_control()) {
1857 return false;
1858 }
1859
1860 let colon_count = term.matches(':').count();
1863 if colon_count > 1 {
1864 return false;
1865 }
1866 if colon_count == 1 && (term.starts_with(':') || term.ends_with(':')) {
1867 return false;
1868 }
1869
1870 true
1871 }
1872}
1873
1874enum TypedLiteralSuffix {
1875 Datatype(String),
1876 Language(String),
1877}
1878
1879impl Default for KnowledgeGraph {
1880 fn default() -> Self {
1881 Self::new()
1882 }
1883}
1884
1885impl Graph {
1886 pub fn export_rdf(&self, format: &str) -> Result<String, KgError> {
1887 let kg = KnowledgeGraph::from_graph(self)?;
1888 match format {
1889 "turtle" => Ok(kg.to_turtle()),
1890 "rdf-xml" => Ok(kg.to_rdf_xml()),
1891 _ => Err(KgError::UnsupportedFormat(format.to_string())),
1892 }
1893 }
1894}
1895
1896#[cfg(test)]
1897mod tests {
1898 use super::*;
1899 use crate::primitives::{Entity, Flow, Resource};
1900 use rust_decimal::Decimal;
1901
1902 #[test]
1903 fn test_from_turtle_preserves_semicolons_in_iris() {
1904 let turtle = r#"<https://example.test/s> <https://example.test/p;v=1> <https://example.test/o;v=2> ; sea:label "a;b" ."#;
1905 let kg = KnowledgeGraph::from_turtle(turtle).unwrap();
1906
1907 assert_eq!(kg.triples.len(), 2);
1908 assert_eq!(kg.triples[0].predicate, "<https://example.test/p;v=1>");
1909 assert_eq!(kg.triples[0].object, "<https://example.test/o;v=2>");
1910 assert_eq!(kg.triples[1].predicate, "sea:label");
1911 assert_eq!(kg.triples[1].object, "\"a;b\"");
1912 }
1913
1914 #[test]
1915 fn test_from_turtle_preserves_commas_in_iri_objects() {
1916 let turtle = r#"<https://example.test/s> sea:link <https://example.test/a,b>, <https://example.test/c,d>, "e,f" ."#;
1917 let kg = KnowledgeGraph::from_turtle(turtle).unwrap();
1918
1919 let objects: Vec<&str> = kg
1920 .triples
1921 .iter()
1922 .map(|triple| triple.object.as_str())
1923 .collect();
1924 assert_eq!(
1925 objects,
1926 [
1927 "<https://example.test/a,b>",
1928 "<https://example.test/c,d>",
1929 "\"e,f\"",
1930 ]
1931 );
1932 }
1933
1934 #[test]
1935 fn test_export_to_rdf_turtle() {
1936 let mut graph = Graph::new();
1937
1938 let entity1 = Entity::new_with_namespace("Supplier", "supply_chain");
1939 let entity2 = Entity::new_with_namespace("Manufacturer", "supply_chain");
1940 let resource = Resource::new_with_namespace(
1941 "Parts",
1942 crate::units::unit_from_string("kg"),
1943 "supply_chain",
1944 );
1945
1946 let entity1_id = entity1.id().clone();
1947 let entity2_id = entity2.id().clone();
1948 let resource_id = resource.id().clone();
1949
1950 graph.add_entity(entity1).unwrap();
1951 graph.add_entity(entity2).unwrap();
1952 graph.add_resource(resource).unwrap();
1953
1954 #[allow(deprecated)]
1955 let flow = Flow::new(resource_id, entity1_id, entity2_id, Decimal::new(100, 0));
1956 graph.add_flow(flow).unwrap();
1957
1958 let rdf_turtle = graph.export_rdf("turtle").unwrap();
1959
1960 assert!(rdf_turtle.contains("sea:Entity"));
1961 assert!(rdf_turtle.contains("sea:hasResource"));
1962 assert!(rdf_turtle.contains("@prefix"));
1963 }
1964
1965 #[test]
1966 fn test_export_to_rdf_xml() {
1967 let mut graph = Graph::new();
1968
1969 let entity = Entity::new_with_namespace("TestEntity", "default".to_string());
1970 graph.add_entity(entity).unwrap();
1971
1972 let rdf_xml = graph.export_rdf("rdf-xml").unwrap();
1973
1974 assert!(rdf_xml.contains("<?xml"));
1975 assert!(rdf_xml.contains("rdf:RDF"));
1976 }
1977
1978 #[test]
1979 fn test_unsupported_format() {
1980 let graph = Graph::new();
1981 let result = graph.export_rdf("json-ld");
1982
1983 assert!(result.is_err());
1984 assert!(matches!(result.unwrap_err(), KgError::UnsupportedFormat(_)));
1985 }
1986
1987 #[test]
1988 fn test_export_rdf_turtle_encodes_special_characters_and_literals() {
1989 let mut graph = Graph::new();
1990
1991 let entity_space = Entity::new_with_namespace("Entity With Space", "default".to_string());
1992 let entity_colon = Entity::new_with_namespace("Entity:Colon", "default".to_string());
1993 let entity_slash = Entity::new_with_namespace("Entity/Slash", "default".to_string());
1994 let entity_hash = Entity::new_with_namespace("Entity#Hash", "default".to_string());
1995
1996 graph.add_entity(entity_space.clone()).unwrap();
1997 graph.add_entity(entity_colon.clone()).unwrap();
1998 graph.add_entity(entity_slash.clone()).unwrap();
1999 graph.add_entity(entity_hash.clone()).unwrap();
2000
2001 let resource = Resource::new_with_namespace(
2002 "Resource:Name/Hash",
2003 crate::units::unit_from_string("units"),
2004 "default".to_string(),
2005 );
2006 let resource_id = resource.id().clone();
2007 graph.add_resource(resource).unwrap();
2008
2009 let flow = Flow::new(
2010 resource_id,
2011 entity_space.id().clone(),
2012 entity_colon.id().clone(),
2013 Decimal::new(42, 0),
2014 );
2015 graph.add_flow(flow).unwrap();
2016
2017 let turtle = graph.export_rdf("turtle").unwrap();
2018 assert!(turtle.contains("sea:Entity%20With%20Space"));
2019 assert!(turtle.contains("sea:Entity%3AColon"));
2020 assert!(turtle.contains("sea:Entity%2FSlash"));
2021 assert!(turtle.contains("sea:Entity%23Hash"));
2022 assert!(turtle.contains("sea:Resource%3AName%2FHash"));
2023 assert!(turtle.contains("\"42\"^^xsd:decimal"));
2024 }
2025
2026 #[test]
2027 fn test_rdf_xml_escapes_special_literals_and_language_tags() {
2028 let mut kg = KnowledgeGraph::new();
2029
2030 kg.triples.push(Triple {
2031 subject: "sea:testEntity".to_string(),
2032 predicate: "sea:hasNumericValue".to_string(),
2033 object: "\"100\"^^xsd:decimal".to_string(),
2034 });
2035 kg.triples.push(Triple {
2036 subject: "sea:testEntity".to_string(),
2037 predicate: "sea:description".to_string(),
2038 object: "\"Hello & <World>\"@en".to_string(),
2039 });
2040
2041 let xml = kg.to_rdf_xml();
2042 assert!(xml.contains("rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\""));
2043 assert!(xml.contains(">100<"));
2044 assert!(xml.contains("xml:lang=\"en\""));
2045 assert!(xml.contains("&"));
2046 assert!(xml.contains("<"));
2047 assert!(xml.contains(">"));
2048 }
2049}