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> {
1090 use crate::graph::Graph;
1091 use crate::primitives::{Entity, Flow, Resource};
1092 use crate::units::unit_from_string;
1093 use rust_decimal::Decimal;
1094
1095 let mut graph = Graph::new();
1096
1097 let mut namespace_map: std::collections::HashMap<String, String> =
1098 std::collections::HashMap::new();
1099 for t in &self.triples {
1100 if t.predicate == "sea:namespace" {
1101 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1102 let name = percent_decode_str(name_encoded)
1103 .decode_utf8_lossy()
1104 .to_string();
1105 let ns = extract_literal_value(&t.object);
1106 namespace_map.insert(name, ns);
1107 }
1108 }
1109
1110 let mut unit_map: std::collections::HashMap<String, String> =
1111 std::collections::HashMap::new();
1112 for t in &self.triples {
1113 if t.predicate == "sea:unit" {
1114 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1115 let name = percent_decode_str(name_encoded)
1116 .decode_utf8_lossy()
1117 .to_string();
1118 let unit_str = extract_literal_value(&t.object);
1119 unit_map.insert(name, unit_str);
1120 }
1121 }
1122
1123 for t in &self.triples {
1124 if t.predicate == "rdf:type" && t.object == "sea:Entity" {
1125 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1126 let name = percent_decode_str(name_encoded)
1127 .decode_utf8_lossy()
1128 .to_string();
1129 let namespace = namespace_map
1130 .get(&name)
1131 .cloned()
1132 .unwrap_or_else(|| "default".to_string());
1133 let entity = Entity::new_with_namespace(name, namespace);
1134 graph
1135 .add_entity(entity)
1136 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1137 }
1138 if t.predicate == "rdf:type" && t.object == "sea:Resource" {
1139 let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
1140 let name = percent_decode_str(name_encoded)
1141 .decode_utf8_lossy()
1142 .to_string();
1143 let namespace = namespace_map
1144 .get(&name)
1145 .cloned()
1146 .unwrap_or_else(|| "default".to_string());
1147 let unit =
1148 unit_from_string(unit_map.get(&name).map(|s| s.as_str()).unwrap_or("units"));
1149 let resource = Resource::new_with_namespace(name, unit, namespace);
1150 graph
1151 .add_resource(resource)
1152 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1153 }
1154 }
1155
1156 for t in &self.triples {
1157 if t.predicate == "rdf:type" && t.object == "sea:Flow" {
1158 let flow_subject = t.subject.clone();
1159 let mut from: Option<String> = None;
1160 let mut to: Option<String> = None;
1161 let mut resource_name: Option<String> = None;
1162 let mut quantity: Option<Decimal> = None;
1163
1164 for p in &self.triples {
1165 if p.subject != flow_subject {
1166 continue;
1167 }
1168 match p.predicate.as_str() {
1169 "sea:from" => {
1170 from = Some(extract_local_name(&p.object));
1171 }
1172 "sea:to" => {
1173 to = Some(extract_local_name(&p.object));
1174 }
1175 "sea:hasResource" => {
1176 resource_name = Some(extract_local_name(&p.object));
1177 }
1178 "sea:quantity" => {
1179 let lexical = extract_literal_value(&p.object);
1180 let parsed = Decimal::from_str(&lexical).map_err(|e| {
1181 KgError::SerializationError(format!(
1182 "Invalid quantity literal '{}': {}",
1183 p.object, e
1184 ))
1185 })?;
1186 quantity = Some(parsed);
1187 }
1188 _ => {}
1189 }
1190 }
1191
1192 if let (Some(from_name), Some(to_name), Some(res_name), Some(quantity_val)) =
1193 (from, to, resource_name, quantity)
1194 {
1195 let from_decoded = percent_decode_str(&from_name)
1196 .decode_utf8_lossy()
1197 .to_string();
1198 let to_decoded = percent_decode_str(&to_name).decode_utf8_lossy().to_string();
1199 let res_decoded = percent_decode_str(&res_name)
1200 .decode_utf8_lossy()
1201 .to_string();
1202
1203 let from_id = graph.find_entity_by_name(&from_decoded).ok_or_else(|| {
1204 KgError::SerializationError(format!("Unknown entity: {}", from_decoded))
1205 })?;
1206 let to_id = graph.find_entity_by_name(&to_decoded).ok_or_else(|| {
1207 KgError::SerializationError(format!("Unknown entity: {}", to_decoded))
1208 })?;
1209 let res_id = graph.find_resource_by_name(&res_decoded).ok_or_else(|| {
1210 KgError::SerializationError(format!("Unknown resource: {}", res_decoded))
1211 })?;
1212
1213 let flow = Flow::new(res_id, from_id, to_id, quantity_val);
1214 graph
1215 .add_flow(flow)
1216 .map_err(|e| KgError::SerializationError(e.to_string()))?;
1217 }
1218 }
1219 }
1220
1221 Ok(graph)
1222 }
1223
1224 pub fn validate_shacl(&self) -> Result<Vec<crate::policy::Violation>, KgError> {
1225 use crate::policy::{Severity, Violation};
1226
1227 if self.shapes.is_empty() {
1229 return Ok(Vec::new());
1230 }
1231
1232 let mut violations: Vec<Violation> = Vec::new();
1233
1234 fn parse_literal_and_datatype(obj: &str) -> (String, Option<String>) {
1237 let s = obj.trim();
1238 if !s.starts_with('"') {
1239 return (s.to_string(), None);
1240 }
1241
1242 let bytes = s.as_bytes();
1244 let mut end_quote = None;
1245 let mut i = 1;
1246 while i < bytes.len() {
1247 if bytes[i] == b'\\' {
1248 i += 2;
1250 continue;
1251 }
1252 if bytes[i] == b'"' {
1253 end_quote = Some(i);
1254 break;
1255 }
1256 i += 1;
1257 }
1258
1259 if let Some(end) = end_quote {
1260 let lex = &s[1..end];
1261 let rest = s[end + 1..].trim();
1262 let dtype = rest.strip_prefix("^^").map(|s| s.trim().to_string());
1263 (lex.to_string(), dtype)
1264 } else {
1265 (s.trim_matches('"').to_string(), None)
1267 }
1268 }
1269
1270 for shape in &self.shapes {
1272 match shape.target_class.as_str() {
1273 "sea:Flow" | "sea:Entity" | "sea:Resource" => {}
1274 other => {
1275 return Err(KgError::SerializationError(format!(
1276 "Unsupported SHACL target class: {}",
1277 other
1278 )))
1279 }
1280 }
1281
1282 let mut subjects: Vec<String> = Vec::new();
1284 for t in &self.triples {
1285 if t.predicate == "rdf:type" && t.object == shape.target_class {
1286 subjects.push(t.subject.clone());
1287 }
1288 }
1289
1290 for subject in subjects {
1291 for prop in &shape.properties {
1292 let count = self
1294 .triples
1295 .iter()
1296 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1297 .count() as u32;
1298
1299 if let Some(min) = prop.min_count {
1300 if count < min {
1301 let msg = format!(
1302 "SHACL violation: subject {} missing required property {} (min_count={} found={})",
1303 subject, prop.path, min, count
1304 );
1305 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})));
1306 }
1307 }
1308
1309 if let Some(max) = prop.max_count {
1310 if count > max {
1311 let msg = format!(
1312 "SHACL violation: subject {} has {} occurrences of {} (max_count={} found={})",
1313 subject, count, prop.path, max, count
1314 );
1315 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})));
1316 }
1317 }
1318
1319 if let Some(dt) = &prop.datatype {
1321 for tr in self
1322 .triples
1323 .iter()
1324 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1325 {
1326 let obj = tr.object.trim();
1327 let (_lex, dtype_opt) = parse_literal_and_datatype(obj);
1328 if let Some(dtype) = dtype_opt {
1330 if &dtype != dt {
1331 let msg = format!(
1332 "SHACL violation: subject {} property {} expected datatype {} but found {}",
1333 subject, prop.path, dt, dtype
1334 );
1335 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})));
1336 }
1337 } else if dt != "xsd:string" {
1338 let msg = format!(
1340 "SHACL violation: subject {} property {} expected datatype {} but found untyped literal {}",
1341 subject, prop.path, dt, obj
1342 );
1343 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})));
1344 }
1345 }
1346 }
1347
1348 if let Some(min_ex) = &prop.min_exclusive {
1353 if prop.datatype.as_deref() == Some("xsd:decimal") {
1354 let threshold =
1355 rust_decimal::Decimal::from_str(&extract_literal_value(min_ex))
1356 .map_err(|e| {
1357 KgError::SerializationError(format!(
1358 "Invalid minExclusive threshold '{}': {}",
1359 min_ex, e
1360 ))
1361 })?;
1362 for tr in self
1363 .triples
1364 .iter()
1365 .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1366 {
1367 let obj = tr.object.trim();
1368 let lex = extract_literal_value(obj);
1369 if let Ok(val) = rust_decimal::Decimal::from_str(&lex) {
1370 if val <= threshold {
1371 let msg = format!(
1372 "SHACL violation: subject {} property {} must be > {} but found {}",
1373 subject, prop.path, threshold, val
1374 );
1375 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()})));
1376 }
1377 }
1378 }
1379 }
1380 }
1381 }
1382 }
1383 }
1384
1385 Ok(violations)
1386 }
1387
1388 pub fn to_rdf_xml(&self) -> String {
1389 let mut xml = String::new();
1390
1391 xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1392 xml.push_str("<rdf:RDF\n");
1393 xml.push_str(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
1394 xml.push_str(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n");
1397 xml.push_str(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n");
1398 xml.push_str(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n");
1399 xml.push_str(" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n");
1402 xml.push_str(" xmlns:sea=\"http://domainforge.ai/sea#\"\n");
1403 xml.push_str(" xmlns:sh=\"http://www.w3.org/ns/shacl#\">\n\n");
1404
1405 for triple in &self.triples {
1406 let subject = Self::clean_uri(&triple.subject);
1407 let predicate_name = triple.predicate.clone();
1411 let object = &triple.object;
1412
1413 if object.starts_with('"') {
1414 let (literal_value, suffix) = Self::parse_typed_literal(object);
1415 let escaped_value = Self::escape_xml(&literal_value);
1416
1417 xml.push_str(&format!(" <rdf:Description rdf:about=\"{}\">\n", subject));
1418
1419 match suffix {
1420 Some(TypedLiteralSuffix::Datatype(datatype)) => {
1421 let datatype_uri = Self::clean_uri(&datatype);
1422 xml.push_str(&format!(
1423 " <{} rdf:datatype=\"{}\">{}</{}>\n",
1424 predicate_name, datatype_uri, escaped_value, predicate_name
1425 ));
1426 }
1427 Some(TypedLiteralSuffix::Language(lang)) => {
1428 xml.push_str(&format!(
1429 " <{} xml:lang=\"{}\">{}</{}>\n",
1430 predicate_name, lang, escaped_value, predicate_name
1431 ));
1432 }
1433 None => {
1434 xml.push_str(&format!(
1435 " <{}>{}</{}>\n",
1436 predicate_name, escaped_value, predicate_name
1437 ));
1438 }
1439 }
1440
1441 xml.push_str(" </rdf:Description>\n\n");
1442 } else {
1443 let cleaned_object = Self::clean_uri(object);
1444 xml.push_str(&format!(" <rdf:Description rdf:about=\"{}\">\n", subject));
1445 xml.push_str(&format!(
1446 " <{} rdf:resource=\"{}\"/>\n",
1447 predicate_name, cleaned_object
1448 ));
1449 xml.push_str(" </rdf:Description>\n\n");
1450 }
1451 }
1452 xml.push('\n');
1453 for shape in &self.shapes {
1455 xml.push_str(&Self::write_shacl_shapes_xml(shape));
1456 }
1457
1458 xml.push_str("</rdf:RDF>\n");
1459 xml
1460 }
1461
1462 fn write_shacl_shapes_xml(shape: &ShaclShape) -> String {
1463 let mut xml = String::new();
1464 let shape_name = shape.target_class.replace("sea:", "") + "Shape";
1465 xml.push_str(&format!(
1466 " <sh:NodeShape rdf:about=\"http://domainforge.ai/sea#{}\">\n",
1467 shape_name
1468 ));
1469 xml.push_str(&format!(
1470 " <sh:targetClass rdf:resource=\"http://domainforge.ai/sea#{}\"/>\n",
1471 shape.target_class.replace("sea:", "")
1472 ));
1473 for prop in &shape.properties {
1474 xml.push_str(" <sh:property>\n");
1475 xml.push_str(" <rdf:Description>\n");
1476 let (ns, local) = if let Some(rest) = prop.path.strip_prefix("sea:") {
1478 ("http://domainforge.ai/sea#", rest)
1479 } else if let Some(rest) = prop.path.strip_prefix("rdfs:") {
1480 ("http://www.w3.org/2000/01/rdf-schema#", rest)
1481 } else {
1482 ("http://domainforge.ai/sea#", prop.path.as_str())
1483 };
1484 xml.push_str(&format!(
1485 " <sh:path rdf:resource=\"{}{}\"/>\n",
1486 ns, local
1487 ));
1488 if let Some(dt) = &prop.datatype {
1489 let dt_uri = if dt.starts_with("xsd:") {
1490 dt.replace("xsd:", "http://www.w3.org/2001/XMLSchema#")
1491 } else {
1492 dt.clone()
1493 };
1494 xml.push_str(&format!(
1495 " <sh:datatype rdf:resource=\"{}\"/>\n",
1496 dt_uri
1497 ));
1498 }
1499 if let Some(min) = prop.min_count {
1500 xml.push_str(&format!(" <sh:minCount>{}</sh:minCount>\n", min));
1501 }
1502 if let Some(max) = prop.max_count {
1503 xml.push_str(&format!(" <sh:maxCount>{}</sh:maxCount>\n", max));
1504 }
1505 if let Some(min_ex) = &prop.min_exclusive {
1506 xml.push_str(&format!(" <sh:minExclusive rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\">{}</sh:minExclusive>\n", min_ex));
1507 }
1508 xml.push_str(" </rdf:Description>\n");
1509 xml.push_str(" </sh:property>\n");
1510 }
1511 xml.push_str(" </sh:NodeShape>\n\n");
1512 xml
1513 }
1514
1515 pub fn escape_turtle_literal(input: &str) -> String {
1516 let mut escaped = String::with_capacity(input.len());
1517 for ch in input.chars() {
1518 match ch {
1519 '\\' => escaped.push_str("\\\\"),
1520 '"' => escaped.push_str("\\\""),
1521 '\n' => escaped.push_str("\\n"),
1522 '\r' => escaped.push_str("\\r"),
1523 '\t' => escaped.push_str("\\t"),
1524 '\x08' => escaped.push_str("\\b"), '\x0C' => escaped.push_str("\\f"), other => escaped.push(other),
1527 }
1528 }
1529 escaped
1530 }
1531
1532 fn uri_encode(s: &str) -> String {
1533 utf8_percent_encode(s, URI_ENCODE_SET).to_string()
1534 }
1535
1536 fn entity_instance_iri(instance: &Instance) -> String {
1545 format!("sea:instance_{}", Self::uri_encode(instance.name()))
1546 }
1547
1548 fn policy_iri(policy: &Policy) -> String {
1549 format!("sea:policy_{}", Self::uri_encode(&policy.name))
1550 }
1551
1552 fn xsd_datatype(field_type: &FieldType) -> &'static str {
1556 match field_type {
1557 FieldType::Scalar { scalar } => match scalar {
1558 ScalarType::String | ScalarType::Uuid => "xsd:string",
1559 ScalarType::Int => "xsd:integer",
1560 ScalarType::Decimal => "xsd:decimal",
1561 ScalarType::Bool => "xsd:boolean",
1562 ScalarType::Timestamp => "xsd:dateTime",
1563 },
1564 FieldType::Quantity { .. } => "xsd:decimal",
1565 FieldType::EntityRef { .. } | FieldType::Enum { .. } | FieldType::List { .. } => {
1566 "xsd:string"
1567 }
1568 }
1569 }
1570
1571 fn instance_field_object(value: &Value, declared: Option<&FieldType>) -> Option<String> {
1574 if value.is_null() {
1575 return None;
1576 }
1577
1578 let literal = match value {
1579 Value::String(text) => text.clone(),
1580 Value::Bool(flag) => flag.to_string(),
1581 Value::Number(number) => number.to_string(),
1582 other => other.to_string(),
1585 };
1586
1587 let datatype = match declared {
1588 Some(field_type) => Self::xsd_datatype(field_type),
1589 None => match value {
1590 Value::Bool(_) => "xsd:boolean",
1591 Value::Number(_) => "xsd:decimal",
1592 _ => "xsd:string",
1593 },
1594 };
1595
1596 if datatype == "xsd:integer" {
1606 if let Value::Number(number) = value {
1607 match number.as_f64() {
1608 Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18 => {
1609 return Some(format!(
1610 "\"{}\"^^xsd:integer",
1611 Self::escape_turtle_literal(&(f as i64).to_string())
1612 ));
1613 }
1614 _ => {
1615 return Some(format!(
1616 "\"{}\"^^xsd:string",
1617 Self::escape_turtle_literal(&literal)
1618 ));
1619 }
1620 }
1621 }
1622 }
1623
1624 if datatype == "xsd:decimal" && Self::validate_turtle_decimal(&literal).is_err() {
1628 return Some(format!(
1629 "\"{}\"^^xsd:string",
1630 Self::escape_turtle_literal(&literal)
1631 ));
1632 }
1633
1634 Some(format!(
1635 "\"{}\"^^{}",
1636 Self::escape_turtle_literal(&literal),
1637 datatype
1638 ))
1639 }
1640
1641 fn validate_turtle_decimal(decimal_str: &str) -> Result<(), String> {
1642 let trimmed = decimal_str.trim();
1644
1645 if trimmed
1647 .chars()
1648 .any(|ch| matches!(ch, '"' | '\'' | '\\' | '\n' | '\r' | '\t'))
1649 {
1650 return Err("Decimal contains invalid characters".to_string());
1651 }
1652
1653 if trimmed.is_empty() {
1655 return Err("Decimal is empty".to_string());
1656 }
1657
1658 let mut has_digit = false;
1660 let mut chars = trimmed.chars().peekable();
1661
1662 if matches!(chars.peek(), Some('+') | Some('-')) {
1664 chars.next();
1665 }
1666
1667 while let Some(ch) = chars.next() {
1669 if ch.is_ascii_digit() {
1670 has_digit = true;
1671 } else if ch == '.' {
1672 if !chars.next().is_some_and(|c| c.is_ascii_digit()) {
1674 return Err("Invalid decimal format".to_string());
1675 }
1676 for c in chars.by_ref() {
1677 if !c.is_ascii_digit() {
1678 return Err("Invalid decimal format".to_string());
1679 }
1680 }
1681 break;
1682 } else {
1683 return Err("Invalid decimal format".to_string());
1684 }
1685 }
1686
1687 if !has_digit {
1688 return Err("Invalid decimal format".to_string());
1689 }
1690
1691 Ok(())
1692 }
1693
1694 fn clean_uri(uri: &str) -> String {
1695 if uri.contains(':') {
1696 let parts: Vec<&str> = uri.splitn(2, ':').collect();
1697 if parts.len() == 2 {
1698 let (prefix, name) = (parts[0], parts[1]);
1699
1700 let standard_prefixes = [
1702 ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
1703 ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
1704 ("xsd", "http://www.w3.org/2001/XMLSchema#"),
1705 ("owl", "http://www.w3.org/2002/07/owl#"),
1706 ("sh", "http://www.w3.org/ns/shacl#"),
1707 ("sea", "http://domainforge.ai/sea#"),
1708 ];
1709
1710 for (std_prefix, namespace) in &standard_prefixes {
1711 if prefix == *std_prefix {
1712 return format!("{}{}", namespace, name);
1713 }
1714 }
1715
1716 return format!("http://domainforge.ai/{}#{}", prefix, name);
1718 }
1719 }
1720 uri.to_string()
1721 }
1722
1723 fn shorten_token(token: &str) -> String {
1724 let t = token.trim();
1725 let value = if t.starts_with('<') && t.ends_with('>') {
1727 &t[1..t.len() - 1]
1728 } else {
1729 t
1730 };
1731
1732 if value.contains("^^<http://www.w3.org/2001/XMLSchema#") {
1734 if let Some(pos) = value.find("^^<http://www.w3.org/2001/XMLSchema#") {
1736 let (lit, rest) = value.split_at(pos);
1737 if rest.contains("decimal") {
1738 return format!("{}^^xsd:decimal", lit.trim());
1739 } else if rest.contains("string") {
1740 return format!("{}^^xsd:string", lit.trim());
1741 }
1742 }
1743 }
1744
1745 let mappings = [
1747 ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:"),
1748 ("http://www.w3.org/2000/01/rdf-schema#", "rdfs:"),
1749 ("http://www.w3.org/2001/XMLSchema#", "xsd:"),
1750 ("http://www.w3.org/2002/07/owl#", "owl:"),
1751 ("http://www.w3.org/ns/shacl#", "sh:"),
1752 ("http://domainforge.ai/sea#", "sea:"),
1753 ("http://domainforge.ai/rdfs#", "rdfs:"),
1754 ];
1755
1756 for (ns, prefix) in &mappings {
1757 if let Some(stripped) = value.strip_prefix(ns) {
1758 return format!("{}{}", prefix, stripped);
1759 }
1760 }
1761
1762 t.to_string()
1764 }
1765
1766 pub fn escape_xml(input: &str) -> String {
1767 let mut escaped = String::with_capacity(input.len());
1768 for ch in input.chars() {
1769 match ch {
1770 '&' => escaped.push_str("&"),
1771 '<' => escaped.push_str("<"),
1772 '>' => escaped.push_str(">"),
1773 '"' => escaped.push_str("""),
1774 '\'' => escaped.push_str("'"),
1775 other => escaped.push(other),
1776 }
1777 }
1778 escaped
1779 }
1780
1781 fn parse_escaped_value<I>(chars: &mut I) -> String
1782 where
1783 I: Iterator<Item = char>,
1784 {
1785 let mut value = String::new();
1786 let mut escaped = false;
1787
1788 for ch in chars.by_ref() {
1789 if escaped {
1790 let resolved = match ch {
1791 'n' => '\n',
1792 't' => '\t',
1793 'r' => '\r',
1794 '"' => '"',
1795 '\\' => '\\',
1796 other => {
1797 value.push('\\');
1798 other
1799 }
1800 };
1801 value.push(resolved);
1802 escaped = false;
1803 continue;
1804 }
1805
1806 match ch {
1807 '\\' => escaped = true,
1808 '"' => break,
1809 other => value.push(other),
1810 }
1811 }
1812
1813 value
1814 }
1815
1816 fn parse_typed_literal(literal: &str) -> (String, Option<TypedLiteralSuffix>) {
1817 if !literal.starts_with('"') {
1818 return (literal.to_string(), None);
1819 }
1820
1821 let mut chars = literal.chars();
1822 chars.next();
1823 let value = Self::parse_escaped_value(&mut chars);
1824
1825 let remainder: String = chars.collect();
1826 let trimmed = remainder.trim();
1827
1828 let suffix = if let Some(rest) = trimmed.strip_prefix("^^") {
1829 let datatype = rest.trim();
1830 if datatype.is_empty() {
1831 None
1832 } else {
1833 Some(TypedLiteralSuffix::Datatype(datatype.to_string()))
1834 }
1835 } else if let Some(rest) = trimmed.strip_prefix('@') {
1836 let language = rest.trim();
1837 if language.is_empty() {
1838 None
1839 } else {
1840 Some(TypedLiteralSuffix::Language(language.to_string()))
1841 }
1842 } else {
1843 None
1844 };
1845
1846 (value, suffix)
1847 }
1848
1849 fn is_valid_rdf_term(term: &str) -> bool {
1852 if term.contains('"') || term.contains('<') || term.contains('>') || term.contains('\\') {
1854 return false;
1855 }
1856
1857 if term.chars().any(|c| c.is_control()) {
1859 return false;
1860 }
1861
1862 let colon_count = term.matches(':').count();
1865 if colon_count > 1 {
1866 return false;
1867 }
1868 if colon_count == 1 && (term.starts_with(':') || term.ends_with(':')) {
1869 return false;
1870 }
1871
1872 true
1873 }
1874}
1875
1876enum TypedLiteralSuffix {
1877 Datatype(String),
1878 Language(String),
1879}
1880
1881impl Default for KnowledgeGraph {
1882 fn default() -> Self {
1883 Self::new()
1884 }
1885}
1886
1887impl Graph {
1888 pub fn export_rdf(&self, format: &str) -> Result<String, KgError> {
1889 let kg = KnowledgeGraph::from_graph(self)?;
1890 match format {
1891 "turtle" => Ok(kg.to_turtle()),
1892 "rdf-xml" => Ok(kg.to_rdf_xml()),
1893 _ => Err(KgError::UnsupportedFormat(format.to_string())),
1894 }
1895 }
1896}
1897
1898#[cfg(test)]
1899mod tests {
1900 use super::*;
1901 use crate::primitives::{Entity, Flow, Resource};
1902 use rust_decimal::Decimal;
1903
1904 #[test]
1905 fn test_from_turtle_preserves_semicolons_in_iris() {
1906 let turtle = r#"<https://example.test/s> <https://example.test/p;v=1> <https://example.test/o;v=2> ; sea:label "a;b" ."#;
1907 let kg = KnowledgeGraph::from_turtle(turtle).unwrap();
1908
1909 assert_eq!(kg.triples.len(), 2);
1910 assert_eq!(kg.triples[0].predicate, "<https://example.test/p;v=1>");
1911 assert_eq!(kg.triples[0].object, "<https://example.test/o;v=2>");
1912 assert_eq!(kg.triples[1].predicate, "sea:label");
1913 assert_eq!(kg.triples[1].object, "\"a;b\"");
1914 }
1915
1916 #[test]
1917 fn test_from_turtle_preserves_commas_in_iri_objects() {
1918 let turtle = r#"<https://example.test/s> sea:link <https://example.test/a,b>, <https://example.test/c,d>, "e,f" ."#;
1919 let kg = KnowledgeGraph::from_turtle(turtle).unwrap();
1920
1921 let objects: Vec<&str> = kg
1922 .triples
1923 .iter()
1924 .map(|triple| triple.object.as_str())
1925 .collect();
1926 assert_eq!(
1927 objects,
1928 [
1929 "<https://example.test/a,b>",
1930 "<https://example.test/c,d>",
1931 "\"e,f\"",
1932 ]
1933 );
1934 }
1935
1936 #[test]
1937 fn test_export_to_rdf_turtle() {
1938 let mut graph = Graph::new();
1939
1940 let entity1 = Entity::new_with_namespace("Supplier", "supply_chain");
1941 let entity2 = Entity::new_with_namespace("Manufacturer", "supply_chain");
1942 let resource = Resource::new_with_namespace(
1943 "Parts",
1944 crate::units::unit_from_string("kg"),
1945 "supply_chain",
1946 );
1947
1948 let entity1_id = entity1.id().clone();
1949 let entity2_id = entity2.id().clone();
1950 let resource_id = resource.id().clone();
1951
1952 graph.add_entity(entity1).unwrap();
1953 graph.add_entity(entity2).unwrap();
1954 graph.add_resource(resource).unwrap();
1955
1956 #[allow(deprecated)]
1957 let flow = Flow::new(resource_id, entity1_id, entity2_id, Decimal::new(100, 0));
1958 graph.add_flow(flow).unwrap();
1959
1960 let rdf_turtle = graph.export_rdf("turtle").unwrap();
1961
1962 assert!(rdf_turtle.contains("sea:Entity"));
1963 assert!(rdf_turtle.contains("sea:hasResource"));
1964 assert!(rdf_turtle.contains("@prefix"));
1965 }
1966
1967 #[test]
1968 fn test_export_to_rdf_xml() {
1969 let mut graph = Graph::new();
1970
1971 let entity = Entity::new_with_namespace("TestEntity", "default".to_string());
1972 graph.add_entity(entity).unwrap();
1973
1974 let rdf_xml = graph.export_rdf("rdf-xml").unwrap();
1975
1976 assert!(rdf_xml.contains("<?xml"));
1977 assert!(rdf_xml.contains("rdf:RDF"));
1978 }
1979
1980 #[test]
1981 fn test_unsupported_format() {
1982 let graph = Graph::new();
1983 let result = graph.export_rdf("json-ld");
1984
1985 assert!(result.is_err());
1986 assert!(matches!(result.unwrap_err(), KgError::UnsupportedFormat(_)));
1987 }
1988
1989 #[test]
1990 fn test_export_rdf_turtle_encodes_special_characters_and_literals() {
1991 let mut graph = Graph::new();
1992
1993 let entity_space = Entity::new_with_namespace("Entity With Space", "default".to_string());
1994 let entity_colon = Entity::new_with_namespace("Entity:Colon", "default".to_string());
1995 let entity_slash = Entity::new_with_namespace("Entity/Slash", "default".to_string());
1996 let entity_hash = Entity::new_with_namespace("Entity#Hash", "default".to_string());
1997
1998 graph.add_entity(entity_space.clone()).unwrap();
1999 graph.add_entity(entity_colon.clone()).unwrap();
2000 graph.add_entity(entity_slash.clone()).unwrap();
2001 graph.add_entity(entity_hash.clone()).unwrap();
2002
2003 let resource = Resource::new_with_namespace(
2004 "Resource:Name/Hash",
2005 crate::units::unit_from_string("units"),
2006 "default".to_string(),
2007 );
2008 let resource_id = resource.id().clone();
2009 graph.add_resource(resource).unwrap();
2010
2011 let flow = Flow::new(
2012 resource_id,
2013 entity_space.id().clone(),
2014 entity_colon.id().clone(),
2015 Decimal::new(42, 0),
2016 );
2017 graph.add_flow(flow).unwrap();
2018
2019 let turtle = graph.export_rdf("turtle").unwrap();
2020 assert!(turtle.contains("sea:Entity%20With%20Space"));
2021 assert!(turtle.contains("sea:Entity%3AColon"));
2022 assert!(turtle.contains("sea:Entity%2FSlash"));
2023 assert!(turtle.contains("sea:Entity%23Hash"));
2024 assert!(turtle.contains("sea:Resource%3AName%2FHash"));
2025 assert!(turtle.contains("\"42\"^^xsd:decimal"));
2026 }
2027
2028 #[test]
2029 fn test_rdf_xml_escapes_special_literals_and_language_tags() {
2030 let mut kg = KnowledgeGraph::new();
2031
2032 kg.triples.push(Triple {
2033 subject: "sea:testEntity".to_string(),
2034 predicate: "sea:hasNumericValue".to_string(),
2035 object: "\"100\"^^xsd:decimal".to_string(),
2036 });
2037 kg.triples.push(Triple {
2038 subject: "sea:testEntity".to_string(),
2039 predicate: "sea:description".to_string(),
2040 object: "\"Hello & <World>\"@en".to_string(),
2041 });
2042
2043 let xml = kg.to_rdf_xml();
2044 assert!(xml.contains("rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\""));
2045 assert!(xml.contains(">100<"));
2046 assert!(xml.contains("xml:lang=\"en\""));
2047 assert!(xml.contains("&"));
2048 assert!(xml.contains("<"));
2049 assert!(xml.contains(">"));
2050 }
2051}