Skip to main content

ggen_core/sync/
mod.rs

1//! Sync orchestrator — full platform regeneration pipeline
2//!
3//! Implements the five-stage pipeline (with 4.5 coherence gate) that drives `ggen sync`:
4//!
5//! ```text
6//! Stage 1    — Load    : Read .ttl ontology → in-memory Graph
7//! Stage 2    — Extract : Execute .rq SPARQL SELECT files → row bindings
8//! Stage 3    — Generate: Call language-specific codegen from bindings
9//! Stage 4    — Validate: Run WvdA soundness gates on generated source text (non-fatal)
10//! Stage 4.5  — Coherence: Check O ≅ A ≅ L three-pole isomorphism (FATAL — blocks Stage 5)
11//! Stage 5    — Write   : Flush files to disk; compute sha256 receipt (only if Stage 4.5 admits)
12//! Stage 5b   — Report  : Write coherence report to disk (observability only)
13//! ```
14//!
15//! ## Armstrong / WvdA compliance
16//!
17//! - Every blocking or I/O operation returns `Result<T, SyncError>` — no `.unwrap()`.
18//! - The pipeline stages are **independent**: a failure in Stage 3 does not corrupt
19//!   the already-loaded ontology graph from Stage 1.
20//! - The receipt is **deterministic**: `sha256(ontology_content || sorted_file_contents)`.
21//! - SPARQL execution time is bounded by [`SPARQL_TIMEOUT_SECS`].
22//!
23//! ## Quick start
24//!
25//! ```rust,no_run
26//! use crate::sync::{SyncConfig, SyncLanguage, sync};
27//! use std::path::PathBuf;
28//!
29//! let config = SyncConfig {
30//!     ontology_path: PathBuf::from("businessos.ttl"),
31//!     queries_dir:   PathBuf::from("queries/businessos"),
32//!     output_dir:    PathBuf::from("."),
33//!     language:      SyncLanguage::Go,
34//!     validate:      true,
35//!     dry_run:       false,
36//! };
37//!
38//! let result = sync(config).unwrap();
39//! println!("Generated {} files, receipt={}", result.files_generated.len(), result.receipt);
40//! ```
41
42#[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
62// ---------------------------------------------------------------------------
63// Constants
64// ---------------------------------------------------------------------------
65
66/// Maximum wall-clock time allowed for a single SPARQL query execution.
67pub const SPARQL_TIMEOUT_SECS: u64 = 30;
68
69// ---------------------------------------------------------------------------
70// Public types
71// ---------------------------------------------------------------------------
72
73/// Target language for code generation.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum SyncLanguage {
76    /// Generate Go microservice structs and handlers
77    Go,
78    /// Generate Elixir GenServer modules
79    Elixir,
80    /// Generate Rust structs with serde derives
81    Rust,
82    /// Generate TypeScript interfaces
83    TypeScript,
84    /// Generate Python dataclasses
85    Python,
86    /// Detect language from ontology metadata or file extension heuristics
87    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/// Configuration for a single `ggen sync` invocation.
120#[derive(Debug, Clone)]
121pub struct SyncConfig {
122    /// Path to the `.ttl` ontology file (Stage 1 input).
123    pub ontology_path: PathBuf,
124
125    /// Directory containing `.rq` SPARQL SELECT files (Stage 2 input).
126    /// All `*.rq` files in this directory are executed in lexicographic order.
127    pub queries_dir: PathBuf,
128
129    /// Directory where generated files will be written (Stage 5 output).
130    /// Created if it does not exist (unless `dry_run` is `true`).
131    pub output_dir: PathBuf,
132
133    /// Target language for code generation (Stage 3).
134    pub language: SyncLanguage,
135
136    /// Run WvdA soundness gates on generated source (Stage 4).
137    /// Soundness violations are returned in `SyncResult` but do **not** abort the
138    /// pipeline unless every generated file has at least one critical violation —
139    /// callers decide whether to treat violations as hard errors.
140    pub validate: bool,
141
142    /// Simulate the pipeline without writing any files.
143    /// `SyncResult::files_generated` will be populated with the paths that *would*
144    /// have been written; `SyncResult::receipt` is still computed.
145    pub dry_run: bool,
146}
147
148/// Aggregate output from a completed `sync()` invocation.
149#[derive(Debug, Clone)]
150pub struct SyncResult {
151    /// Paths of files written to `config.output_dir`
152    /// (or that would have been written if `dry_run` is `true`).
153    pub files_generated: Vec<PathBuf>,
154
155    /// WvdA soundness violations found in generated source code.
156    /// Empty when `config.validate` is `false`.
157    pub soundness_violations: Vec<SoundnessViolation>,
158
159    /// Wall-clock time for the complete pipeline in milliseconds.
160    pub elapsed_ms: u64,
161
162    /// Deterministic cryptographic receipt: `hex( sha256( ontology_bytes || sorted_output_bytes ) )`.
163    /// Same inputs always produce the same receipt.
164    pub receipt: String,
165
166    /// Three-pole coherence report (ontology/artifact/event-log isomorphism check).
167    pub coherence_report: Option<CoherenceReport>,
168}
169
170/// Errors that can occur during the sync pipeline.
171#[derive(Debug, thiserror::Error)]
172pub enum SyncError {
173    /// Stage 1: ontology file missing or unreadable
174    #[error("ontology load failed: {0}")]
175    OntologyLoad(String),
176
177    /// Stage 1: Turtle parse error
178    #[error("ontology parse failed: {0}")]
179    OntologyParse(String),
180
181    /// Stage 2: queries directory missing or unreadable
182    #[error("queries directory error: {0}")]
183    QueriesDir(String),
184
185    /// Stage 2: a `.rq` file could not be read
186    #[error("query file read error ({path}): {message}")]
187    QueryRead {
188        /// Path of the failing `.rq` file
189        path: PathBuf,
190        /// Underlying I/O message
191        message: String,
192    },
193
194    /// Stage 2: SPARQL execution error
195    #[error("SPARQL execution error ({query}): {message}")]
196    SparqlExecution {
197        /// Name of the query (stem of the `.rq` filename)
198        query: String,
199        /// Underlying error message
200        message: String,
201    },
202
203    /// Stage 2: SPARQL execution exceeded [`SPARQL_TIMEOUT_SECS`]
204    #[error("SPARQL timeout after {SPARQL_TIMEOUT_SECS}s for query '{query}'")]
205    SparqlTimeout {
206        /// Name of the query that timed out
207        query: String,
208    },
209
210    /// Stage 3: code generation failed
211    #[error("code generation failed: {0}")]
212    Codegen(String),
213
214    /// Stage 5: file I/O error while writing output
215    #[error("file write error ({path}): {message}")]
216    FileWrite {
217        /// Path that could not be written
218        path: PathBuf,
219        /// Underlying I/O message
220        message: String,
221    },
222
223    /// Output directory creation failed
224    #[error("cannot create output directory ({path}): {message}")]
225    OutputDir {
226        /// Path of the directory that could not be created
227        path: PathBuf,
228        /// Underlying I/O message
229        message: String,
230    },
231
232    /// The requested language string is not recognised
233    #[error("unknown language '{0}'; valid values: go, elixir, rust, typescript, python, auto")]
234    InvalidLanguage(String),
235
236    /// Stage 4.5: coherence check failed (O ≅ A ≅ L violation) — FATAL, blocks Stage 5 write
237    #[error("coherence violation: {detail}")]
238    CoherenceViolation {
239        /// Human-readable summary of the drift(s) detected
240        detail: String,
241        /// Full coherence report with pole states and drift observations
242        report: CoherenceReport,
243    },
244}
245
246// Allow converting ggen_utils errors so we can use ? in internal helpers.
247impl From<GgenError> for SyncError {
248    fn from(e: GgenError) -> Self {
249        Self::OntologyParse(e.to_string())
250    }
251}
252
253// ---------------------------------------------------------------------------
254// Pipeline entry point
255// ---------------------------------------------------------------------------
256
257/// Execute the full sync pipeline and return aggregated results.
258///
259/// ## Stages
260///
261/// | Stage | Description | Timeout | Fatal? |
262/// |-------|-------------|---------|--------|
263/// | 1 | Load ontology | — | Yes |
264/// | 2 | Execute SPARQL queries | 30 s each | Yes |
265/// | 3 | Generate code | — | Yes |
266/// | 4 | Validate soundness (if enabled) | — | No |
267/// | 4.5 | Coherence gate (O ≅ A ≅ L) | — | Yes |
268/// | 5 | Write files and compute receipt | — | Yes |
269/// | 5b | Write coherence report | — | No |
270///
271/// ## Error handling
272///
273/// Returns `Err(SyncError)` on the **first fatal error** in any stage.
274/// - **Non-fatal errors**: Soundness violations from Stage 4 accumulate in `SyncResult`.
275/// - **Fatal errors**: Any error in Stages 1, 2, 3, 4.5, or 5 aborts the pipeline.
276/// - **Coherence violations** from Stage 4.5 return `SyncError::CoherenceViolation` and block Stage 5 write.
277pub fn sync(config: SyncConfig) -> Result<SyncResult, SyncError> {
278    let start = Instant::now();
279
280    // ------------------------------------------------------------------
281    // Stage 1 — Load ontology
282    // ------------------------------------------------------------------
283    let (graph, ontology_bytes) = load_ontology(&config.ontology_path)?;
284
285    // ------------------------------------------------------------------
286    // Stage 2 — Extract: run SPARQL queries
287    // ------------------------------------------------------------------
288    let bindings = run_sparql_queries(&graph, &config.queries_dir)?;
289
290    // ------------------------------------------------------------------
291    // Stage 3 — Generate code
292    // ------------------------------------------------------------------
293    let generated = generate_code(&config, &bindings)?;
294
295    // ------------------------------------------------------------------
296    // Stage 4 — Validate soundness (optional, non-fatal)
297    // ------------------------------------------------------------------
298    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    // ------------------------------------------------------------------
308    // Stage 4.5 — Coherence gate (FATAL — blocks Stage 5 write if violated)
309    // ------------------------------------------------------------------
310    // In dry-run mode, skip event-log pole (no events produced).
311    // In normal mode, check all three poles.
312    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    // Construct (path, content) pairs for artifact fingerprinting.
320    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    // ------------------------------------------------------------------
328    // Stage 5 — Write files and compute receipt
329    // (Only reached if Stage 4.5 coherence gate admitted)
330    // ------------------------------------------------------------------
331    let files_generated = write_files(&config, &generated)?;
332
333    let receipt = compute_receipt(&ontology_bytes, &generated);
334
335    // ------------------------------------------------------------------
336    // Stage 5b — Write coherence report to disk (observability only)
337    // ------------------------------------------------------------------
338    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
357// ---------------------------------------------------------------------------
358// Stage implementations
359// ---------------------------------------------------------------------------
360
361/// Stage 1: Read the `.ttl` file and load it into an in-memory Graph.
362///
363/// Returns both the `Graph` and the raw bytes so Stage 5 can hash the input.
364fn 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
378/// A single SPARQL SELECT result: one row per binding set.
379pub type QueryRow = BTreeMap<String, String>;
380
381/// Stage 2: Run every `*.rq` file in `queries_dir`, return all rows.
382///
383/// Files are executed in **lexicographic order** to ensure determinism.
384/// Each query has a wall-clock timeout of [`SPARQL_TIMEOUT_SECS`].
385fn 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    // Collect *.rq files in sorted order
394    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        // Bounded execution: run in a thread and enforce the timeout
418        let rows = execute_with_timeout(graph, &sparql, &query_name, timeout)?;
419        all_rows.extend(rows);
420    }
421
422    Ok(all_rows)
423}
424
425/// Execute one SPARQL SELECT query with a wall-clock deadline.
426///
427/// The timeout is enforced by running the SPARQL evaluation on the calling
428/// thread with a before/after elapsed check. Oxigraph is synchronous and does
429/// not support mid-query cancellation; the timeout guards against pathologically
430/// large result sets rather than infinite loops.
431fn 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            // Non-SELECT queries contribute no rows — treat as empty
453            Ok(Vec::new())
454        }
455    }
456}
457
458/// Stage 3: Dispatch to the appropriate code generator.
459///
460/// Returns a `Vec<(relative_filename, source_text)>` pair for each generated
461/// file.  The filename is relative to the output directory.
462fn 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            // Auto resolved to a concrete language above; reaching here is impossible
475            // but we must handle it for exhaustiveness.
476            Err(SyncError::InvalidLanguage("auto".to_string()))
477        }
478    }
479}
480
481/// Resolve `SyncLanguage::Auto` by inspecting the ontology path / queries dir.
482///
483/// Falls back to `Go` if no signal is found, since it is the primary language
484/// in the BusinessOS platform.
485fn resolve_language(lang: &SyncLanguage, ontology_path: &Path) -> SyncLanguage {
486    if *lang != SyncLanguage::Auto {
487        return lang.clone();
488    }
489    // Heuristic: look for language cues in the ontology filename
490    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        // Default: Go (BusinessOS primary language)
504        SyncLanguage::Go
505    }
506}
507
508// ---------------------------------------------------------------------------
509// Language-specific generators
510// ---------------------------------------------------------------------------
511
512/// Generate Go source files from SPARQL bindings.
513///
514/// Produces one `<service_name>.go` file per unique `?service` binding found
515/// in the query results.  Falls back to a single `services.go` when no
516/// `?service` variable is present.
517fn generate_go(bindings: &[QueryRow]) -> Result<Vec<(PathBuf, String)>, SyncError> {
518    let mut outputs: Vec<(PathBuf, String)> = Vec::new();
519
520    // Group bindings by service name
521    let service_groups = group_by_key(bindings, "service");
522
523    if service_groups.is_empty() {
524        // No service bindings — produce a single placeholder file
525        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
541/// Generate Elixir source files from SPARQL bindings.
542fn 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
561/// Generate Rust source files from SPARQL bindings.
562fn 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
581/// Generate TypeScript source files from SPARQL bindings.
582fn 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
601/// Generate Python source files from SPARQL bindings.
602fn 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
621// ---------------------------------------------------------------------------
622// Code templates (minimal, self-contained)
623// ---------------------------------------------------------------------------
624
625fn 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
696// ---------------------------------------------------------------------------
697// Stage 5: file writing and receipt
698// ---------------------------------------------------------------------------
699
700/// Write generated files to `config.output_dir` (unless `dry_run` is set).
701///
702/// Returns the list of absolute paths written (or that would have been written).
703fn 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            // Ensure parent directories exist
720            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
741/// Compute the deterministic sha256 receipt.
742///
743/// ```text
744/// receipt = hex( sha256( ontology_bytes || sorted( file_contents... ) ) )
745/// ```
746///
747/// Files are sorted by their relative path before hashing so that the order
748/// in which the generator emits them does not affect the receipt.
749fn compute_receipt(ontology_bytes: &[u8], generated: &[(PathBuf, String)]) -> String {
750    let mut hasher = Sha256::new();
751    hasher.update(ontology_bytes);
752
753    // Sort by path to ensure determinism regardless of generator order
754    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
766// ---------------------------------------------------------------------------
767// Helpers
768// ---------------------------------------------------------------------------
769
770/// Group rows by the value of a named variable.
771///
772/// Rows that do not contain the variable are silently dropped.
773/// Returns a `BTreeMap` so iteration order is deterministic.
774fn 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            // Strip surrounding angle-brackets added by Oxigraph for IRI terms
779            let clean = strip_iri_brackets(value);
780            groups.entry(clean).or_default().push(row.clone());
781        }
782    }
783    groups
784}
785
786/// Remove `<` and `>` from Oxigraph's IRI serialisation and extract the
787/// local name (fragment or last path segment).
788fn strip_iri_brackets(iri: &str) -> String {
789    let inner = iri.trim_start_matches('<').trim_end_matches('>');
790
791    // Prefer the fragment identifier as the local name
792    if let Some(fragment) = inner.rsplit_once('#').map(|(_, f)| f) {
793        return fragment.to_string();
794    }
795    // Fall back to the last path segment
796    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
804/// Simple camelCase conversion for TypeScript file names.
805fn 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}