1#[cfg(test)]
43mod tests;
44
45pub mod coherence_gate;
46pub use coherence_gate::{CoherenceGate, CoherenceGateConfig};
47
48use crate::codegen::go::GoCodeGenerator;
49use crate::graph::types::CachedResult;
50use crate::graph::Graph;
51use crate::utils::error::Error as GgenError;
52use crate::validation::soundness_gates::{
53 check_boundedness, check_deadlock_freedom, check_liveness, SoundnessViolation,
54};
55use ggen_graph::{CoherenceChecker, CoherenceReport};
56use sha2::{Digest, Sha256};
57use std::collections::BTreeMap;
58use std::fs;
59use std::path::{Path, PathBuf};
60use std::time::{Duration, Instant};
61
62pub const SPARQL_TIMEOUT_SECS: u64 = 30;
68
69#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum SyncLanguage {
76 Go,
78 Elixir,
80 Rust,
82 TypeScript,
84 Python,
86 Auto,
88}
89
90impl std::fmt::Display for SyncLanguage {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 match self {
93 Self::Go => write!(f, "go"),
94 Self::Elixir => write!(f, "elixir"),
95 Self::Rust => write!(f, "rust"),
96 Self::TypeScript => write!(f, "typescript"),
97 Self::Python => write!(f, "python"),
98 Self::Auto => write!(f, "auto"),
99 }
100 }
101}
102
103impl std::str::FromStr for SyncLanguage {
104 type Err = SyncError;
105
106 fn from_str(s: &str) -> Result<Self, Self::Err> {
107 match s.to_ascii_lowercase().as_str() {
108 "go" | "golang" => Ok(Self::Go),
109 "elixir" => Ok(Self::Elixir),
110 "rust" => Ok(Self::Rust),
111 "typescript" | "ts" => Ok(Self::TypeScript),
112 "python" | "py" => Ok(Self::Python),
113 "auto" => Ok(Self::Auto),
114 other => Err(SyncError::InvalidLanguage(other.to_string())),
115 }
116 }
117}
118
119#[derive(Debug, Clone)]
121pub struct SyncConfig {
122 pub ontology_path: PathBuf,
124
125 pub queries_dir: PathBuf,
128
129 pub output_dir: PathBuf,
132
133 pub language: SyncLanguage,
135
136 pub validate: bool,
141
142 pub dry_run: bool,
146}
147
148#[derive(Debug, Clone)]
150pub struct SyncResult {
151 pub files_generated: Vec<PathBuf>,
154
155 pub soundness_violations: Vec<SoundnessViolation>,
158
159 pub elapsed_ms: u64,
161
162 pub receipt: String,
165
166 pub coherence_report: Option<CoherenceReport>,
168}
169
170#[derive(Debug, thiserror::Error)]
172pub enum SyncError {
173 #[error("ontology load failed: {0}")]
175 OntologyLoad(String),
176
177 #[error("ontology parse failed: {0}")]
179 OntologyParse(String),
180
181 #[error("queries directory error: {0}")]
183 QueriesDir(String),
184
185 #[error("query file read error ({path}): {message}")]
187 QueryRead {
188 path: PathBuf,
190 message: String,
192 },
193
194 #[error("SPARQL execution error ({query}): {message}")]
196 SparqlExecution {
197 query: String,
199 message: String,
201 },
202
203 #[error("SPARQL timeout after {SPARQL_TIMEOUT_SECS}s for query '{query}'")]
205 SparqlTimeout {
206 query: String,
208 },
209
210 #[error("code generation failed: {0}")]
212 Codegen(String),
213
214 #[error("file write error ({path}): {message}")]
216 FileWrite {
217 path: PathBuf,
219 message: String,
221 },
222
223 #[error("cannot create output directory ({path}): {message}")]
225 OutputDir {
226 path: PathBuf,
228 message: String,
230 },
231
232 #[error("unknown language '{0}'; valid values: go, elixir, rust, typescript, python, auto")]
234 InvalidLanguage(String),
235
236 #[error("coherence violation: {detail}")]
238 CoherenceViolation {
239 detail: String,
241 report: CoherenceReport,
243 },
244}
245
246impl From<GgenError> for SyncError {
248 fn from(e: GgenError) -> Self {
249 Self::OntologyParse(e.to_string())
250 }
251}
252
253pub fn sync(config: SyncConfig) -> Result<SyncResult, SyncError> {
278 let start = Instant::now();
279
280 let (graph, ontology_bytes) = load_ontology(&config.ontology_path)?;
284
285 let bindings = run_sparql_queries(&graph, &config.queries_dir)?;
289
290 let generated = generate_code(&config, &bindings)?;
294
295 let mut soundness_violations = Vec::new();
299 if config.validate {
300 for (_path, source) in &generated {
301 soundness_violations.extend(check_deadlock_freedom(source));
302 soundness_violations.extend(check_liveness(source));
303 soundness_violations.extend(check_boundedness(source));
304 }
305 }
306
307 let coherence_gate_config = CoherenceGateConfig {
313 allow_count_discrepancy: true,
314 check_event_log: !config.dry_run,
315 expectations: None,
316 };
317 let gate = CoherenceGate::new(coherence_gate_config);
318
319 let generated_pairs: Vec<(String, String)> = generated
321 .iter()
322 .map(|(p, c)| (p.to_string_lossy().to_string(), c.clone()))
323 .collect();
324
325 let coherence_report = gate.validate(&ontology_bytes, &generated_pairs, &[])?;
326
327 let files_generated = write_files(&config, &generated)?;
332
333 let receipt = compute_receipt(&ontology_bytes, &generated);
334
335 if !config.dry_run {
339 if let Ok(json) = serde_json::to_string_pretty(&coherence_report) {
340 let receipts_dir = config.output_dir.join(".ggen").join("receipts");
341 let _ = std::fs::create_dir_all(&receipts_dir);
342 let _ = std::fs::write(receipts_dir.join("coherence-latest.json"), json);
343 }
344 }
345
346 let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
347
348 Ok(SyncResult {
349 files_generated,
350 soundness_violations,
351 elapsed_ms,
352 receipt,
353 coherence_report: Some(coherence_report),
354 })
355}
356
357fn load_ontology(path: &Path) -> Result<(Graph, Vec<u8>), SyncError> {
365 let bytes = fs::read(path).map_err(|e| SyncError::OntologyLoad(e.to_string()))?;
366
367 let graph = Graph::new().map_err(|e| SyncError::OntologyParse(e.to_string()))?;
368 graph
369 .insert_turtle(
370 std::str::from_utf8(&bytes)
371 .map_err(|e| SyncError::OntologyParse(format!("UTF-8 error: {e}")))?,
372 )
373 .map_err(|e| SyncError::OntologyParse(e.to_string()))?;
374
375 Ok((graph, bytes))
376}
377
378pub type QueryRow = BTreeMap<String, String>;
380
381fn run_sparql_queries(graph: &Graph, queries_dir: &Path) -> Result<Vec<QueryRow>, SyncError> {
386 if !queries_dir.exists() {
387 return Err(SyncError::QueriesDir(format!(
388 "directory does not exist: {}",
389 queries_dir.display()
390 )));
391 }
392
393 let mut query_files: Vec<PathBuf> = fs::read_dir(queries_dir)
395 .map_err(|e| SyncError::QueriesDir(e.to_string()))?
396 .filter_map(|entry| entry.ok())
397 .map(|e| e.path())
398 .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("rq"))
399 .collect();
400 query_files.sort();
401
402 let timeout = Duration::from_secs(SPARQL_TIMEOUT_SECS);
403 let mut all_rows: Vec<QueryRow> = Vec::new();
404
405 for query_path in &query_files {
406 let query_name = query_path
407 .file_stem()
408 .and_then(|s| s.to_str())
409 .unwrap_or("unknown")
410 .to_string();
411
412 let sparql = fs::read_to_string(query_path).map_err(|e| SyncError::QueryRead {
413 path: query_path.clone(),
414 message: e.to_string(),
415 })?;
416
417 let rows = execute_with_timeout(graph, &sparql, &query_name, timeout)?;
419 all_rows.extend(rows);
420 }
421
422 Ok(all_rows)
423}
424
425fn execute_with_timeout(
432 graph: &Graph, sparql: &str, query_name: &str, timeout: Duration,
433) -> Result<Vec<QueryRow>, SyncError> {
434 let before = Instant::now();
435
436 let cached = graph
437 .query_cached(sparql)
438 .map_err(|e| SyncError::SparqlExecution {
439 query: query_name.to_string(),
440 message: e.to_string(),
441 })?;
442
443 if before.elapsed() > timeout {
444 return Err(SyncError::SparqlTimeout {
445 query: query_name.to_string(),
446 });
447 }
448
449 match cached {
450 CachedResult::Solutions(rows) => Ok(rows),
451 CachedResult::Boolean(_) | CachedResult::Graph(_) => {
452 Ok(Vec::new())
454 }
455 }
456}
457
458fn generate_code(
463 config: &SyncConfig, bindings: &[QueryRow],
464) -> Result<Vec<(PathBuf, String)>, SyncError> {
465 let effective_language = resolve_language(&config.language, &config.ontology_path);
466
467 match effective_language {
468 SyncLanguage::Go => generate_go(bindings),
469 SyncLanguage::Elixir => generate_elixir(bindings),
470 SyncLanguage::Rust => generate_rust(bindings),
471 SyncLanguage::TypeScript => generate_typescript(bindings),
472 SyncLanguage::Python => generate_python(bindings),
473 SyncLanguage::Auto => {
474 Err(SyncError::InvalidLanguage("auto".to_string()))
477 }
478 }
479}
480
481fn resolve_language(lang: &SyncLanguage, ontology_path: &Path) -> SyncLanguage {
486 if *lang != SyncLanguage::Auto {
487 return lang.clone();
488 }
489 let stem = ontology_path
491 .file_stem()
492 .and_then(|s| s.to_str())
493 .unwrap_or("")
494 .to_ascii_lowercase();
495
496 if stem.contains("elixir") || stem.contains("canopy") || stem.contains("osa") {
497 SyncLanguage::Elixir
498 } else if stem.contains("rust") {
499 SyncLanguage::Rust
500 } else if stem.contains("typescript") || stem.contains("svelte") {
501 SyncLanguage::TypeScript
502 } else {
503 SyncLanguage::Go
505 }
506}
507
508fn generate_go(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
518 let mut outputs: Vec<(PathBuf, String)> = Vec::new();
519
520 let service_groups = group_by_key(bindings, "service");
522
523 if service_groups.is_empty() {
524 let source = GoCodeGenerator::generate_service_struct("GeneratedService", &[])
526 .map_err(SyncError::Codegen)?;
527 outputs.push((PathBuf::from("generated_service.go"), source));
528 } else {
529 for service_name in service_groups.keys() {
530 let source = GoCodeGenerator::generate_service_struct(service_name, &[])
531 .map_err(SyncError::Codegen)?;
532
533 let file_name = format!("{}.go", service_name.to_ascii_lowercase().replace(' ', "_"));
534 outputs.push((PathBuf::from(file_name), source));
535 }
536 }
537
538 Ok(outputs)
539}
540
541fn generate_elixir(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
543 let module_groups = group_by_key(bindings, "service");
544
545 let mut outputs: Vec<(PathBuf, String)> = Vec::new();
546
547 if module_groups.is_empty() {
548 let source = elixir_genserver_template("GeneratedService");
549 outputs.push((PathBuf::from("generated_service.ex"), source));
550 } else {
551 for module_name in module_groups.keys() {
552 let source = elixir_genserver_template(module_name);
553 let file_name = format!("{}.ex", module_name.to_ascii_lowercase().replace(' ', "_"));
554 outputs.push((PathBuf::from(file_name), source));
555 }
556 }
557
558 Ok(outputs)
559}
560
561fn generate_rust(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
563 let struct_groups = group_by_key(bindings, "service");
564
565 let mut outputs: Vec<(PathBuf, String)> = Vec::new();
566
567 if struct_groups.is_empty() {
568 let source = rust_struct_template("GeneratedService");
569 outputs.push((PathBuf::from("generated_service.rs"), source));
570 } else {
571 for struct_name in struct_groups.keys() {
572 let source = rust_struct_template(struct_name);
573 let file_name = format!("{}.rs", struct_name.to_ascii_lowercase().replace(' ', "_"));
574 outputs.push((PathBuf::from(file_name), source));
575 }
576 }
577
578 Ok(outputs)
579}
580
581fn generate_typescript(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
583 let interface_groups = group_by_key(bindings, "service");
584
585 let mut outputs: Vec<(PathBuf, String)> = Vec::new();
586
587 if interface_groups.is_empty() {
588 let source = typescript_interface_template("GeneratedService");
589 outputs.push((PathBuf::from("generatedService.ts"), source));
590 } else {
591 for interface_name in interface_groups.keys() {
592 let source = typescript_interface_template(interface_name);
593 let file_name = format!("{}.ts", to_camel_case(interface_name));
594 outputs.push((PathBuf::from(file_name), source));
595 }
596 }
597
598 Ok(outputs)
599}
600
601fn generate_python(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
603 let class_groups = group_by_key(bindings, "service");
604
605 let mut outputs: Vec<(PathBuf, String)> = Vec::new();
606
607 if class_groups.is_empty() {
608 let source = python_dataclass_template("GeneratedService");
609 outputs.push((PathBuf::from("generated_service.py"), source));
610 } else {
611 for class_name in class_groups.keys() {
612 let source = python_dataclass_template(class_name);
613 let file_name = format!("{}.py", class_name.to_ascii_lowercase().replace(' ', "_"));
614 outputs.push((PathBuf::from(file_name), source));
615 }
616 }
617
618 Ok(outputs)
619}
620
621fn elixir_genserver_template(module_name: &str) -> String {
626 format!(
627 r#"defmodule {module_name} do
628 @moduledoc "Generated by ggen sync"
629 use GenServer
630
631 def start_link(opts \\ []) do
632 GenServer.start_link(__MODULE__, :ok, opts)
633 end
634
635 def init(:ok) do
636 {{:ok, %{{}}}}
637 end
638end
639"#,
640 module_name = module_name
641 )
642}
643
644fn rust_struct_template(struct_name: &str) -> String {
645 format!(
646 r"//! Generated by ggen sync
647use serde::{{Deserialize, Serialize}};
648
649/// {struct_name} — generated from ontology
650#[derive(Debug, Clone, Serialize, Deserialize)]
651pub struct {struct_name} {{
652 pub id: String,
653}}
654
655impl {struct_name} {{
656 /// Create a new instance
657 pub fn new(id: impl Into<String>) -> Self {{
658 Self {{ id: id.into() }}
659 }}
660}}
661",
662 struct_name = struct_name
663 )
664}
665
666fn typescript_interface_template(interface_name: &str) -> String {
667 format!(
668 r"// Generated by ggen sync
669
670export interface {interface_name} {{
671 id: string;
672}}
673
674export function create{interface_name}(id: string): {interface_name} {{
675 return {{ id }};
676}}
677",
678 interface_name = interface_name
679 )
680}
681
682fn python_dataclass_template(class_name: &str) -> String {
683 format!(
684 r"# Generated by ggen sync
685from dataclasses import dataclass
686
687
688@dataclass
689class {class_name}:
690 id: str
691",
692 class_name = class_name
693 )
694}
695
696fn write_files(
704 config: &SyncConfig, generated: &[(PathBuf, String)],
705) -> Result<Vec<PathBuf>, SyncError> {
706 if !config.dry_run && !config.output_dir.exists() {
707 fs::create_dir_all(&config.output_dir).map_err(|e| SyncError::OutputDir {
708 path: config.output_dir.clone(),
709 message: e.to_string(),
710 })?;
711 }
712
713 let mut written = Vec::new();
714
715 for (rel_path, source) in generated {
716 let abs_path = config.output_dir.join(rel_path);
717
718 if !config.dry_run {
719 if let Some(parent) = abs_path.parent() {
721 if !parent.exists() {
722 fs::create_dir_all(parent).map_err(|e| SyncError::OutputDir {
723 path: parent.to_path_buf(),
724 message: e.to_string(),
725 })?;
726 }
727 }
728
729 fs::write(&abs_path, source).map_err(|e| SyncError::FileWrite {
730 path: abs_path.clone(),
731 message: e.to_string(),
732 })?;
733 }
734
735 written.push(abs_path);
736 }
737
738 Ok(written)
739}
740
741fn compute_receipt(ontology_bytes: &[u8], generated: &[(PathBuf, String)]) -> String {
750 let mut hasher = Sha256::new();
751 hasher.update(ontology_bytes);
752
753 let mut sorted: Vec<(&PathBuf, &str)> =
755 generated.iter().map(|(p, s)| (p, s.as_str())).collect();
756 sorted.sort_by_key(|(p, _)| p.as_path());
757
758 for (_path, source) in &sorted {
759 hasher.update(source.as_bytes());
760 }
761
762 let digest = hasher.finalize();
763 hex::encode(digest)
764}
765
766fn group_by_key(rows: &[QueryRow], key: &str) -> BTreeMap<String, Vec<QueryRow>> {
775 let mut groups: BTreeMap<String, Vec<QueryRow>> = BTreeMap::new();
776 for row in rows {
777 if let Some(value) = row.get(key) {
778 let clean = strip_iri_brackets(value);
780 groups.entry(clean).or_default().push(row.clone());
781 }
782 }
783 groups
784}
785
786fn strip_iri_brackets(iri: &str) -> String {
789 let inner = iri.trim_start_matches('<').trim_end_matches('>');
790
791 if let Some(fragment) = inner.rsplit_once('#').map(|(_, f)| f) {
793 return fragment.to_string();
794 }
795 if let Some(segment) = inner.rsplit('/').next() {
797 if !segment.is_empty() {
798 return segment.to_string();
799 }
800 }
801 inner.to_string()
802}
803
804fn to_camel_case(s: &str) -> String {
806 let mut result = String::new();
807 let mut capitalise_next = false;
808 for (i, c) in s.chars().enumerate() {
809 if c == ' ' || c == '_' || c == '-' {
810 capitalise_next = true;
811 } else if capitalise_next {
812 result.extend(c.to_uppercase());
813 capitalise_next = false;
814 } else if i == 0 {
815 result.extend(c.to_lowercase());
816 } else {
817 result.push(c);
818 }
819 }
820 result
821}