Skip to main content

Crate ggen_core

Crate ggen_core 

Source
Expand description

§ggen-core - Core graph-aware code generation engine

This crate provides the core functionality for RDF-based code generation, including template processing, RDF handling, and deterministic output generation.

§Overview

ggen-core is the foundational crate for the ggen code generation system. It provides:

  • Template Processing: Parse, render, and generate code from templates with RDF integration
  • RDF Graph Management: Load, query, and manipulate RDF data using SPARQL
  • Project Generation: Scaffold complete projects from templates
  • Registry Integration: Discover and install template packs from the registry
  • Lifecycle Management: Orchestrate build, test, and deployment phases
  • Deterministic Output: Ensure reproducible code generation

§Key Modules

§Template System

  • template - Core template parsing and rendering
  • templates - File tree generation from templates
  • pipeline - Template processing pipeline
  • generator - High-level generation engine

§RDF Integration

  • graph - RDF graph management with SPARQL caching
  • rdf - Template metadata and validation
  • delta - Delta-driven projection for graph changes

§Project Management

§Registry and Packs

  • registry - Registry client for pack discovery
  • cache - Local cache manager for downloaded packs
  • lockfile - Dependency lockfile management
  • resolver - Template resolution from packs
  • gpack - Gpack manifest structure and file discovery

§Utilities

  • inject - File injection utilities
  • merge - Three-way merge for delta-driven projection
  • snapshot - Snapshot management for baselines
  • preprocessor - Template preprocessor pipeline
  • register - Tera filter and function registration
  • tera_env - Tera template engine environment utilities

§Security (Week 4 Hardening)

  • security - Security hardening module (command injection prevention, input validation)

§Quick Start

§Basic Template Generation

use crate::{Generator, GenContext, Pipeline};
use std::collections::BTreeMap;
use std::path::PathBuf;

let pipeline = Pipeline::new()?;
let mut vars = BTreeMap::new();
vars.insert("name".to_string(), "MyApp".to_string());

let ctx = GenContext::new(
    PathBuf::from("template.tmpl"),
    PathBuf::from("output")
).with_vars(vars);

let mut generator = Generator::new(pipeline, ctx);
let output_path = generator.generate()?;
println!("Generated: {:?}", output_path);

§Using RDF Graph

use ggen_core::Graph;
use oxigraph::sparql::QueryResults;

