ggen_core/codegen/
mod.rs

1//! Code generation module
2//!
3//! This module provides generators for different target languages and frameworks,
4//! converting OntologySchema into working code for TypeScript, GraphQL, SQL, and more.
5//!
6//! ## Semantic Code Generation (v5)
7//!
8//! The new semantic code generation pipeline transforms RDF ontologies through
9//! CONSTRUCT queries into typed code graphs, which are then rendered via Tera templates.
10//!
11//! ### Pipeline Flow
12//!
13//! ```text
14//! ontology.ttl → Graph → CONSTRUCT rules → Code Graph → Tera → .rs files
15//! ```
16//!
17//! ### Key Types
18//!
19//! - [`GenerationPipeline`] - Orchestrates the full generation flow
20//! - [`CodeGraphBuilder`] - Converts SPARQL results to code entities
21//! - [`AuditTrailBuilder`] - Tracks execution for determinism verification
22
23pub mod audit;
24pub mod code_graph;
25pub mod concurrent;
26pub mod dependency_validation;
27pub mod execution_lifecycle;
28pub mod execution_proof;
29pub mod executor;
30pub mod incremental_cache;
31#[allow(dead_code)]
32pub mod lifecycle_hooks;
33pub mod marketplace_integration;
34pub mod merge;
35pub mod pipeline;
36pub mod proof_archive;
37pub mod swarm_execution;
38pub mod swarm_executor_bridge;
39pub mod typescript;
40pub mod watch;
41pub mod watch_cache_integration;
42pub mod watch_mode;
43
44// Re-export key types
45pub use audit::{AuditOutput, AuditStep, AuditTrail, AuditTrailBuilder};
46pub use code_graph::{
47    CodeEnum, CodeField, CodeGraphBuilder, CodeImpl, CodeImport, CodeItem, CodeMethod, CodeModule,
48    CodeParam, CodeStruct, CodeTrait, CodeVariant,
49};
50pub use concurrent::ConcurrentRuleExecutor;
51pub use dependency_validation::{DependencyCheck, DependencyValidationReport, DependencyValidator};
52pub use execution_lifecycle::{ExecutionLifecycle, PostSyncContext, PreSyncContext};
53pub use execution_proof::{ExecutionProof, ProofCarrier, RuleExecution};
54pub use executor::{SyncExecutor, SyncResult, SyncedFileInfo, ValidationCheck};
55pub use incremental_cache::{CacheInvalidation, IncrementalCache};
56pub use marketplace_integration::{MarketplaceValidator, PackageValidation, PreFlightReport};
57pub use merge::{merge_sections, parse_merge_markers, MergeMarkers, MergedSections};
58pub use pipeline::{
59    ExecutedRule, GeneratedFile, GenerationPipeline, PipelineState, RuleType, ValidationResult,
60    ValidationSeverity,
61};
62pub use proof_archive::{ChainVerification, ProofArchive};
63pub use swarm_execution::{Agent, SwarmCoordinator, SwarmSummary};
64pub use swarm_executor_bridge::{ExecutionStrategy, SwarmExecutorBridge};
65pub use typescript::TypeScriptGenerator;
66pub use watch::{collect_watch_paths, FileWatcher, WatchEvent};
67pub use watch_cache_integration::{AffectedRulesAnalysis, WatchCacheIntegration};
68pub use watch_mode::{WatchConfig, WatchMode};
69
70// ============================================================================
71// Sync Options (CLI Configuration for ggen sync)
72// ============================================================================
73
74/// Output format for `ggen sync` command results
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
76pub enum OutputFormat {
77    /// Human-readable text output (default)
78    #[default]
79    Text,
80    /// JSON output for CI/CD and automation
81    Json,
82}
83
84impl std::str::FromStr for OutputFormat {
85    type Err = String;
86
87    fn from_str(s: &str) -> Result<Self, Self::Err> {
88        match s.to_lowercase().as_str() {
89            "text" => Ok(OutputFormat::Text),
90            "json" => Ok(OutputFormat::Json),
91            _ => Err(format!(
92                "Invalid output format: '{}'. Expected 'text' or 'json'",
93                s
94            )),
95        }
96    }
97}
98
99impl std::fmt::Display for OutputFormat {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        match self {
102            OutputFormat::Text => write!(f, "text"),
103            OutputFormat::Json => write!(f, "json"),
104        }
105    }
106}
107
108/// Configuration options for `ggen sync` pipeline execution
109///
110/// These options control the behavior of the code synchronization pipeline,
111/// including dry-run mode, audit trail generation, and timeout limits.
112#[derive(Debug, Clone)]
113pub struct SyncOptions {
114    /// Path to the manifest file (default: ggen.toml)
115    pub manifest_path: std::path::PathBuf,
116
117    /// Override output directory from manifest
118    pub output_dir: Option<std::path::PathBuf>,
119
120    /// Preview changes without writing files
121    pub dry_run: bool,
122
123    /// Force overwrite of protected files
124    pub force: bool,
125
126    /// Generate audit trail (audit.json)
127    pub audit: bool,
128
129    /// Run only specific rules (by name)
130    pub selected_rules: Option<Vec<String>>,
131
132    /// Verbose output during execution
133    pub verbose: bool,
134
135    /// Watch for file changes and auto-regenerate
136    pub watch: bool,
137
138    /// Validate manifest without generating
139    pub validate_only: bool,
140
141    /// Output format for results
142    pub output_format: OutputFormat,
143
144    /// Maximum execution timeout in milliseconds
145    pub timeout_ms: u64,
146
147    /// Enable incremental caching for faster re-runs
148    pub use_cache: bool,
149
150    /// Cache directory (relative to output directory)
151    pub cache_dir: Option<std::path::PathBuf>,
152
153    /// Maximum parallel tasks for rule execution
154    pub max_parallelism: Option<usize>,
155}
156
157impl Default for SyncOptions {
158    fn default() -> Self {
159        Self {
160            manifest_path: std::path::PathBuf::from("ggen.toml"),
161            output_dir: None,
162            dry_run: false,
163            force: false,
164            audit: false,
165            selected_rules: None,
166            verbose: false,
167            watch: false,
168            validate_only: false,
169            output_format: OutputFormat::default(),
170            timeout_ms: 30000, // 30 second default
171            use_cache: true,   // Caching enabled by default
172            cache_dir: None,
173            max_parallelism: None, // Use system default
174        }
175    }
176}
177
178impl SyncOptions {
179    /// Create new SyncOptions with default values
180    pub fn new() -> Self {
181        Self::default()
182    }
183
184    /// Create SyncOptions from a manifest path
185    pub fn from_manifest<P: AsRef<std::path::Path>>(path: P) -> Self {
186        Self {
187            manifest_path: path.as_ref().to_path_buf(),
188            ..Self::default()
189        }
190    }
191
192    /// Set dry-run mode
193    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
194        self.dry_run = dry_run;
195        self
196    }
197
198    /// Set verbose output
199    pub fn with_verbose(mut self, verbose: bool) -> Self {
200        self.verbose = verbose;
201        self
202    }
203
204    /// Set audit trail generation
205    pub fn with_audit(mut self, audit: bool) -> Self {
206        self.audit = audit;
207        self
208    }
209
210    /// Set validate-only mode
211    pub fn with_validate_only(mut self, validate_only: bool) -> Self {
212        self.validate_only = validate_only;
213        self
214    }
215
216    /// Set output format
217    pub fn with_output_format(mut self, format: OutputFormat) -> Self {
218        self.output_format = format;
219        self
220    }
221
222    /// Set timeout in milliseconds
223    pub fn with_timeout_ms(mut self, timeout_ms: u64) -> Self {
224        self.timeout_ms = timeout_ms;
225        self
226    }
227
228    /// Set selected rules
229    pub fn with_rules(mut self, rules: Vec<String>) -> Self {
230        self.selected_rules = Some(rules);
231        self
232    }
233
234    /// Set force overwrite
235    pub fn with_force(mut self, force: bool) -> Self {
236        self.force = force;
237        self
238    }
239
240    /// Set output directory override
241    pub fn with_output_dir<P: AsRef<std::path::Path>>(mut self, dir: P) -> Self {
242        self.output_dir = Some(dir.as_ref().to_path_buf());
243        self
244    }
245
246    /// Enable or disable incremental caching
247    pub fn with_cache(mut self, use_cache: bool) -> Self {
248        self.use_cache = use_cache;
249        self
250    }
251
252    /// Set cache directory
253    pub fn with_cache_dir<P: AsRef<std::path::Path>>(mut self, dir: P) -> Self {
254        self.cache_dir = Some(dir.as_ref().to_path_buf());
255        self
256    }
257
258    /// Set maximum parallelism for rule execution
259    pub fn with_max_parallelism(mut self, max_parallelism: usize) -> Self {
260        self.max_parallelism = Some(max_parallelism);
261        self
262    }
263}