-
Notifications
You must be signed in to change notification settings - Fork 0
Code Generation
Generate production-ready code directly from specifications using AI and templates.
Status: ✅ Complete
Phase: Phase 2 - Alpha Enhanced Features
Last Updated: December 3, 2025
The RiceCoder Code Generation module generates code from specifications using AI providers and templates. It implements spec-driven development with validation, conflict detection, and review capabilities.
- Spec-driven generation: Generate code from structured specifications
- Multi-language support: Generate Rust, TypeScript, Python, Go, Java, and more
- Template-based generation: Use templates for consistent code structure
- AI enhancement: Improve generated code with AI providers
- Validation: Syntax checking, linting, and type checking before writing
- Conflict detection: Detect and resolve file conflicts intelligently
- Code quality: Enforce naming conventions, doc comments, and error handling
- Dry-run mode: Preview changes without writing files
- Rollback support: Restore previous state on failure
Generate code from a specification:
# Create a specification
rice spec create my-feature
# Define requirements and design in the spec files
# (interactive or edit spec files directly)
# Generate implementation
rice gen --spec my-feature# Generate with specific provider
rice gen --spec my-feature --provider openai
# Generate with specific model
rice gen --spec my-feature --model gpt-4
# Preview changes without writing
rice gen --spec my-feature --dry-run
# Generate with code review
rice gen --spec my-feature --review
# Generate with tests
rice gen --spec my-feature --testsPress Ctrl+C to cancel generation at any time. No files are written until validation passes.
A specification consists of three files:
.ai/specs/my-feature/
├── requirements.md # What to build (user stories, acceptance criteria)
├── design.md # How to build it (architecture, data models)
└── tasks.md # Implementation tasks (optional)
Define what needs to be built:
# Requirements
## Requirement 1: User Authentication
**User Story**: As a user, I want to log in, so that I can access my account.
### Acceptance Criteria
1. WHEN a user enters valid credentials THEN the system SHALL authenticate the user
2. WHEN a user enters invalid credentials THEN the system SHALL reject the login
3. WHEN a user logs in THEN the system SHALL create a session tokenSpecify how to build it:
# Design
## Architecture
```text
┌─────────────────────┐
│ API Layer │
├─────────────────────┤
│ Application │
├─────────────────────┤
│ Domain │
├─────────────────────┤
│ Infrastructure │
└─────────────────────┘pub struct User {
pub id: String,
pub email: String,
pub password_hash: String,
}All operations return Result<T, AuthError> with explicit error types.
---
## Generation Pipeline
The generation pipeline executes in strict order:
```text
1. Spec Processing
↓
2. Plan Generation
↓
3. Prompt Building (with steering rules)
↓
4. Code Generation (AI or templates)
↓
5. Code Quality Enforcement
↓
6. Validation (syntax, linting, types)
↓
7. Conflict Detection
↓
8. Output Writing (with rollback support)
Parse the specification and extract requirements:
rice gen --spec my-feature --verbose
# Parsing requirements.md...
# Parsing design.md...
# Extracted 5 requirements
# Generated 8 implementation stepsCreate an ordered implementation plan:
# Plan is generated automatically
# Shows dependencies and orderingBuild prompts for AI providers with context:
# Prompts include:
# - Requirements and acceptance criteria
# - Design decisions and architecture
# - Project steering rules and conventions
# - Code examples and patternsGenerate code using AI or templates:
# AI-based generation
rice gen --spec my-feature --provider openai
# Template-based generation
rice gen --spec my-feature --use-templatesApply project standards to generated code:
# Automatically adds:
# - Doc comments for public types and functions
# - Error handling for fallible operations
# - Naming conventions (snake_case, camelCase, etc.)
# - Unit tests (optional)Validate generated code before writing:
# Checks:
# - Syntax errors
# - Linting (clippy, eslint, pylint, etc.)
# - Type checking (cargo check, tsc, mypy, etc.)
# - All errors reported with file paths and line numbersDetect file conflicts before writing:
# Detects:
# - Files that would be overwritten
# - Computes diffs between old and new content
# - Reports conflict detailsWrite files with rollback support:
# Writes:
# - Creates pre-write backups
# - Writes files atomically (all-or-nothing)
# - Restores backups on failure
# - Reports all actions takenConfigure code generation in .ricecoder/config.yaml:
generation:
# Provider settings
provider: openai
model: gpt-4
temperature: 0.7
max-tokens: 4000
# Generation options
validate: true
review: false
dry-run: false
# Conflict handling
conflict-strategy: prompt # skip, overwrite, merge, prompt
# Code quality
enforce-quality: true
generate-tests: false
generate-docs: trueProject-level steering rules guide code generation:
# .ricecoder/steering.yaml
naming:
rust: snake_case
typescript: camelCase
python: snake_case
code-quality:
require-doc-comments: true
require-error-handling: true
require-tests: false
style:
line-length: 100
indent-size: 4
use-tabs: falseConfigure template locations:
templates:
paths:
- .ricecoder/templates
- ~/.ricecoder/templates
- /usr/share/ricecoder/templates
cache: true
cache-ttl: 3600Create a specification:
rice spec create user-apiEdit requirements.md:
# User API Requirements
## Requirement 1: User Endpoints
**User Story**: As an API consumer, I want REST endpoints for user management.
### Acceptance Criteria
1. WHEN I POST to /users THEN the system SHALL create a new user
2. WHEN I GET /users/{id} THEN the system SHALL return the user
3. WHEN I PUT /users/{id} THEN the system SHALL update the user
4. WHEN I DELETE /users/{id} THEN the system SHALL delete the userEdit design.md:
# User API Design
## Architecture
REST API with layered architecture:
- Interfaces: HTTP handlers
- Application: Use cases
- Domain: User entity
- Infrastructure: Database
## Data Models
```rust
pub struct User {
pub id: String,
pub name: String,
pub email: String,
}All endpoints return appropriate HTTP status codes and error messages.
Generate code:
```bash
rice gen --spec user-api --provider openai --model gpt-4
Use templates for consistent code structure:
# Generate using templates
rice gen --spec my-feature --use-templates
# Templates are applied with variable substitution
# Supports all name case variations: {{Name}}, {{name}}, {{NAME}}, {{name-kebab}}, {{name_snake}}Preview changes without writing:
# Dry-run mode shows what would be generated
rice gen --spec my-feature --dry-run
# Output shows:
# - Files that would be created
# - Files that would be modified
# - Diffs for each change
# - Conflicts that would be detectedWhen conflicts are detected:
rice gen --spec my-feature
# If conflicts detected:
# Conflict detected: src/main.rs
# Old content: ... (first 10 lines)
# New content: ... (first 10 lines)
#
# Choose strategy:
# 1. Skip - don't write this file
# 2. Overwrite - write new content and backup original
# 3. Merge - attempt intelligent merge
# 4. Show diff - display full diff
#
# Enter choice (1-4): Generate code with review:
rice gen --spec my-feature --review
# Review output:
# Code Quality Score: 8.5/10
#
# Suggestions:
# - Add error handling for database operations
# - Consider using Result type for fallible operations
# - Add unit tests for business logic
#
# Issues:
# - Missing doc comments on public functions
# - Inconsistent error handling patternsWhen generated files conflict with existing files, choose a strategy:
Don't write conflicting files:
rice gen --spec my-feature --conflict-strategy skip
# Conflicting files are skipped
# Non-conflicting files are written normallyWrite new content and backup original:
rice gen --spec my-feature --conflict-strategy overwrite
# Original files are backed up to .backup/
# New content is written
# Backup location is reportedAttempt intelligent merge:
rice gen --spec my-feature --conflict-strategy merge
# System attempts to merge changes
# If merge fails, prompts for manual resolutionAsk for each conflict:
rice gen --spec my-feature --conflict-strategy prompt
# For each conflict:
# - Shows diff
# - Asks which strategy to use
# - Applies chosen strategyView conflicts before resolving:
rice gen --spec my-feature --dry-run
# Shows all conflicts that would be detected
# Displays diffs for each conflictGenerated code is validated before writing:
# Syntax checking
# - Rust: cargo check
# - TypeScript: tsc
# - Python: python -m py_compile
# Linting
# - Rust: clippy
# - TypeScript: eslint
# - Python: pylint
# Type checking
# - Rust: cargo check (built-in)
# - TypeScript: tsc --strict
# - Python: mypy --strictIf validation fails, generation stops:
rice gen --spec my-feature
# Validation failed:
#
# src/main.rs:10:5 - error: expected `;`
# src/main.rs:15:10 - error: unknown type `User`
#
# Fix errors and try againSkip validation (not recommended):
rice gen --spec my-feature --no-validate
# Warning: Skipping validation
# Generated code may have errorsGenerated code automatically includes:
// Doc comments for public types
/// Represents a user in the system.
pub struct User {
/// Unique identifier
pub id: String,
/// User's email address
pub email: String,
}
// Error handling for fallible operations
pub fn create_user(email: &str) -> Result<User, UserError> {
validate_email(email)?;
// ... implementation
}
// Naming conventions (snake_case in Rust)
pub fn create_user_account() -> Result<(), Error> {
// ...
}Project steering rules are applied:
# .ricecoder/steering.yaml
code-quality:
require-doc-comments: true
require-error-handling: true
naming-convention: snake_caseGenerate unit tests:
rice gen --spec my-feature --tests
# Generates unit tests for all public functions
# Tests cover happy paths and error casesBefore writing files, backups are created:
rice gen --spec my-feature
# Backups created in .backup/
# Original files preserved
# If generation fails, backups are restoredRestore previous state:
# Restore from backup
rice gen --rollback
# Restores all files from most recent backup
# Reports which files were restoredView and manage backups:
# List backups
rice backup list
# Restore specific backup
rice backup restore <backup-id>
# Delete backup
rice backup delete <backup-id>
# Clean old backups
rice backup clean --older-than 7dSolution: Fix the errors in the generated code or adjust the specification:
# View validation errors
rice gen --spec my-feature --verbose
# Fix errors in specification
# Try again
rice gen --spec my-featureSolution: Use skip strategy or adjust specification:
# Skip conflicting files
rice gen --spec my-feature --conflict-strategy skip
# Or use merge strategy
rice gen --spec my-feature --conflict-strategy mergeSolution: Review the specification and adjust:
# Check specification
cat .ai/specs/my-feature/requirements.md
# Adjust specification if needed
# Try generation again
rice gen --spec my-featureSolution: Check provider and model:
# Use faster model
rice gen --spec my-feature --model gpt-3.5-turbo
# Or use templates instead of AI
rice gen --spec my-feature --use-templates
# Check network connectivity
rice infoSolution: Reduce context size:
# .ricecoder/config.yaml
generation:
max-tokens: 2000 # Reduce from 4000
context-size: 50 # Reduce contextSolution: Check steering rules:
# View steering rules
cat .ricecoder/steering.yaml
# Update if needed
rice config set naming.rust snake_caseSolution: Check file permissions:
# Check backup directory
ls -la .backup/
# Ensure write permissions
chmod 755 .backup/Solution: This shouldn't happen. Report as a bug:
# Provide details
rice gen --spec my-feature --dry-run > dry-run.txt
rice gen --spec my-feature > actual.txt
# Compare outputs
diff dry-run.txt actual.txtCreate custom templates for your project:
# Create template directory
mkdir -p .ricecoder/templates/rust
# Create template file
cat > .ricecoder/templates/rust/service-template.rs << 'EOF'
/// {{Name}} service
pub struct {{Name}} {
// Implementation
}
impl {{Name}} {
/// Create a new {{name}}
pub fn new() -> Self {
// Implementation
}
}
EOFUse custom templates:
rice gen --spec my-feature --use-templatesGenerate multiple features:
# Generate multiple specs
for spec in spec1 spec2 spec3; do
rice gen --spec $spec
doneGenerate code in CI/CD pipeline:
# .github/workflows/generate.yml
- name: Generate code
run: rice gen --spec my-feature --validateUse generation API:
use ricecoder_generation::GenerationManager;
let manager = GenerationManager::new(config);
let result = manager.generate(request).await?;
println!("Generated {} files", result.files.len());
println!("Validation: {}", result.validation.valid);# .ricecoder/config.yaml
generation:
# Use faster model
model: gpt-3.5-turbo
# Reduce context
max-tokens: 2000
# Use templates instead of AI
use-templates: true
# Disable review
review: falsegeneration:
# Split generation into smaller steps
batch-size: 5
# Cache templates
template-cache: true
# Parallel validation
parallel-validation: trueWrite detailed requirements and design before generating:
# Good specification
- Clear user stories
- Specific acceptance criteria
- Detailed design decisions
- Error handling strategy
# Poor specification
- Vague requirements
- No acceptance criteria
- Missing design detailsAlways preview changes before writing:
rice gen --spec my-feature --dry-run
# Review output
rice gen --spec my-featureReview generated code before committing:
rice gen --spec my-feature --review
# Read suggestions
# Make adjustments if neededUpdate specifications as requirements change:
# Edit specification
vim .ai/specs/my-feature/requirements.md
# Regenerate
rice gen --spec my-featureCommit specifications and generated code:
git add .ai/specs/my-feature/
git add src/
git commit -m "Generate my-feature from spec"Run tests after generation:
rice gen --spec my-feature
cargo testDocument how code was generated:
# Generated Code
This code was generated from specification:
- Spec: `.ai/specs/my-feature/`
- Generated: 2025-12-03
- Provider: OpenAI GPT-4
- Model: gpt-4
To regenerate:
```bash
rice gen --spec my-feature
---
## See Also
- [Quick Start Guide](./Quick-Start.md) - Get started with RiceCoder
- [Spec-Driven Development](./Spec-Driven-Development.md) - Learn spec-driven development
- [Configuration Guide](./Configuration.md) - Configure code generation
- [CLI Commands](./CLI-Commands.md) - Learn all CLI commands
- [Troubleshooting Guide](./Troubleshooting.md) - Solve common problems
- [Architecture Overview](./Architecture-Overview.md) - System architecture
---
*Last updated: December 3, 2025*