Skip to main content

domainforge_core/
kg.rs

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, Serialize, Deserialize)]
40pub struct ShaclShape {
41    pub target_class: String,
42    pub properties: Vec<ShaclProperty>,
43}
44
45#[derive(Debug, Clone, 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 tokenize_triple_line(line: &str) -> Vec<String> {
75    let mut tokens = Vec::new();
76    let mut buffer = String::new();
77    let mut in_literal = false;
78    let mut escape = false;
79
80    for c in line.chars() {
81        if in_literal {
82            buffer.push(c);
83            if escape {
84                escape = false;
85            } else if c == '\\' {
86                escape = true;
87            } else if c == '"' {
88                in_literal = false;
89            }
90            continue;
91        }
92
93        match c {
94            '"' => {
95                in_literal = true;
96                buffer.push(c);
97            }
98            c if c.is_whitespace() => {
99                if !buffer.is_empty() {
100                    tokens.push(buffer.clone());
101                    buffer.clear();
102                }
103            }
104            _ => {
105                buffer.push(c);
106            }
107        }
108    }
109
110    if !buffer.is_empty() {
111        tokens.push(buffer);
112    }
113
114    tokens
115}
116
117fn extract_local_name(token: &str) -> String {
118    let trimmed = token.trim();
119    let stripped = trimmed.trim_matches(|c| c == '<' || c == '>');
120    stripped
121        .rsplit(|c| ['#', ':'].contains(&c))
122        .next()
123        .unwrap_or(stripped)
124        .to_string()
125}
126
127fn extract_literal_value(token: &str) -> String {
128    let trimmed = token.trim();
129    if let Some(stripped) = trimmed.strip_prefix('"') {
130        if let Some(end_quote) = stripped.find('"') {
131            return stripped[..end_quote].to_string();
132        }
133        return stripped.trim_end_matches('"').to_string();
134    }
135
136    if let Some(idx) = trimmed.find("^^") {
137        return trimmed[..idx].trim().to_string();
138    }
139    trimmed.to_string()
140}
141
142impl KnowledgeGraph {
143    pub fn new() -> Self {
144        Self {
145            triples: Vec::new(),
146            shapes: Vec::new(),
147        }
148    }
149
150    pub fn from_graph(graph: &Graph) -> Result<Self, KgError> {
151        let mut kg = Self::new();
152
153        let registry = ProjectionRegistry::new(graph);
154        let projections = registry.find_projections_for_target(&TargetFormat::Kg);
155        let projection = projections.first().copied();
156
157        for entity in graph.all_entities() {
158            let mut rdf_class = "sea:Entity".to_string();
159            let mut prop_map = std::collections::HashMap::new();
160
161            if let Some(proj) = projection {
162                if let Some(rule) = find_projection_override(proj, "Entity", entity.name()) {
163                    if let Some(cls) = rule.fields.get("rdf_class").and_then(|v| v.as_str()) {
164                        if Self::is_valid_rdf_term(cls) {
165                            rdf_class = cls.to_string();
166                        } else {
167                            eprintln!("Warning: Invalid RDF term for rdf_class, skipping: {}", cls);
168                        }
169                    }
170                    if let Some(props) = rule.fields.get("properties").and_then(|v| v.as_object()) {
171                        for (k, v) in props {
172                            if let Some(v_str) = v.as_str() {
173                                if Self::is_valid_rdf_term(v_str) {
174                                    prop_map.insert(k.clone(), v_str.to_string());
175                                } else {
176                                    eprintln!(
177                                        "Warning: Invalid RDF term for property '{}', skipping: {}",
178                                        k, v_str
179                                    );
180                                }
181                            }
182                        }
183                    }
184                }
185            }
186
187            kg.triples.push(Triple {
188                subject: format!("sea:{}", Self::uri_encode(entity.name())),
189                predicate: "rdf:type".to_string(),
190                object: rdf_class,
191            });
192
193            let label_pred = prop_map
194                .get("name")
195                .cloned()
196                .unwrap_or_else(|| "rdfs:label".to_string());
197            kg.triples.push(Triple {
198                subject: format!("sea:{}", Self::uri_encode(entity.name())),
199                predicate: label_pred,
200                object: format!("\"{}\"", Self::escape_turtle_literal(entity.name())),
201            });
202
203            let ns_pred = prop_map
204                .get("namespace")
205                .cloned()
206                .unwrap_or_else(|| "sea:namespace".to_string());
207            kg.triples.push(Triple {
208                subject: format!("sea:{}", Self::uri_encode(entity.name())),
209                predicate: ns_pred,
210                object: format!("\"{}\"", Self::escape_turtle_literal(entity.namespace())),
211            });
212        }
213
214        for role in graph.all_roles() {
215            kg.triples.push(Triple {
216                subject: format!("sea:{}", Self::uri_encode(role.name())),
217                predicate: "rdf:type".to_string(),
218                object: "sea:Role".to_string(),
219            });
220
221            kg.triples.push(Triple {
222                subject: format!("sea:{}", Self::uri_encode(role.name())),
223                predicate: "rdfs:label".to_string(),
224                object: format!("\"{}\"", Self::escape_turtle_literal(role.name())),
225            });
226
227            kg.triples.push(Triple {
228                subject: format!("sea:{}", Self::uri_encode(role.name())),
229                predicate: "sea:namespace".to_string(),
230                object: format!("\"{}\"", Self::escape_turtle_literal(role.namespace())),
231            });
232        }
233
234        for resource in graph.all_resources() {
235            kg.triples.push(Triple {
236                subject: format!("sea:{}", Self::uri_encode(resource.name())),
237                predicate: "rdf:type".to_string(),
238                object: "sea:Resource".to_string(),
239            });
240
241            kg.triples.push(Triple {
242                subject: format!("sea:{}", Self::uri_encode(resource.name())),
243                predicate: "rdfs:label".to_string(),
244                object: format!("\"{}\"", Self::escape_turtle_literal(resource.name())),
245            });
246
247            kg.triples.push(Triple {
248                subject: format!("sea:{}", Self::uri_encode(resource.name())),
249                predicate: "sea:unit".to_string(),
250                object: format!(
251                    "\"{}\"",
252                    Self::escape_turtle_literal(&resource.unit().to_string())
253                ),
254            });
255        }
256
257        for pattern in graph.all_patterns() {
258            let subject = format!("sea:pattern_{}", Self::uri_encode(pattern.name()));
259
260            kg.triples.push(Triple {
261                subject: subject.clone(),
262                predicate: "rdf:type".to_string(),
263                object: "sea:Pattern".to_string(),
264            });
265
266            kg.triples.push(Triple {
267                subject: subject.clone(),
268                predicate: "rdfs:label".to_string(),
269                object: format!("\"{}\"", Self::escape_turtle_literal(pattern.name())),
270            });
271
272            kg.triples.push(Triple {
273                subject: subject.clone(),
274                predicate: "sea:namespace".to_string(),
275                object: format!("\"{}\"", Self::escape_turtle_literal(pattern.namespace())),
276            });
277
278            kg.triples.push(Triple {
279                subject,
280                predicate: "sea:regex".to_string(),
281                object: format!("\"{}\"", Self::escape_turtle_literal(pattern.regex())),
282            });
283        }
284
285        for relation in graph.all_relations() {
286            let relation_subject = format!("sea:{}", Self::uri_encode(relation.name()));
287
288            kg.triples.push(Triple {
289                subject: relation_subject.clone(),
290                predicate: "rdf:type".to_string(),
291                object: "sea:Relation".to_string(),
292            });
293
294            kg.triples.push(Triple {
295                subject: relation_subject.clone(),
296                predicate: "rdfs:label".to_string(),
297                object: format!("\"{}\"", Self::escape_turtle_literal(relation.name())),
298            });
299
300            if let Some(subject_role) = graph.get_role(relation.subject_role()) {
301                kg.triples.push(Triple {
302                    subject: relation_subject.clone(),
303                    predicate: "sea:subjectRole".to_string(),
304                    object: format!("sea:{}", Self::uri_encode(subject_role.name())),
305                });
306            }
307
308            if let Some(object_role) = graph.get_role(relation.object_role()) {
309                kg.triples.push(Triple {
310                    subject: relation_subject.clone(),
311                    predicate: "sea:objectRole".to_string(),
312                    object: format!("sea:{}", Self::uri_encode(object_role.name())),
313                });
314            }
315
316            kg.triples.push(Triple {
317                subject: relation_subject.clone(),
318                predicate: "sea:predicate".to_string(),
319                object: format!("\"{}\"", Self::escape_turtle_literal(relation.predicate())),
320            });
321
322            if let Some(flow_id) = relation.via_flow() {
323                if let Some(resource) = graph.get_resource(flow_id) {
324                    kg.triples.push(Triple {
325                        subject: relation_subject.clone(),
326                        predicate: "sea:via".to_string(),
327                        object: format!("sea:{}", Self::uri_encode(resource.name())),
328                    });
329                } else {
330                    kg.triples.push(Triple {
331                        subject: relation_subject.clone(),
332                        predicate: "sea:via".to_string(),
333                        object: format!("\"{}\"", flow_id),
334                    });
335                }
336            }
337        }
338
339        for flow in graph.all_flows() {
340            let flow_id = format!("sea:flow_{}", Self::uri_encode(&flow.id().to_string()));
341
342            kg.triples.push(Triple {
343                subject: flow_id.clone(),
344                predicate: "rdf:type".to_string(),
345                object: "sea:Flow".to_string(),
346            });
347
348            if let Some(from_entity) = graph.get_entity(flow.from_id()) {
349                kg.triples.push(Triple {
350                    subject: flow_id.clone(),
351                    predicate: "sea:from".to_string(),
352                    object: format!("sea:{}", Self::uri_encode(from_entity.name())),
353                });
354            }
355
356            if let Some(to_entity) = graph.get_entity(flow.to_id()) {
357                kg.triples.push(Triple {
358                    subject: flow_id.clone(),
359                    predicate: "sea:to".to_string(),
360                    object: format!("sea:{}", Self::uri_encode(to_entity.name())),
361                });
362            }
363
364            if let Some(resource) = graph.get_resource(flow.resource_id()) {
365                kg.triples.push(Triple {
366                    subject: flow_id.clone(),
367                    predicate: "sea:hasResource".to_string(),
368                    object: format!("sea:{}", Self::uri_encode(resource.name())),
369                });
370            }
371
372            // Validate that the quantity is a safe decimal string for Turtle format
373            let quantity_str = flow.quantity().to_string();
374            Self::validate_turtle_decimal(&quantity_str).map_err(|e| {
375                KgError::SerializationError(format!("Invalid quantity format: {}", e))
376            })?;
377
378            kg.triples.push(Triple {
379                subject: flow_id.clone(),
380                predicate: "sea:quantity".to_string(),
381                object: format!("\"{}\"^^xsd:decimal", quantity_str),
382            });
383        }
384
385        // Entity instances are authored model content, not derived structure, so
386        // they must survive projection. Their ConceptId is already content-derived
387        // (`namespace` + `Type:name`), so their IRIs are stable without routing
388        // through the projection-level `canonicalize_node_ids` remap.
389        for instance in graph.all_entity_instances() {
390            let subject = Self::entity_instance_iri(instance);
391
392            kg.triples.push(Triple {
393                subject: subject.clone(),
394                predicate: "rdf:type".to_string(),
395                object: "sea:EntityInstance".to_string(),
396            });
397
398            // `sea:instanceOf` rather than typing the instance directly by its
399            // entity IRI: entity names are themselves individuals here, and
400            // punning them as classes would make the emitted ontology OWL Full.
401            kg.triples.push(Triple {
402                subject: subject.clone(),
403                predicate: "sea:instanceOf".to_string(),
404                object: format!("sea:{}", Self::uri_encode(instance.entity_type())),
405            });
406
407            kg.triples.push(Triple {
408                subject: subject.clone(),
409                predicate: "rdfs:label".to_string(),
410                object: format!("\"{}\"", Self::escape_turtle_literal(instance.name())),
411            });
412
413            kg.triples.push(Triple {
414                subject: subject.clone(),
415                predicate: "sea:namespace".to_string(),
416                object: format!("\"{}\"", Self::escape_turtle_literal(instance.namespace())),
417            });
418
419            // Typed entities (0.16.0 `entity` contracts) give each field a declared
420            // datatype; untyped instances fall back to the JSON value's own shape.
421            let contract = graph
422                .find_entity_by_name_and_namespace(instance.entity_type(), instance.namespace())
423                .and_then(|entity_id| graph.entity_contract(&entity_id));
424
425            // `Instance::fields` is a HashMap; sort before emitting or the byte
426            // -identical-output guarantee (and the verify-rdf CI gate) breaks.
427            let ordered: BTreeMap<&str, &Value> = instance
428                .fields()
429                .iter()
430                .map(|(key, value)| (key.as_str(), value))
431                .collect();
432
433            for (key, value) in ordered {
434                let declared = contract.and_then(|contract| {
435                    contract
436                        .fields
437                        .iter()
438                        .find(|field| field.name == key)
439                        .map(|field| &field.field_type)
440                });
441                let Some(object) = Self::instance_field_object(value, declared) else {
442                    continue;
443                };
444                kg.triples.push(Triple {
445                    subject: subject.clone(),
446                    predicate: format!("sea:{}", Self::uri_encode(key)),
447                    object,
448                });
449            }
450        }
451
452        // Policies are declared, not derived. They are emitted as traceable
453        // individuals carrying their normalized expression; they are deliberately
454        // NOT lowered into SHACL constraints, because a partial translation would
455        // silently change what a policy means.
456        for policy in graph.all_policies() {
457            let subject = Self::policy_iri(policy);
458
459            kg.triples.push(Triple {
460                subject: subject.clone(),
461                predicate: "rdf:type".to_string(),
462                object: "sea:Policy".to_string(),
463            });
464
465            let mut literals: Vec<(&str, String)> = vec![
466                ("rdfs:label", policy.name.clone()),
467                ("sea:namespace", policy.namespace.clone()),
468                ("sea:version", policy.version.to_string()),
469                (
470                    "sea:modality",
471                    match policy.modality {
472                        PolicyModality::Obligation => "obligation",
473                        PolicyModality::Prohibition => "prohibition",
474                        PolicyModality::Permission => "permission",
475                    }
476                    .to_string(),
477                ),
478                (
479                    "sea:policyKind",
480                    match policy.kind {
481                        PolicyKind::Constraint => "constraint",
482                        PolicyKind::Derivation => "derivation",
483                        PolicyKind::Obligation => "obligation",
484                    }
485                    .to_string(),
486                ),
487                ("sea:expression", policy.normalized_expression().to_string()),
488            ];
489            if let Some(rationale) = policy.rationale.as_ref() {
490                literals.push(("sea:rationale", rationale.clone()));
491            }
492
493            for (predicate, literal) in literals {
494                kg.triples.push(Triple {
495                    subject: subject.clone(),
496                    predicate: predicate.to_string(),
497                    object: format!("\"{}\"", Self::escape_turtle_literal(&literal)),
498                });
499            }
500
501            kg.triples.push(Triple {
502                subject: subject.clone(),
503                predicate: "sea:priority".to_string(),
504                object: format!("\"{}\"^^xsd:integer", policy.priority),
505            });
506
507            // Tags are an unordered set on the model; sort for stable output.
508            let mut tags: Vec<&str> = policy.tags.iter().map(String::as_str).collect();
509            tags.sort_unstable();
510            tags.dedup();
511            for tag in tags {
512                kg.triples.push(Triple {
513                    subject: subject.clone(),
514                    predicate: "sea:tag".to_string(),
515                    object: format!("\"{}\"", Self::escape_turtle_literal(tag)),
516                });
517            }
518        }
519
520        kg.shapes.push(ShaclShape {
521            target_class: "sea:Flow".to_string(),
522            properties: vec![
523                ShaclProperty {
524                    path: "sea:quantity".to_string(),
525                    datatype: Some("xsd:decimal".to_string()),
526                    min_count: None,
527                    max_count: None,
528                    min_exclusive: Some("0".to_string()),
529                },
530                ShaclProperty {
531                    path: "sea:hasResource".to_string(),
532                    datatype: None,
533                    min_count: Some(1),
534                    max_count: Some(1),
535                    min_exclusive: None,
536                },
537                ShaclProperty {
538                    path: "sea:from".to_string(),
539                    datatype: None,
540                    min_count: Some(1),
541                    max_count: Some(1),
542                    min_exclusive: None,
543                },
544                ShaclProperty {
545                    path: "sea:to".to_string(),
546                    datatype: None,
547                    min_count: Some(1),
548                    max_count: Some(1),
549                    min_exclusive: None,
550                },
551            ],
552        });
553
554        kg.shapes.push(ShaclShape {
555            target_class: "sea:Entity".to_string(),
556            properties: vec![ShaclProperty {
557                path: "rdfs:label".to_string(),
558                datatype: Some("xsd:string".to_string()),
559                min_count: Some(1),
560                max_count: Some(1),
561                min_exclusive: None,
562            }],
563        });
564
565        Ok(kg)
566    }
567
568    pub fn to_turtle(&self) -> String {
569        let mut turtle = String::new();
570
571        turtle.push_str("@prefix sea: <http://domainforge.ai/sea#> .\n");
572        turtle.push_str("@prefix owl: <http://www.w3.org/2002/07/owl#> .\n");
573        turtle.push_str("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n");
574        turtle.push_str("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n");
575        turtle.push_str("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n");
576        turtle.push_str("@prefix sh: <http://www.w3.org/ns/shacl#> .\n");
577        turtle.push('\n');
578
579        turtle.push_str("# Ontology\n");
580        turtle.push_str("sea:Entity a owl:Class ;\n");
581        turtle.push_str("    rdfs:label \"Entity\" ;\n");
582        turtle.push_str(
583            "    rdfs:comment \"Business actor, location, or organizational unit\" .\n\n",
584        );
585
586        turtle.push_str("sea:Resource a owl:Class ;\n");
587        turtle.push_str("    rdfs:label \"Resource\" ;\n");
588        turtle.push_str("    rdfs:comment \"Quantifiable subject of value\" .\n\n");
589
590        turtle.push_str("sea:Flow a owl:Class ;\n");
591        turtle.push_str("    rdfs:label \"Flow\" ;\n");
592        turtle.push_str("    rdfs:comment \"Transfer of resource between entities\" .\n\n");
593
594        turtle.push_str("sea:hasResource a owl:ObjectProperty ;\n");
595        turtle.push_str("    rdfs:domain sea:Flow ;\n");
596        turtle.push_str("    rdfs:range sea:Resource .\n\n");
597
598        turtle.push_str("sea:from a owl:ObjectProperty ;\n");
599        turtle.push_str("    rdfs:domain sea:Flow ;\n");
600        turtle.push_str("    rdfs:range sea:Entity .\n\n");
601
602        turtle.push_str("sea:to a owl:ObjectProperty ;\n");
603        turtle.push_str("    rdfs:domain sea:Flow ;\n");
604        turtle.push_str("    rdfs:range sea:Entity .\n\n");
605
606        turtle.push_str("sea:EntityInstance a owl:Class ;\n");
607        turtle.push_str("    rdfs:label \"EntityInstance\" ;\n");
608        turtle.push_str(
609            "    rdfs:comment \"Declared instance of an entity with field values\" .\n\n",
610        );
611
612        turtle.push_str("sea:Policy a owl:Class ;\n");
613        turtle.push_str("    rdfs:label \"Policy\" ;\n");
614        turtle.push_str("    rdfs:comment \"Declared rule over the model; expression is stated, not enforced here\" .\n\n");
615
616        turtle.push_str("sea:instanceOf a owl:ObjectProperty ;\n");
617        turtle.push_str("    rdfs:domain sea:EntityInstance ;\n");
618        turtle.push_str("    rdfs:range sea:Entity .\n\n");
619
620        turtle.push_str("# Instances\n");
621        for triple in &self.triples {
622            turtle.push_str(&format!(
623                "{} {} {} .\n",
624                triple.subject, triple.predicate, triple.object
625            ));
626        }
627
628        turtle.push_str("\n# SHACL Shapes\n");
629        for shape in &self.shapes {
630            turtle.push_str(&format!(
631                "sea:{}Shape a sh:NodeShape ;\n",
632                shape.target_class.replace("sea:", "")
633            ));
634            turtle.push_str(&format!("    sh:targetClass {} ;\n", shape.target_class));
635
636            for (i, prop) in shape.properties.iter().enumerate() {
637                turtle.push_str("    sh:property [\n");
638                turtle.push_str(&format!("        sh:path {} ;\n", prop.path));
639
640                if let Some(dt) = &prop.datatype {
641                    turtle.push_str(&format!("        sh:datatype {} ;\n", dt));
642                }
643                if let Some(min) = prop.min_count {
644                    turtle.push_str(&format!("        sh:minCount {} ;\n", min));
645                }
646                if let Some(max) = prop.max_count {
647                    turtle.push_str(&format!("        sh:maxCount {} ;\n", max));
648                }
649                if let Some(min_ex) = &prop.min_exclusive {
650                    turtle.push_str(&format!("        sh:minExclusive {} ;\n", min_ex));
651                }
652
653                if i < shape.properties.len() - 1 {
654                    turtle.push_str("    ] ;\n");
655                } else {
656                    turtle.push_str("    ] .\n");
657                }
658            }
659            turtle.push('\n');
660        }
661
662        turtle
663    }
664
665    /// Parse a simple Turtle snippet into a KnowledgeGraph. This is a best-effort parser
666    /// expecting the exact triple format generated by `to_turtle()` in this crate.
667    #[allow(clippy::while_let_on_iterator)]
668    pub fn from_turtle(turtle: &str) -> Result<Self, KgError> {
669        let mut kg = Self::new();
670        for line in turtle.lines() {
671            let trimmed = line.trim();
672            if trimmed.is_empty() || trimmed.starts_with('@') || trimmed.starts_with('#') {
673                continue;
674            }
675            let triple_line = if let Some(stripped) = trimmed.strip_suffix('.') {
676                stripped.trim_end()
677            } else {
678                trimmed
679            };
680            let tokens = tokenize_triple_line(triple_line);
681            if tokens.len() != 3 {
682                continue;
683            }
684            let subject = &tokens[0];
685            let predicate = &tokens[1];
686            let object = &tokens[2];
687            let norm_s = Self::shorten_token(subject);
688            let norm_p = Self::shorten_token(predicate);
689            let norm_o = Self::shorten_token(object);
690            kg.triples.push(Triple {
691                subject: norm_s,
692                predicate: norm_p,
693                object: norm_o,
694            });
695        }
696        // parse shapes: look for NodeShape blocks (start with 'sea:SomethingShape a sh:NodeShape')
697        // We scan lines to find blocks terminating with '.' and containing 'sh:property' entries
698        let mut lines_iter = turtle.lines();
699        while let Some(line) = lines_iter.next() {
700            let l = line.trim();
701            if l.contains("a sh:NodeShape") {
702                // Collect shape block until '.' terminator
703                let mut block = l.to_string();
704                if !l.ends_with('.') {
705                    while let Some(next_line) = lines_iter.next() {
706                        block.push(' ');
707                        block.push_str(next_line.trim());
708                        if next_line.trim().ends_with('.') {
709                            break;
710                        }
711                    }
712                }
713
714                // Normalize full URIs into prefixes for easier parsing
715                let normalized_block = block
716                    .replace("http://www.w3.org/ns/shacl#", "sh:")
717                    .replace("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:")
718                    .replace("http://www.w3.org/2000/01/rdf-schema#", "rdfs:")
719                    .replace("http://www.w3.org/2001/XMLSchema#", "xsd:")
720                    .replace("http://domainforge.ai/sea#", "sea:");
721
722                // Extract target class
723                let target_class = if let Some(pos) = normalized_block.find("sh:targetClass") {
724                    let rest = &normalized_block[pos + "sh:targetClass".len()..];
725                    let tok = rest
726                        .split_whitespace()
727                        .next()
728                        .unwrap_or("")
729                        .trim()
730                        .trim_end_matches(';')
731                        .to_string();
732                    tok
733                } else {
734                    continue; // ignore shapes without targetClass
735                };
736
737                let mut shape = ShaclShape {
738                    target_class,
739                    properties: Vec::new(),
740                };
741
742                // Find property blocks: 'sh:property [ ... ]' occurrences
743                let mut start_idx = 0;
744                while let Some(idx) = normalized_block[start_idx..].find("sh:property") {
745                    let local_idx = start_idx + idx;
746                    // Find the opening '[' and closing ']' for the property
747                    if let Some(open_br) = normalized_block[local_idx..].find('[') {
748                        let open_idx = local_idx + open_br + 1;
749                        if let Some(close_br) = normalized_block[open_idx..].find(']') {
750                            let close_idx = open_idx + close_br;
751                            let prop_block = &normalized_block[open_idx..close_idx];
752                            // Parse property attributes
753                            let mut path = String::new();
754                            let mut datatype: Option<String> = None;
755                            let mut min_count: Option<u32> = None;
756                            let mut max_count: Option<u32> = None;
757                            let mut min_exclusive: Option<String> = None;
758
759                            for tok in prop_block.split(';') {
760                                let tok = tok.trim();
761                                if tok.is_empty() {
762                                    continue;
763                                }
764                                if let Some(s) = tok.strip_prefix("sh:path") {
765                                    path = s.trim().to_string();
766                                } else if let Some(s) = tok.strip_prefix("sh:datatype") {
767                                    datatype = Some(s.trim().to_string());
768                                } else if let Some(s) = tok.strip_prefix("sh:minCount") {
769                                    let val = s.trim();
770                                    if let Ok(n) = val.parse::<u32>() {
771                                        min_count = Some(n);
772                                    }
773                                } else if let Some(s) = tok.strip_prefix("sh:maxCount") {
774                                    let val = s.trim();
775                                    if let Ok(n) = val.parse::<u32>() {
776                                        max_count = Some(n);
777                                    }
778                                } else if let Some(s) = tok.strip_prefix("sh:minExclusive") {
779                                    let val = s.trim();
780                                    min_exclusive = Some(val.to_string());
781                                }
782                            }
783
784                            if !path.is_empty() {
785                                shape.properties.push(ShaclProperty {
786                                    path,
787                                    datatype,
788                                    min_count,
789                                    max_count,
790                                    min_exclusive,
791                                });
792                            }
793                            start_idx = close_idx + 1;
794                            continue;
795                        }
796                    }
797                    start_idx = local_idx + 1;
798                }
799
800                if !shape.properties.is_empty() {
801                    kg.shapes.push(shape);
802                }
803            }
804        }
805        Ok(kg)
806    }
807
808    /// Convert the knowledge graph back into a Graph by interpreting triples exported by `to_turtle`.
809    ///
810    /// Known gap: this reconstructs `Entity`/`Resource`/`Flow`/`Relation` but
811    /// not the `sea:EntityInstance` or `sea:Policy` triples `to_turtle`
812    /// emits — round-tripping a graph that has instances or policies through
813    /// `to_turtle`/`from_turtle`/`to_graph` silently drops them rather than
814    /// erroring. Closing this requires reversing `xsd_datatype` dispatch per
815    /// declared field type and re-deriving a `Policy`'s `Expression` from
816    /// its normalized-text triple, which is real reconstruction work, not a
817    /// quick addition; tracked in `.agents/next_steps.md`. Do not rely on
818    /// this method for instance/policy round-tripping — use the Canonical
819    /// Semantic Envelope instead (`.sea/interaction/README.md` "Known
820    /// Toolchain Boundaries").
821    pub fn to_graph(&self) -> Result<crate::graph::Graph, KgError> {
822        use crate::graph::Graph;
823        use crate::primitives::{Entity, Flow, Resource};
824        use crate::units::unit_from_string;
825        use rust_decimal::Decimal;
826
827        let mut graph = Graph::new();
828
829        let mut namespace_map: std::collections::HashMap<String, String> =
830            std::collections::HashMap::new();
831        for t in &self.triples {
832            if t.predicate == "sea:namespace" {
833                let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
834                let name = percent_decode_str(name_encoded)
835                    .decode_utf8_lossy()
836                    .to_string();
837                let ns = extract_literal_value(&t.object);
838                namespace_map.insert(name, ns);
839            }
840        }
841
842        let mut unit_map: std::collections::HashMap<String, String> =
843            std::collections::HashMap::new();
844        for t in &self.triples {
845            if t.predicate == "sea:unit" {
846                let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
847                let name = percent_decode_str(name_encoded)
848                    .decode_utf8_lossy()
849                    .to_string();
850                let unit_str = extract_literal_value(&t.object);
851                unit_map.insert(name, unit_str);
852            }
853        }
854
855        for t in &self.triples {
856            if t.predicate == "rdf:type" && t.object == "sea:Entity" {
857                let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
858                let name = percent_decode_str(name_encoded)
859                    .decode_utf8_lossy()
860                    .to_string();
861                let namespace = namespace_map
862                    .get(&name)
863                    .cloned()
864                    .unwrap_or_else(|| "default".to_string());
865                let entity = Entity::new_with_namespace(name, namespace);
866                graph
867                    .add_entity(entity)
868                    .map_err(|e| KgError::SerializationError(e.to_string()))?;
869            }
870            if t.predicate == "rdf:type" && t.object == "sea:Resource" {
871                let name_encoded = t.subject.split(':').nth(1).unwrap_or(&t.subject);
872                let name = percent_decode_str(name_encoded)
873                    .decode_utf8_lossy()
874                    .to_string();
875                let namespace = namespace_map
876                    .get(&name)
877                    .cloned()
878                    .unwrap_or_else(|| "default".to_string());
879                let unit =
880                    unit_from_string(unit_map.get(&name).map(|s| s.as_str()).unwrap_or("units"));
881                let resource = Resource::new_with_namespace(name, unit, namespace);
882                graph
883                    .add_resource(resource)
884                    .map_err(|e| KgError::SerializationError(e.to_string()))?;
885            }
886        }
887
888        for t in &self.triples {
889            if t.predicate == "rdf:type" && t.object == "sea:Flow" {
890                let flow_subject = t.subject.clone();
891                let mut from: Option<String> = None;
892                let mut to: Option<String> = None;
893                let mut resource_name: Option<String> = None;
894                let mut quantity: Option<Decimal> = None;
895
896                for p in &self.triples {
897                    if p.subject != flow_subject {
898                        continue;
899                    }
900                    match p.predicate.as_str() {
901                        "sea:from" => {
902                            from = Some(extract_local_name(&p.object));
903                        }
904                        "sea:to" => {
905                            to = Some(extract_local_name(&p.object));
906                        }
907                        "sea:hasResource" => {
908                            resource_name = Some(extract_local_name(&p.object));
909                        }
910                        "sea:quantity" => {
911                            let lexical = extract_literal_value(&p.object);
912                            let parsed = Decimal::from_str(&lexical).map_err(|e| {
913                                KgError::SerializationError(format!(
914                                    "Invalid quantity literal '{}': {}",
915                                    p.object, e
916                                ))
917                            })?;
918                            quantity = Some(parsed);
919                        }
920                        _ => {}
921                    }
922                }
923
924                if let (Some(from_name), Some(to_name), Some(res_name), Some(quantity_val)) =
925                    (from, to, resource_name, quantity)
926                {
927                    let from_decoded = percent_decode_str(&from_name)
928                        .decode_utf8_lossy()
929                        .to_string();
930                    let to_decoded = percent_decode_str(&to_name).decode_utf8_lossy().to_string();
931                    let res_decoded = percent_decode_str(&res_name)
932                        .decode_utf8_lossy()
933                        .to_string();
934
935                    let from_id = graph.find_entity_by_name(&from_decoded).ok_or_else(|| {
936                        KgError::SerializationError(format!("Unknown entity: {}", from_decoded))
937                    })?;
938                    let to_id = graph.find_entity_by_name(&to_decoded).ok_or_else(|| {
939                        KgError::SerializationError(format!("Unknown entity: {}", to_decoded))
940                    })?;
941                    let res_id = graph.find_resource_by_name(&res_decoded).ok_or_else(|| {
942                        KgError::SerializationError(format!("Unknown resource: {}", res_decoded))
943                    })?;
944
945                    let flow = Flow::new(res_id, from_id, to_id, quantity_val);
946                    graph
947                        .add_flow(flow)
948                        .map_err(|e| KgError::SerializationError(e.to_string()))?;
949                }
950            }
951        }
952
953        Ok(graph)
954    }
955
956    pub fn validate_shacl(&self) -> Result<Vec<crate::policy::Violation>, KgError> {
957        use crate::policy::{Severity, Violation};
958
959        // If no shapes are defined, nothing to validate
960        if self.shapes.is_empty() {
961            return Ok(Vec::new());
962        }
963
964        let mut violations: Vec<Violation> = Vec::new();
965
966        // Helper: parse a Turtle literal (optionally typed) into its lexical form
967        // and optional datatype suffix (e.g. "\"0\"^^xsd:decimal" -> ("0", Some("xsd:decimal"))).
968        fn parse_literal_and_datatype(obj: &str) -> (String, Option<String>) {
969            let s = obj.trim();
970            if !s.starts_with('"') {
971                return (s.to_string(), None);
972            }
973
974            // Find the closing quote for the lexical form, respecting simple escapes.
975            let bytes = s.as_bytes();
976            let mut end_quote = None;
977            let mut i = 1;
978            while i < bytes.len() {
979                if bytes[i] == b'\\' {
980                    // Skip escaped character
981                    i += 2;
982                    continue;
983                }
984                if bytes[i] == b'"' {
985                    end_quote = Some(i);
986                    break;
987                }
988                i += 1;
989            }
990
991            if let Some(end) = end_quote {
992                let lex = &s[1..end];
993                let rest = s[end + 1..].trim();
994                let dtype = rest.strip_prefix("^^").map(|s| s.trim().to_string());
995                (lex.to_string(), dtype)
996            } else {
997                // No matching closing quote; fall back to naive trimming
998                (s.trim_matches('"').to_string(), None)
999            }
1000        }
1001
1002        // For each shape, find all subjects in triples typed as the target class
1003        for shape in &self.shapes {
1004            match shape.target_class.as_str() {
1005                "sea:Flow" | "sea:Entity" | "sea:Resource" => {}
1006                other => {
1007                    return Err(KgError::SerializationError(format!(
1008                        "Unsupported SHACL target class: {}",
1009                        other
1010                    )))
1011                }
1012            }
1013
1014            // collect all candidate subjects by rdf:type triples
1015            let mut subjects: Vec<String> = Vec::new();
1016            for t in &self.triples {
1017                if t.predicate == "rdf:type" && t.object == shape.target_class {
1018                    subjects.push(t.subject.clone());
1019                }
1020            }
1021
1022            for subject in subjects {
1023                for prop in &shape.properties {
1024                    // check min_count / max_count constraints
1025                    let count = self
1026                        .triples
1027                        .iter()
1028                        .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1029                        .count() as u32;
1030
1031                    if let Some(min) = prop.min_count {
1032                        if count < min {
1033                            let msg = format!(
1034                                "SHACL violation: subject {} missing required property {} (min_count={} found={})",
1035                                subject, prop.path, min, count
1036                            );
1037                            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})));
1038                        }
1039                    }
1040
1041                    if let Some(max) = prop.max_count {
1042                        if count > max {
1043                            let msg = format!(
1044                                "SHACL violation: subject {} has {} occurrences of {} (max_count={} found={})",
1045                                subject, count, prop.path, max, count
1046                            );
1047                            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})));
1048                        }
1049                    }
1050
1051                    // datatype checks (only handle basic types like xsd:decimal and xsd:string)
1052                    if let Some(dt) = &prop.datatype {
1053                        for tr in self
1054                            .triples
1055                            .iter()
1056                            .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1057                        {
1058                            let obj = tr.object.trim();
1059                            let (_lex, dtype_opt) = parse_literal_and_datatype(obj);
1060                            // look for typed literal like "123"^^xsd:decimal
1061                            if let Some(dtype) = dtype_opt {
1062                                if &dtype != dt {
1063                                    let msg = format!(
1064                                        "SHACL violation: subject {} property {} expected datatype {} but found {}",
1065                                        subject, prop.path, dt, dtype
1066                                    );
1067                                    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})));
1068                                }
1069                            } else if dt != "xsd:string" {
1070                                // untyped literal but expected typed -> violation
1071                                let msg = format!(
1072                                    "SHACL violation: subject {} property {} expected datatype {} but found untyped literal {}",
1073                                    subject, prop.path, dt, obj
1074                                );
1075                                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})));
1076                            }
1077                        }
1078                    }
1079
1080                    // minExclusive check (e.g. > 0) — interpreted for decimal numbers
1081                    if let Some(min_ex) = &prop.min_exclusive {
1082                        if prop.datatype.as_deref() == Some("xsd:decimal") {
1083                            let threshold =
1084                                rust_decimal::Decimal::from_str(min_ex).map_err(|e| {
1085                                    KgError::SerializationError(format!(
1086                                        "Invalid minExclusive threshold '{}': {}",
1087                                        min_ex, e
1088                                    ))
1089                                })?;
1090                            for tr in self
1091                                .triples
1092                                .iter()
1093                                .filter(|tr| tr.subject == subject && tr.predicate == prop.path)
1094                            {
1095                                let obj = tr.object.trim();
1096                                let lex = extract_literal_value(obj);
1097                                if let Ok(val) = rust_decimal::Decimal::from_str(&lex) {
1098                                    if val <= threshold {
1099                                        let msg = format!(
1100                                            "SHACL violation: subject {} property {} must be > {} but found {}",
1101                                            subject, prop.path, threshold, val
1102                                        );
1103                                        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()})));
1104                                    }
1105                                }
1106                            }
1107                        }
1108                    }
1109                }
1110            }
1111        }
1112
1113        Ok(violations)
1114    }
1115
1116    pub fn to_rdf_xml(&self) -> String {
1117        let mut xml = String::new();
1118
1119        xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1120        xml.push_str("<rdf:RDF\n");
1121        xml.push_str("    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
1122        // Use project-local namespace for rdfs to preserve existing prefix mapping
1123        // in tests and downstream tooling that expects the domainforge namespace.
1124        xml.push_str("    xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n");
1125        xml.push_str("    xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n");
1126        xml.push_str("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n");
1127        // Explicitly declare the xml namespace so XML processors (and tests using roxmltree)
1128        // can resolve attributes like xml:lang correctly.
1129        xml.push_str("    xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n");
1130        xml.push_str("    xmlns:sea=\"http://domainforge.ai/sea#\"\n");
1131        xml.push_str("    xmlns:sh=\"http://www.w3.org/ns/shacl#\">\n\n");
1132
1133        for triple in &self.triples {
1134            let subject = Self::clean_uri(&triple.subject);
1135            // Keep the predicate as the original prefixed name for use as XML element
1136            // (e.g. rdfs:label). Use the cleaned URI only for rdf:datatype or rdf:resource
1137            // attributes where a full URI is required.
1138            let predicate_name = triple.predicate.clone();
1139            let object = &triple.object;
1140
1141            if object.starts_with('"') {
1142                let (literal_value, suffix) = Self::parse_typed_literal(object);
1143                let escaped_value = Self::escape_xml(&literal_value);
1144
1145                xml.push_str(&format!("  <rdf:Description rdf:about=\"{}\">\n", subject));
1146
1147                match suffix {
1148                    Some(TypedLiteralSuffix::Datatype(datatype)) => {
1149                        let datatype_uri = Self::clean_uri(&datatype);
1150                        xml.push_str(&format!(
1151                            "    <{} rdf:datatype=\"{}\">{}</{}>\n",
1152                            predicate_name, datatype_uri, escaped_value, predicate_name
1153                        ));
1154                    }
1155                    Some(TypedLiteralSuffix::Language(lang)) => {
1156                        xml.push_str(&format!(
1157                            "    <{} xml:lang=\"{}\">{}</{}>\n",
1158                            predicate_name, lang, escaped_value, predicate_name
1159                        ));
1160                    }
1161                    None => {
1162                        xml.push_str(&format!(
1163                            "    <{}>{}</{}>\n",
1164                            predicate_name, escaped_value, predicate_name
1165                        ));
1166                    }
1167                }
1168
1169                xml.push_str("  </rdf:Description>\n\n");
1170            } else {
1171                let cleaned_object = Self::clean_uri(object);
1172                xml.push_str(&format!("  <rdf:Description rdf:about=\"{}\">\n", subject));
1173                xml.push_str(&format!(
1174                    "    <{} rdf:resource=\"{}\"/>\n",
1175                    predicate_name, cleaned_object
1176                ));
1177                xml.push_str("  </rdf:Description>\n\n");
1178            }
1179        }
1180        xml.push('\n');
1181        // Emit SHACL shapes (as RDF/XML)
1182        for shape in &self.shapes {
1183            xml.push_str(&Self::write_shacl_shapes_xml(shape));
1184        }
1185
1186        xml.push_str("</rdf:RDF>\n");
1187        xml
1188    }
1189
1190    fn write_shacl_shapes_xml(shape: &ShaclShape) -> String {
1191        let mut xml = String::new();
1192        let shape_name = shape.target_class.replace("sea:", "") + "Shape";
1193        xml.push_str(&format!(
1194            "  <sh:NodeShape rdf:about=\"http://domainforge.ai/sea#{}\">\n",
1195            shape_name
1196        ));
1197        xml.push_str(&format!(
1198            "    <sh:targetClass rdf:resource=\"http://domainforge.ai/sea#{}\"/>\n",
1199            shape.target_class.replace("sea:", "")
1200        ));
1201        for prop in &shape.properties {
1202            xml.push_str("    <sh:property>\n");
1203            xml.push_str("      <rdf:Description>\n");
1204            // Resolve the full URI for the sh:path based on the prefixed name.
1205            let (ns, local) = if let Some(rest) = prop.path.strip_prefix("sea:") {
1206                ("http://domainforge.ai/sea#", rest)
1207            } else if let Some(rest) = prop.path.strip_prefix("rdfs:") {
1208                ("http://www.w3.org/2000/01/rdf-schema#", rest)
1209            } else {
1210                ("http://domainforge.ai/sea#", prop.path.as_str())
1211            };
1212            xml.push_str(&format!(
1213                "        <sh:path rdf:resource=\"{}{}\"/>\n",
1214                ns, local
1215            ));
1216            if let Some(dt) = &prop.datatype {
1217                let dt_uri = if dt.starts_with("xsd:") {
1218                    dt.replace("xsd:", "http://www.w3.org/2001/XMLSchema#")
1219                } else {
1220                    dt.clone()
1221                };
1222                xml.push_str(&format!(
1223                    "        <sh:datatype rdf:resource=\"{}\"/>\n",
1224                    dt_uri
1225                ));
1226            }
1227            if let Some(min) = prop.min_count {
1228                xml.push_str(&format!("        <sh:minCount>{}</sh:minCount>\n", min));
1229            }
1230            if let Some(max) = prop.max_count {
1231                xml.push_str(&format!("        <sh:maxCount>{}</sh:maxCount>\n", max));
1232            }
1233            if let Some(min_ex) = &prop.min_exclusive {
1234                xml.push_str(&format!("        <sh:minExclusive rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\">{}</sh:minExclusive>\n", min_ex));
1235            }
1236            xml.push_str("      </rdf:Description>\n");
1237            xml.push_str("    </sh:property>\n");
1238        }
1239        xml.push_str("  </sh:NodeShape>\n\n");
1240        xml
1241    }
1242
1243    pub fn escape_turtle_literal(input: &str) -> String {
1244        let mut escaped = String::with_capacity(input.len());
1245        for ch in input.chars() {
1246            match ch {
1247                '\\' => escaped.push_str("\\\\"),
1248                '"' => escaped.push_str("\\\""),
1249                '\n' => escaped.push_str("\\n"),
1250                '\r' => escaped.push_str("\\r"),
1251                '\t' => escaped.push_str("\\t"),
1252                '\x08' => escaped.push_str("\\b"), // backspace
1253                '\x0C' => escaped.push_str("\\f"), // form feed
1254                other => escaped.push(other),
1255            }
1256        }
1257        escaped
1258    }
1259
1260    fn uri_encode(s: &str) -> String {
1261        utf8_percent_encode(s, URI_ENCODE_SET).to_string()
1262    }
1263
1264    /// Mint a stable IRI for an entity instance, kind-prefixed like the existing
1265    /// `flow_`/`pattern_` nodes.
1266    ///
1267    /// The name alone is sufficient: `Graph::insert_entity_instance` rejects any
1268    /// instance whose name already exists, so instance names are unique across the
1269    /// whole graph. Keeping the entity type out of the IRI also means retyping an
1270    /// instance does not change its identity. If that uniqueness rule is ever
1271    /// relaxed, this scheme must be revisited.
1272    fn entity_instance_iri(instance: &Instance) -> String {
1273        format!("sea:instance_{}", Self::uri_encode(instance.name()))
1274    }
1275
1276    fn policy_iri(policy: &Policy) -> String {
1277        format!("sea:policy_{}", Self::uri_encode(&policy.name))
1278    }
1279
1280    /// XSD datatype for a declared field type. `EntityRef` deliberately maps to a
1281    /// literal: the referenced key value is preserved verbatim rather than minted
1282    /// into an IRI that could dangle when the model has not been validated.
1283    fn xsd_datatype(field_type: &FieldType) -> &'static str {
1284        match field_type {
1285            FieldType::Scalar { scalar } => match scalar {
1286                ScalarType::String | ScalarType::Uuid => "xsd:string",
1287                ScalarType::Int => "xsd:integer",
1288                ScalarType::Decimal => "xsd:decimal",
1289                ScalarType::Bool => "xsd:boolean",
1290                ScalarType::Timestamp => "xsd:dateTime",
1291            },
1292            FieldType::Quantity { .. } => "xsd:decimal",
1293            FieldType::EntityRef { .. } | FieldType::Enum { .. } | FieldType::List { .. } => {
1294                "xsd:string"
1295            }
1296        }
1297    }
1298
1299    /// Render one instance field as a Turtle object term. Returns `None` for JSON
1300    /// null, which represents an absent field rather than an empty value.
1301    fn instance_field_object(value: &Value, declared: Option<&FieldType>) -> Option<String> {
1302        if value.is_null() {
1303            return None;
1304        }
1305
1306        let literal = match value {
1307            Value::String(text) => text.clone(),
1308            Value::Bool(flag) => flag.to_string(),
1309            Value::Number(number) => number.to_string(),
1310            // Lists and nested objects have no lossless RDF literal form; keep the
1311            // authored JSON verbatim rather than flattening it away.
1312            other => other.to_string(),
1313        };
1314
1315        let datatype = match declared {
1316            Some(field_type) => Self::xsd_datatype(field_type),
1317            None => match value {
1318                Value::Bool(_) => "xsd:boolean",
1319                Value::Number(_) => "xsd:decimal",
1320                _ => "xsd:string",
1321            },
1322        };
1323
1324        // `Value::Number` literals are stored as f64 (see the parser's
1325        // Decimal -> f64 conversion for numeric literals), so a field
1326        // declared `int` with value 50000 stringifies as "50000.0" —
1327        // not a valid xsd:integer lexical form (XSD forbids a decimal
1328        // point in the integer value space). Normalize to signed-integer
1329        // text when the value is whole; a genuinely fractional value under
1330        // a declared `int` field is an upstream data inconsistency, not
1331        // something to paper over as malformed Turtle, so it downgrades to
1332        // xsd:string like any other value that fails the decimal guard.
1333        if datatype == "xsd:integer" {
1334            if let Value::Number(number) = value {
1335                match number.as_f64() {
1336                    Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18 => {
1337                        return Some(format!(
1338                            "\"{}\"^^xsd:integer",
1339                            Self::escape_turtle_literal(&(f as i64).to_string())
1340                        ));
1341                    }
1342                    _ => {
1343                        return Some(format!(
1344                            "\"{}\"^^xsd:string",
1345                            Self::escape_turtle_literal(&literal)
1346                        ));
1347                    }
1348                }
1349            }
1350        }
1351
1352        // Numeric literals go through the same decimal guard as flow quantities;
1353        // a value that cannot be a safe Turtle decimal degrades to a string rather
1354        // than emitting malformed Turtle.
1355        if datatype == "xsd:decimal" && Self::validate_turtle_decimal(&literal).is_err() {
1356            return Some(format!(
1357                "\"{}\"^^xsd:string",
1358                Self::escape_turtle_literal(&literal)
1359            ));
1360        }
1361
1362        Some(format!(
1363            "\"{}\"^^{}",
1364            Self::escape_turtle_literal(&literal),
1365            datatype
1366        ))
1367    }
1368
1369    fn validate_turtle_decimal(decimal_str: &str) -> Result<(), String> {
1370        // Basic validation for safe decimal literals in Turtle
1371        let trimmed = decimal_str.trim();
1372
1373        // Check for invalid characters that could break Turtle syntax
1374        if trimmed
1375            .chars()
1376            .any(|ch| matches!(ch, '"' | '\'' | '\\' | '\n' | '\r' | '\t'))
1377        {
1378            return Err("Decimal contains invalid characters".to_string());
1379        }
1380
1381        // Ensure it looks like a valid decimal number
1382        if trimmed.is_empty() {
1383            return Err("Decimal is empty".to_string());
1384        }
1385
1386        // Basic pattern check: optional sign, digits, optional fractional part
1387        let mut has_digit = false;
1388        let mut chars = trimmed.chars().peekable();
1389
1390        // Optional sign
1391        if matches!(chars.peek(), Some('+') | Some('-')) {
1392            chars.next();
1393        }
1394
1395        // Digits and optional fractional part
1396        while let Some(ch) = chars.next() {
1397            if ch.is_ascii_digit() {
1398                has_digit = true;
1399            } else if ch == '.' {
1400                // Check fractional part
1401                if !chars.next().is_some_and(|c| c.is_ascii_digit()) {
1402                    return Err("Invalid decimal format".to_string());
1403                }
1404                for c in chars.by_ref() {
1405                    if !c.is_ascii_digit() {
1406                        return Err("Invalid decimal format".to_string());
1407                    }
1408                }
1409                break;
1410            } else {
1411                return Err("Invalid decimal format".to_string());
1412            }
1413        }
1414
1415        if !has_digit {
1416            return Err("Invalid decimal format".to_string());
1417        }
1418
1419        Ok(())
1420    }
1421
1422    fn clean_uri(uri: &str) -> String {
1423        if uri.contains(':') {
1424            let parts: Vec<&str> = uri.splitn(2, ':').collect();
1425            if parts.len() == 2 {
1426                let (prefix, name) = (parts[0], parts[1]);
1427
1428                // Check for standard RDF/XSD prefixes
1429                let standard_prefixes = [
1430                    ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
1431                    ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
1432                    ("xsd", "http://www.w3.org/2001/XMLSchema#"),
1433                    ("owl", "http://www.w3.org/2002/07/owl#"),
1434                    ("sh", "http://www.w3.org/ns/shacl#"),
1435                    ("sea", "http://domainforge.ai/sea#"),
1436                ];
1437
1438                for (std_prefix, namespace) in &standard_prefixes {
1439                    if prefix == *std_prefix {
1440                        return format!("{}{}", namespace, name);
1441                    }
1442                }
1443
1444                // Fall back to original behavior for unknown prefixes
1445                return format!("http://domainforge.ai/{}#{}", prefix, name);
1446            }
1447        }
1448        uri.to_string()
1449    }
1450
1451    fn shorten_token(token: &str) -> String {
1452        let t = token.trim();
1453        // remove enclosing angle brackets
1454        let value = if t.starts_with('<') && t.ends_with('>') {
1455            &t[1..t.len() - 1]
1456        } else {
1457            t
1458        };
1459
1460        // If contains typed literal with full datatype like "123"^^<http://www.w3.org/2001/XMLSchema#decimal>
1461        if value.contains("^^<http://www.w3.org/2001/XMLSchema#") {
1462            // replace the full URI with xsd: prefix
1463            if let Some(pos) = value.find("^^<http://www.w3.org/2001/XMLSchema#") {
1464                let (lit, rest) = value.split_at(pos);
1465                if rest.contains("decimal") {
1466                    return format!("{}^^xsd:decimal", lit.trim());
1467                } else if rest.contains("string") {
1468                    return format!("{}^^xsd:string", lit.trim());
1469                }
1470            }
1471        }
1472
1473        // Map common vocabularies
1474        let mappings = [
1475            ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:"),
1476            ("http://www.w3.org/2000/01/rdf-schema#", "rdfs:"),
1477            ("http://www.w3.org/2001/XMLSchema#", "xsd:"),
1478            ("http://www.w3.org/2002/07/owl#", "owl:"),
1479            ("http://www.w3.org/ns/shacl#", "sh:"),
1480            ("http://domainforge.ai/sea#", "sea:"),
1481            ("http://domainforge.ai/rdfs#", "rdfs:"),
1482        ];
1483
1484        for (ns, prefix) in &mappings {
1485            if let Some(stripped) = value.strip_prefix(ns) {
1486                return format!("{}{}", prefix, stripped);
1487            }
1488        }
1489
1490        // Fall back to original token
1491        t.to_string()
1492    }
1493
1494    pub fn escape_xml(input: &str) -> String {
1495        let mut escaped = String::with_capacity(input.len());
1496        for ch in input.chars() {
1497            match ch {
1498                '&' => escaped.push_str("&amp;"),
1499                '<' => escaped.push_str("&lt;"),
1500                '>' => escaped.push_str("&gt;"),
1501                '"' => escaped.push_str("&quot;"),
1502                '\'' => escaped.push_str("&apos;"),
1503                other => escaped.push(other),
1504            }
1505        }
1506        escaped
1507    }
1508
1509    fn parse_escaped_value<I>(chars: &mut I) -> String
1510    where
1511        I: Iterator<Item = char>,
1512    {
1513        let mut value = String::new();
1514        let mut escaped = false;
1515
1516        for ch in chars.by_ref() {
1517            if escaped {
1518                let resolved = match ch {
1519                    'n' => '\n',
1520                    't' => '\t',
1521                    'r' => '\r',
1522                    '"' => '"',
1523                    '\\' => '\\',
1524                    other => {
1525                        value.push('\\');
1526                        other
1527                    }
1528                };
1529                value.push(resolved);
1530                escaped = false;
1531                continue;
1532            }
1533
1534            match ch {
1535                '\\' => escaped = true,
1536                '"' => break,
1537                other => value.push(other),
1538            }
1539        }
1540
1541        value
1542    }
1543
1544    fn parse_typed_literal(literal: &str) -> (String, Option<TypedLiteralSuffix>) {
1545        if !literal.starts_with('"') {
1546            return (literal.to_string(), None);
1547        }
1548
1549        let mut chars = literal.chars();
1550        chars.next();
1551        let value = Self::parse_escaped_value(&mut chars);
1552
1553        let remainder: String = chars.collect();
1554        let trimmed = remainder.trim();
1555
1556        let suffix = if let Some(rest) = trimmed.strip_prefix("^^") {
1557            let datatype = rest.trim();
1558            if datatype.is_empty() {
1559                None
1560            } else {
1561                Some(TypedLiteralSuffix::Datatype(datatype.to_string()))
1562            }
1563        } else if let Some(rest) = trimmed.strip_prefix('@') {
1564            let language = rest.trim();
1565            if language.is_empty() {
1566                None
1567            } else {
1568                Some(TypedLiteralSuffix::Language(language.to_string()))
1569            }
1570        } else {
1571            None
1572        };
1573
1574        (value, suffix)
1575    }
1576
1577    /// Validates that a string is a safe RDF term for use in triples.
1578    /// Returns true if the term is valid (no quotes, angle brackets, control chars, backslashes, or illegal colons).
1579    fn is_valid_rdf_term(term: &str) -> bool {
1580        // Check for dangerous characters
1581        if term.contains('"') || term.contains('<') || term.contains('>') || term.contains('\\') {
1582            return false;
1583        }
1584
1585        // Check for control characters
1586        if term.chars().any(|c| c.is_control()) {
1587            return false;
1588        }
1589
1590        // Check for illegal colons (only allow prefixed names like "sea:Something" or local names without colons)
1591        // A valid prefixed name has exactly one colon not at the start or end
1592        let colon_count = term.matches(':').count();
1593        if colon_count > 1 {
1594            return false;
1595        }
1596        if colon_count == 1 && (term.starts_with(':') || term.ends_with(':')) {
1597            return false;
1598        }
1599
1600        true
1601    }
1602}
1603
1604enum TypedLiteralSuffix {
1605    Datatype(String),
1606    Language(String),
1607}
1608
1609impl Default for KnowledgeGraph {
1610    fn default() -> Self {
1611        Self::new()
1612    }
1613}
1614
1615impl Graph {
1616    pub fn export_rdf(&self, format: &str) -> Result<String, KgError> {
1617        let kg = KnowledgeGraph::from_graph(self)?;
1618        match format {
1619            "turtle" => Ok(kg.to_turtle()),
1620            "rdf-xml" => Ok(kg.to_rdf_xml()),
1621            _ => Err(KgError::UnsupportedFormat(format.to_string())),
1622        }
1623    }
1624}
1625
1626#[cfg(test)]
1627mod tests {
1628    use super::*;
1629    use crate::primitives::{Entity, Flow, Resource};
1630    use rust_decimal::Decimal;
1631
1632    #[test]
1633    fn test_export_to_rdf_turtle() {
1634        let mut graph = Graph::new();
1635
1636        let entity1 = Entity::new_with_namespace("Supplier", "supply_chain");
1637        let entity2 = Entity::new_with_namespace("Manufacturer", "supply_chain");
1638        let resource = Resource::new_with_namespace(
1639            "Parts",
1640            crate::units::unit_from_string("kg"),
1641            "supply_chain",
1642        );
1643
1644        let entity1_id = entity1.id().clone();
1645        let entity2_id = entity2.id().clone();
1646        let resource_id = resource.id().clone();
1647
1648        graph.add_entity(entity1).unwrap();
1649        graph.add_entity(entity2).unwrap();
1650        graph.add_resource(resource).unwrap();
1651
1652        #[allow(deprecated)]
1653        let flow = Flow::new(resource_id, entity1_id, entity2_id, Decimal::new(100, 0));
1654        graph.add_flow(flow).unwrap();
1655
1656        let rdf_turtle = graph.export_rdf("turtle").unwrap();
1657
1658        assert!(rdf_turtle.contains("sea:Entity"));
1659        assert!(rdf_turtle.contains("sea:hasResource"));
1660        assert!(rdf_turtle.contains("@prefix"));
1661    }
1662
1663    #[test]
1664    fn test_export_to_rdf_xml() {
1665        let mut graph = Graph::new();
1666
1667        let entity = Entity::new_with_namespace("TestEntity", "default".to_string());
1668        graph.add_entity(entity).unwrap();
1669
1670        let rdf_xml = graph.export_rdf("rdf-xml").unwrap();
1671
1672        assert!(rdf_xml.contains("<?xml"));
1673        assert!(rdf_xml.contains("rdf:RDF"));
1674    }
1675
1676    #[test]
1677    fn test_unsupported_format() {
1678        let graph = Graph::new();
1679        let result = graph.export_rdf("json-ld");
1680
1681        assert!(result.is_err());
1682        assert!(matches!(result.unwrap_err(), KgError::UnsupportedFormat(_)));
1683    }
1684
1685    #[test]
1686    fn test_export_rdf_turtle_encodes_special_characters_and_literals() {
1687        let mut graph = Graph::new();
1688
1689        let entity_space = Entity::new_with_namespace("Entity With Space", "default".to_string());
1690        let entity_colon = Entity::new_with_namespace("Entity:Colon", "default".to_string());
1691        let entity_slash = Entity::new_with_namespace("Entity/Slash", "default".to_string());
1692        let entity_hash = Entity::new_with_namespace("Entity#Hash", "default".to_string());
1693
1694        graph.add_entity(entity_space.clone()).unwrap();
1695        graph.add_entity(entity_colon.clone()).unwrap();
1696        graph.add_entity(entity_slash.clone()).unwrap();
1697        graph.add_entity(entity_hash.clone()).unwrap();
1698
1699        let resource = Resource::new_with_namespace(
1700            "Resource:Name/Hash",
1701            crate::units::unit_from_string("units"),
1702            "default".to_string(),
1703        );
1704        let resource_id = resource.id().clone();
1705        graph.add_resource(resource).unwrap();
1706
1707        let flow = Flow::new(
1708            resource_id,
1709            entity_space.id().clone(),
1710            entity_colon.id().clone(),
1711            Decimal::new(42, 0),
1712        );
1713        graph.add_flow(flow).unwrap();
1714
1715        let turtle = graph.export_rdf("turtle").unwrap();
1716        assert!(turtle.contains("sea:Entity%20With%20Space"));
1717        assert!(turtle.contains("sea:Entity%3AColon"));
1718        assert!(turtle.contains("sea:Entity%2FSlash"));
1719        assert!(turtle.contains("sea:Entity%23Hash"));
1720        assert!(turtle.contains("sea:Resource%3AName%2FHash"));
1721        assert!(turtle.contains("\"42\"^^xsd:decimal"));
1722    }
1723
1724    #[test]
1725    fn test_rdf_xml_escapes_special_literals_and_language_tags() {
1726        let mut kg = KnowledgeGraph::new();
1727
1728        kg.triples.push(Triple {
1729            subject: "sea:testEntity".to_string(),
1730            predicate: "sea:hasNumericValue".to_string(),
1731            object: "\"100\"^^xsd:decimal".to_string(),
1732        });
1733        kg.triples.push(Triple {
1734            subject: "sea:testEntity".to_string(),
1735            predicate: "sea:description".to_string(),
1736            object: "\"Hello & <World>\"@en".to_string(),
1737        });
1738
1739        let xml = kg.to_rdf_xml();
1740        assert!(xml.contains("rdf:datatype=\"http://www.w3.org/2001/XMLSchema#decimal\""));
1741        assert!(xml.contains(">100<"));
1742        assert!(xml.contains("xml:lang=\"en\""));
1743        assert!(xml.contains("&amp;"));
1744        assert!(xml.contains("&lt;"));
1745        assert!(xml.contains("&gt;"));
1746    }
1747}