ggen_core/
lib.rs

1//! # ggen-core - Core graph-aware code generation engine
2//!
3//! This crate provides the core functionality for RDF-based code generation,
4//! including template processing, RDF handling, and deterministic output generation.
5//!
6//! ## Overview
7//!
8//! `ggen-core` is the foundational crate for the ggen code generation system. It provides:
9//!
10//! - **Template Processing**: Parse, render, and generate code from templates with RDF integration
11//! - **RDF Graph Management**: Load, query, and manipulate RDF data using SPARQL
12//! - **Project Generation**: Scaffold complete projects from templates
13//! - **Registry Integration**: Discover and install template packs from the registry
14//! - **Lifecycle Management**: Orchestrate build, test, and deployment phases
15//! - **Deterministic Output**: Ensure reproducible code generation
16//!
17//! ## Key Modules
18//!
19//! ### Template System
20//! - [`template`] - Core template parsing and rendering
21//! - [`templates`] - File tree generation from templates
22//! - [`pipeline`] - Template processing pipeline
23//! - [`generator`] - High-level generation engine
24//!
25//! ### RDF Integration
26//! - [`graph`] - RDF graph management with SPARQL caching
27//! - [`rdf`] - Template metadata and validation
28//! - [`delta`] - Delta-driven projection for graph changes
29//!
30//! ### Project Management
31//! - [`project_generator`] - Scaffold new projects (Rust, Next.js, etc.)
32//! - [`cli_generator`] - Generate CLI projects from ontologies
33//! - [`lifecycle`] - Universal lifecycle system for cross-language projects
34//!
35//! ### Registry and Packs
36//! - [`registry`] - Registry client for pack discovery
37//! - [`cache`] - Local cache manager for downloaded packs
38//! - [`lockfile`] - Dependency lockfile management
39//! - [`resolver`] - Template resolution from packs
40//! - [`gpack`] - Gpack manifest structure and file discovery
41//!
42//! ### Utilities
43//! - [`inject`] - File injection utilities
44//! - [`merge`] - Three-way merge for delta-driven projection
45//! - [`snapshot`] - Snapshot management for baselines
46//! - [`preprocessor`] - Template preprocessor pipeline
47//! - [`register`] - Tera filter and function registration
48//! - [`tera_env`] - Tera template engine environment utilities
49//!
50//! ### Security (Week 4 Hardening)
51//! - [`security`] - Security hardening module (command injection prevention, input validation)
52//!
53//! ## Quick Start
54//!
55//! ### Basic Template Generation
56//!
57//! ```rust,no_run
58//! use ggen_core::{Generator, GenContext, Pipeline};
59//! use std::collections::BTreeMap;
60//! use std::path::PathBuf;
61//!
62//! # fn main() -> ggen_utils::error::Result<()> {
63//! let pipeline = Pipeline::new()?;
64//! let mut vars = BTreeMap::new();
65//! vars.insert("name".to_string(), "MyApp".to_string());
66//!
67//! let ctx = GenContext::new(
68//!     PathBuf::from("template.tmpl"),
69//!     PathBuf::from("output")
70//! ).with_vars(vars);
71//!
72//! let mut generator = Generator::new(pipeline, ctx);
73//! let output_path = generator.generate()?;
74//! println!("Generated: {:?}", output_path);
75//! # Ok(())
76//! # }
77//! ```
78//!
79//! ### Using RDF Graph
80//!
81//! ```rust
82//! use ggen_core::Graph;
83//!
84//! # fn main() -> ggen_utils::error::Result<()> {
85//! let graph = Graph::new()?;
86//! graph.insert_turtle(r#"
87//!     @prefix ex: <http://example.org/> .
88//!     ex:alice a ex:Person ;
89//!              ex:name "Alice" .
90//! "#)?;
91//!
92//! let results = graph.query("SELECT ?s ?o WHERE { ?s ex:name ?o }")?;
93//! assert!(!results.is_empty());
94//! # Ok(())
95//! # }
96//! ```
97//!
98//! ### Creating a New Project
99//!
100//! ```rust,no_run
101//! use ggen_core::project_generator::{ProjectConfig, ProjectType, create_new_project};
102//! use std::path::PathBuf;
103//!
104//! # async fn example() -> ggen_utils::error::Result<()> {
105//! let config = ProjectConfig {
106//!     name: "my-cli".to_string(),
107//!     project_type: ProjectType::RustCli,
108//!     framework: None,
109//!     path: PathBuf::from("."),
110//! };
111//!
112//! create_new_project(&config).await?;
113//! # Ok(())
114//! # }
115//! ```
116
117#![deny(warnings)] // Poka-Yoke: Prevent warnings at compile time - compiler enforces correctness
118
119pub mod audit;
120pub mod cache;
121pub mod cli_generator;
122pub mod codegen;
123pub mod config;
124// N3/CONSTRUCT semantic code generation manifest (v5)
125pub mod delta;
126#[cfg(test)]
127pub mod e2e_tests;
128pub mod generator;
129pub mod github;
130pub mod gpack;
131pub mod graph;
132pub mod inject;
133pub mod lifecycle;
134pub mod lockfile;
135pub mod lockfile_unified; // Unified lockfile trait system (v4.0)
136pub mod manifest;
137pub mod merge;
138pub mod parallel_generator;
139// Ontology system - re-enabled after oxigraph API compatibility fixes
140pub mod ontology;
141pub mod ontology_pack;
142pub mod packs; // Pack installation system - Phase 1
143pub mod pipeline;
144pub mod poc;
145pub mod poka_yoke; // Poka-Yoke error-proofing mechanisms
146pub mod pqc;
147pub mod preprocessor;
148pub mod prevention; // Week 3 Prevention Systems - DfLSS
149pub mod project_generator;
150pub mod rdf;
151pub mod register;
152pub mod registry;
153pub mod resolver;
154pub mod security; // Week 4 Security Hardening
155pub mod snapshot;
156pub mod streaming_generator;
157pub mod telemetry;
158pub mod template;
159pub mod template_cache;
160pub mod templates;
161pub mod tera_env;
162pub mod types; // Enterprise FMEA & Poka-Yoke types for marketplace
163               // pub mod tracing; // Temporarily disabled due to missing tracing_subscriber dependency
164pub mod simple_tracing;
165pub mod v6;
166pub mod validation; // SHACL validation for ggen sync poka-yoke (005-ttl-shacl-validation) // ggen v6: Fully-Rendered Libraries via Ontology-First Compilation
167
168// Re-export production readiness types from lifecycle module
169pub use lifecycle::{
170    Placeholder, PlaceholderProcessor, PlaceholderRegistry, ReadinessCategory, ReadinessReport,
171    ReadinessRequirement, ReadinessStatus, ReadinessTracker,
172};
173
174// Re-export poka-yoke (error prevention) types
175pub use lifecycle::{
176    Closed, Counter, EmptyPathError, EmptyStringError, FileHandle, NonEmptyPath, NonEmptyString,
177    Open,
178};
179
180// Re-export commonly used types for convenience
181pub use cache::{CacheManager, CachedPack};
182pub use delta::{DeltaType, GraphDelta, ImpactAnalyzer, TemplateImpact};
183pub use generator::{GenContext, Generator};
184pub use github::{GitHubClient, PagesConfig, RepoInfo, WorkflowRun, WorkflowRunsResponse};
185pub use gpack::GpackManifest;
186pub use graph::{Graph, GraphStore};
187pub use lockfile::{LockEntry, Lockfile, LockfileManager};
188pub use merge::{
189    ConflictType, MergeConflict, MergeResult, MergeStrategy, RegionAwareMerger, RegionUtils,
190    ThreeWayMerger,
191};
192pub use packs::{LockedPack, PackLockfile, PackSource};
193pub use pipeline::{Pipeline, PipelineBuilder};
194pub use pqc::{calculate_sha256, calculate_sha256_file, PqcSigner, PqcVerifier};
195pub use rdf::{
196    GgenOntology, TemplateMetadata, TemplateMetadataStore, TemplateRelationship, TemplateVariable,
197    ValidationReport, ValidationResult, Validator, GGEN_NAMESPACE,
198};
199pub use registry::{RegistryClient, RegistryIndex, ResolvedPack, SearchResult};
200pub use resolver::{TemplateResolver, TemplateSearchResult, TemplateSource};
201pub use snapshot::{
202    FileSnapshot, GraphSnapshot, Region, RegionType, Snapshot, SnapshotManager, TemplateSnapshot,
203};
204pub use template::Template;
205
206// Re-export template-to-file-tree generation types
207pub use templates::{
208    generate_file_tree, FileTreeGenerator, FileTreeNode, FileTreeTemplate, GenerationResult,
209    NodeType, TemplateContext, TemplateFormat, TemplateParser,
210};
211
212// Re-export ontology pack types
213pub use ontology_pack::{
214    Cardinality, CodeGenTarget, OntologyClass, OntologyConfig, OntologyDefinition, OntologyFormat,
215    OntologyPackMetadata, OntologyProperty, OntologyRelationship, OntologySchema, PropertyRange,
216    RelationshipType,
217};
218
219// Ontology system re-exports
220// Re-enabled after oxigraph API compatibility fixes (Statement::From<Quad> and as_dataset)
221pub use ontology::{
222    AtomicPromotionCheck,
223    // Promotion
224    AtomicSnapshotPromoter,
225    // Control loop
226    AutonomousControlLoop,
227    CompositeValidator,
228    Constitution,
229    ConstitutionValidation,
230    ControlLoopConfig,
231    // Delta proposer
232    DeltaSigmaProposal,
233    DeltaSigmaProposer,
234    DynamicValidator,
235    GuardSoundnessCheck,
236    ImmutabilityCheck,
237    Invariant,
238    // Constitution
239    InvariantCheck,
240    InvariantResult,
241    IterationTelemetry,
242    LoopState,
243    MinerConfig,
244    MockDynamicValidator,
245    MockLLMProposer,
246    MockPerformanceValidator,
247    MockStaticValidator,
248    NoRetrocausationCheck,
249    Observation,
250    ObservationSource,
251    OntClass,
252    OntProperty,
253    OntologyError,
254    OntologyExtractor,
255    OntologyResult,
256    OntologyStats,
257    // Pattern mining
258    Pattern,
259    PatternMiner,
260    PatternType,
261    PerformanceMetrics,
262    PerformanceValidator,
263    ProjectionDeterminismCheck,
264    PromotionMetrics,
265    PromotionResult,
266    ProposedChange,
267    ProposerConfig,
268    RealLLMProposer,
269    SLOPreservationCheck,
270    SigmaOverlay,
271    SigmaReceipt,
272    SigmaRuntime,
273    SigmaSnapshot,
274    // Sigma runtime
275    SigmaSnapshotId,
276    SnapshotGuard,
277    SnapshotMetadata,
278    StaticValidator,
279    TestResult,
280    TypeSoundnessCheck,
281    ValidationContext,
282    // Validators
283    ValidationEvidence,
284    ValidatorResult,
285};
286
287// Note: Cardinality, OntologySchema, PropertyRange are exported from ontology_pack module above
288// to avoid conflicts with ontology module exports
289
290// Re-export enterprise FMEA & Poka-Yoke types for marketplace
291pub use types::{
292    // CODEOWNERS generation
293    CodeownersGenerator,
294    // FMEA types
295    Detection,
296    // Enterprise configuration
297    DomainProtectionStrategy,
298    EnterpriseConfig,
299    FailureModeEntry,
300    FmeaConfig,
301    FmeaValidationError,
302    GenerationConfig,
303    Occurrence,
304    OwnerEntry,
305    OwnersFile,
306    // Path protection
307    PathProtectionConfig,
308    PathProtectionError,
309    PokaYokeConfig,
310    ProtectedPath,
311    RegeneratePath,
312    RpnLevel,
313    RpnScore,
314    Severity,
315};
316
317// Re-export v6 ontology compilation types
318pub use v6::{
319    // Vocabulary governance
320    AllowedVocabulary,
321    // Core types
322    BuildReceipt,
323    // Pass implementations
324    CanonicalizationPass,
325    EmissionPass,
326    Epoch,
327    EpochId,
328    ExtractionPass,
329    ForbiddenVocabulary,
330    // Guard system
331    Guard,
332    GuardAction,
333    GuardViolation,
334    NormalizationPass,
335    OutputFile,
336    // Pass system
337    Pass,
338    PassContext,
339    PassExecution,
340    PassResult,
341    PassType,
342    PathGuard,
343    PipelineConfig,
344    ReceiptGenerationPass,
345    SecretGuard,
346    StagedPipeline,
347    VerifyMode,
348    VocabularyRegistry,
349};