let graph = Graph::new()?;
graph.insert_turtle(r#"
    @prefix ex: <http://example.org/> .
    ex:alice a ex:Person ;
             ex:name "Alice" .
"#)?;

let results = graph.query("SELECT ?s ?o WHERE { ?s ex:name ?o }")?;
if let QueryResults::Solutions(solutions) = results {
    assert!(solutions.count() > 0);
}

§Creating a New Project

use crate::project_generator::{ProjectConfig, ProjectType, create_new_project};
use std::path::PathBuf;

let config = ProjectConfig {
    name: "my-cli".to_string(),
    project_type: ProjectType::RustCli,
    framework: None,
    path: PathBuf::from("."),
};

create_new_project(&config).await?;

Re-exports§

pub use template_types::Frontmatter;
pub use template_types::Template;
pub use lifecycle::Placeholder;
pub use lifecycle::PlaceholderProcessor;
pub use lifecycle::PlaceholderRegistry;
pub use lifecycle::ReadinessCategory;
pub use lifecycle::ReadinessReport;
pub use lifecycle::ReadinessRequirement;
pub use lifecycle::ReadinessStatus;
pub use lifecycle::ReadinessTracker;
pub use metrics::CodeMetrics;
pub use metrics::DefectMetrics;
pub use metrics::FlowMetrics;
pub use metrics::KaizenMetrics;
pub use metrics::MetricsCollector;
pub use metrics::MetricsReport;
pub use metrics::OEEMetrics;
pub use metrics::ProcessMetrics;
pub use metrics::WasteMetrics;
pub use metrics::WasteType;
pub use lifecycle::Closed;
pub use lifecycle::Counter;
pub use lifecycle::EmptyPathError;
pub use lifecycle::EmptyStringError;
pub use lifecycle::FileHandle;
pub use lifecycle::NonEmptyPath;
pub use lifecycle::NonEmptyString;
pub use lifecycle::Open;
pub use cache::CacheManager;
pub use cache::CachedPack;
pub use delta::DeltaType;
pub use delta::GraphDelta;
pub use delta::ImpactAnalyzer;
pub use delta::TemplateImpact;
pub use drift::ChangeType;
pub use drift::DriftChange;
pub use drift::DriftDetector;
pub use drift::DriftStatus;
pub use drift::FileHashState;
pub use drift::SyncState;
pub use generator::GenContext;
pub use generator::Generator;
pub use github::GitHubClient;
pub use github::PagesConfig;
pub use github::RepoInfo;
pub use github::WorkflowRun;
pub use github::WorkflowRunsResponse;
pub use gpack::GpackManifest;
pub use graph::Graph;
pub use lockfile::Lockfile;
pub use merge::ConflictType;
pub use merge::MergeConflict;
pub use merge::MergeResult;
pub use merge::MergeStrategy;
pub use merge::RegionAwareMerger;
pub use merge::RegionUtils;
pub use merge::ThreeWayMerger;
pub use packs::LockedPack;
pub use packs::PackLockfile;
pub use packs::PackSource;
pub use pipeline::Pipeline;
pub use pipeline::PipelineBuilder;
pub use pki::verify_ed25519;
pub use pki::KeyPurpose;
pub use pki::PkiManager;
pub use pki::TrustedKeyEntry;
pub use pki::TrustedKeysConfig;
pub use pqc::calculate_sha256;
pub use pqc::calculate_sha256_file;
pub use pqc::PqcSigner;
pub use pqc::PqcVerifier;
pub use rdf::GgenOntology;
pub use rdf::Iri;
pub use rdf::Literal;
pub use rdf::SparqlQueryBuilder;
pub use rdf::TemplateMetadata;
pub use rdf::TemplateMetadataStore;
pub use rdf::TemplateRelationship;
pub use rdf::TemplateVariable;
pub use rdf::ValidationReport;
pub use rdf::ValidationResult;
pub use rdf::Validator;
pub use rdf::Variable;
pub use rdf::GGEN_NAMESPACE;
pub use registry::RegistryClient;
pub use registry::RegistryIndex;
pub use registry::ResolvedPack;
pub use registry::SearchResult;
pub use resolver::TemplateResolver;
pub use resolver::TemplateSearchResult;
pub use resolver::TemplateSource;
pub use snapshot::FileSnapshot;
pub use snapshot::GraphSnapshot;
pub use snapshot::Region;
pub use snapshot::RegionType;
pub use snapshot::Snapshot;
pub use snapshot::SnapshotManager;
pub use snapshot::TemplateSnapshot;
pub use templates::generate_file_tree;
pub use templates::FileTreeGenerator;
pub use templates::FileTreeNode;
pub use templates::FileTreeTemplate;
pub use templates::GenerationResult;
pub use templates::NodeType;
pub use templates::TemplateContext;
pub use templates::TemplateFormat;
pub use templates::TemplateParser;
pub use ontology_pack::Cardinality;
pub use ontology_pack::CodeGenTarget;
pub use ontology_pack::OntologyClass;
pub use ontology_pack::OntologyConfig;
pub use ontology_pack::OntologyDefinition;
pub use ontology_pack::OntologyFormat;
pub use ontology_pack::OntologyPackMetadata;
pub use ontology_pack::OntologyProperty;
pub use ontology_pack::OntologyRelationship;
pub use ontology_pack::OntologySchema;
pub use ontology_pack::PropertyRange;
pub use ontology_pack::RelationshipType;
pub use ontology::AtomicPromotionCheck;
pub use ontology::AtomicSnapshotPromoter;
pub use ontology::AutonomousControlLoop;
pub use ontology::CompositeValidator;
pub use ontology::Constitution;
pub use ontology::ConstitutionValidation;
pub use ontology::ControlLoopConfig;
pub use ontology::DeltaSigmaProposal;
pub use ontology::DeltaSigmaProposer;
pub use ontology::DynamicValidator;
pub use ontology::GuardSoundnessCheck;
pub use ontology::ImmutabilityCheck;
pub use ontology::Invariant;
pub use ontology::InvariantCheck;
pub use ontology::InvariantResult;
pub use ontology::IterationTelemetry;
pub use ontology::LoopState;
pub use ontology::MinerConfig;
pub use ontology::NoRetrocausationCheck;
pub use ontology::Observation;
pub use ontology::ObservationSource;
pub use ontology::OntClass;
pub use ontology::OntProperty;
pub use ontology::OntologyError;
pub use ontology::OntologyExtractor;
pub use ontology::OntologyResult;
pub use ontology::OntologyStats;
pub use ontology::Pattern;
pub use ontology::PatternHeuristicProposer;
pub use ontology::PatternMiner;
pub use ontology::PatternType;
pub use ontology::PerformanceMetrics;
pub use ontology::PerformanceValidator;
pub use ontology::ProjectionDeterminismCheck;
pub use ontology::PromotionMetrics;
pub use ontology::PromotionResult;
pub use ontology::ProposedChange;
pub use ontology::ProposerConfig;
pub use ontology::RealLLMProposer;
pub use ontology::SLOPreservationCheck;
pub use ontology::SigmaOverlay;
pub use ontology::SigmaReceipt;
pub use ontology::SigmaRuntime;
pub use ontology::SigmaSnapshot;
pub use ontology::SigmaSnapshotId;
pub use ontology::SnapshotGuard;
pub use ontology::SnapshotMetadata;
pub use ontology::StaticValidator;
pub use ontology::TestResult;
pub use ontology::TypeSoundnessCheck;
pub use ontology::ValidationContext;
pub use ontology::ValidationEvidence;
pub use ontology::ValidatorResult;

Modules§

agent
Agent-facing facade over the packs + marketplace subsystems.
audit
Audit trail module for tracking ggen sync execution
cache
Local cache manager for gpack templates
canonical
Deterministic canonicalization system for ggen
chain
Receipt chain implementation for maintaining hash-linked receipts.
cli_generator
CLI Generator for 2026 best practices
codegen
Code generation module
codegen_lib
Generic code generation framework
config
Configuration management for ggen
config_lib
ggen-config
delta
Delta-driven projection for detecting and analyzing RDF graph changes
dflss
Design for Lean Six Sigma (DFLSS) - DMADV Phase Validation
domain
ggen-domain - Domain Logic Layer
drift
Drift Detection Module
e2e_tests
End-to-end tests for the ggen core functionality
envelope
Receipt envelope (chatmangpt.receipt.envelope.v1).
error
Error types for the receipt system.
generator
Template generation engine
genesis
Genesis Core Primitives (Heap-free and no-std friendly)
github
GitHub API client for Pages and workflow operations
gpack
Gpack manifest structure and file discovery
graph
Comprehensive Oxigraph wrapper with full Store API coverage
inject
File injection utilities for template generation
lean_six_sigma
Lean Six Sigma Quality Gates - DMAIC Phase Validation
lifecycle
Universal lifecycle system for ggen (80/20 Implementation)
lockfile
Lockfile manager for governed marketplace packs.
manifest
ggen.toml manifest parsing and validation module
marketplace
ggen-marketplace-v2: Hyper-Advanced Marketplace System
membrane
Membrane system for Genesis embedded runtime integrations.
merge
Three-way merge for delta-driven projection
metrics
Quality Metrics System for ggen
ontology
ontology_core
ggen-ontology-core - Ontology Handling Layer
ontology_pack
Ontology Pack Metadata and Core Data Structures
pack_resolver
μ₀: Pack Resolution Stage
packs
Pack Installation System for ggen v4.0
parallel_generator
Parallel template generation for bulk operations
parts_execution
Parts Execution Model
parts_foundry
Parts Manufacturing Pipeline (μ₀-μ₅)
pipeline
Template processing pipeline with RDF/SPARQL integration
pipeline_engine
ggen v26_5_19: Fully-Rendered Libraries via Ontology-First Compilation
pki
Public Key Infrastructure (PKI) manager for trusted key management.
poc
Hygen-like POC with RDF support, prefixes, and inline RDF
poka_yoke
Poka-Yoke (Error-Proofing) mechanisms for ggen CLI.
pqc
Post-Quantum Cryptography (PQC) module for ggen
preprocessor
Template preprocessor pipeline for deterministic text transformations
project_generator
Project generator for scaffolding new projects
prompt_mfg
Prompt manufacturing via CONSTRUCT queries
rdf
RDF metadata management for templates using Oxigraph
receipt
receipt_impl
Receipt implementation with Ed25519 signatures.
register
Tera template environment registration and text transformation helpers
registry
Registry client for fetching gpack metadata
resolver
Template resolver for pack_id:template_path syntax
reverse_sync
Reverse synchronization - Code to RDF extraction
schema
Schema Parser and Code Generators
security
Security module for input validation, command execution safety, and error sanitization
semantic_bit
ggen-semantic-bit: The Vision 2030 Kernel
simple_tracing
Simple tracing system for pipeline debugging
snapshot
Snapshot management for delta-driven projection
stewardship
stpnt
Stewards of the Pentecost (stpnt) module
streaming_generator
Streaming file generator for memory-efficient template processing
sync
Sync orchestrator — full platform regeneration pipeline
telemetry
OpenTelemetry instrumentation for ggen
template
Template module — re-exports from template_main for backwards compatibility.
template_cache
Template caching system for performance optimization
template_types
Template system: YAML frontmatter + Tera rendering + RDF/SPARQL integration
templates
Template-to-file-tree generation system
tera_env
Tera template environment setup and configuration
tracing
transport
types
Enterprise types for FMEA & Poka-Yoke marketplace framework.
utils
ggen-utils - Shared utilities for ggen project
validation
SHACL validation module for ggen sync poka-yoke

Macros§

alert
Emit an alert with custom severity
alert_critical
Emit a critical alert (🚨)
alert_debug
Emit a debug alert (🔍)
alert_info
Emit an info alert (ℹ️)
alert_success
Emit a success alert (✅)
alert_warning
Emit a warning alert (⚠️)
bail
Return early with an error
breaking_change
Marks a breaking change with migration path
deprecated_since
Deprecation macro with version tracking and migration notes
ensure
Ensure a condition is true, or return early with an error
experimental
Marks a feature as experimental with version tracking
ggen_error
Create a new Error from a format string or literal
simple_time_operation
Macro to time an operation and record it in the current trace.
telemetry_context
Create a telemetry context with common attributes
time_operation
Macro to time an operation using PerformanceTimer
trace_span
Macro to create a tracing span

Structs§

ConfigLoader
Configuration loader and parser
EnvelopeChain
A chain of cryptographically linked envelopes.
EnvelopeChainLink
Chain link: previous envelope’s BLAKE3 hash and this envelope’s hash. Both are blake3:<hex> strings. previous_envelope_hash is None for genesis envelopes.
EnvelopeSignature
Ed25519 signature block.
GgenConfig
Root configuration structure for ggen.toml PartialEq without Eq: Contains nested config structs via composition
LockfileManager
Lock file manager
Manifest
Package manifest (Cargo.toml equivalent)
Package
A complete package with all versions
PackageId
A validated package identifier
PayloadRef
Reference to the producer-native payload that this envelope commits to.
Producer
Identity of the producing system + the native artifact kind.
QualityScore
Quality score (0-100)
RdfRegistry
High-performance RDF-backed registry
Receipt
A cryptographic receipt for an operation.
ReceiptChain
A chain of cryptographically linked receipts.
ReceiptEnvelope
A signed receipt envelope.
SparqlSearchEngine
SPARQL-powered search engine

Enums§

ConfigError
Errors that can occur during configuration operations
ReceiptError
Errors that can occur during receipt operations.

Constants§

ENVELOPE_SCHEMA
Schema discriminator for v1 envelopes.
HASH_PREFIX
Prefix for BLAKE3 hash strings used in payloads and chain links.
SIGNATURE_ALGORITHM
Canonical signature algorithm identifier (only Ed25519 in v1).

Functions§

create_chained_receipt
Convenience function to create a new receipt chained to a parent.
generate_keypair
Generates a new Ed25519 keypair.
hash_data
Computes the SHA-256 hash of arbitrary data.
payload_hash
Compute BLAKE3 hash of a payload’s bytes. Returns blake3:<hex>.

Type Aliases§

Result
Result type alias for configuration operations