# Code Generation Guide Generate production-ready code directly from specifications using AI and templates. **Status**: ✅ Complete **Phase**: Phase 2 - Alpha Enhanced Features **Last Updated**: December 3, 2025 --- ## Overview 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. ### Key Concepts - **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 --- ## Getting Started ### Basic Usage Generate code from a specification: ```bash # 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 ``` ### With Options ```bash # 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 --tests ``` ### Exiting Generation Press `Ctrl+C` to cancel generation at any time. No files are written until validation passes. --- ## Specification Format ### Spec Structure 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) ``` ### Requirements File Define what needs to be built: ```markdown # 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 token ``` ### Design File Specify how to build it: ```markdown # Design ## Architecture ```text ┌─────────────────────┐ │ API Layer │ ├─────────────────────┤ │ Application │ ├─────────────────────┤ │ Domain │ ├─────────────────────┤ │ Infrastructure │ └─────────────────────┘ ``` ## Data Models ```rust pub struct User { pub id: String, pub email: String, pub password_hash: String, } ``` ## Error Handling All operations return `Result` 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) ``` ### Step 1: Spec Processing Parse the specification and extract requirements: ```bash rice gen --spec my-feature --verbose # Parsing requirements.md... # Parsing design.md... # Extracted 5 requirements # Generated 8 implementation steps ``` ### Step 2: Plan Generation Create an ordered implementation plan: ```bash # Plan is generated automatically # Shows dependencies and ordering ``` ### Step 3: Prompt Building Build prompts for AI providers with context: ```bash # Prompts include: # - Requirements and acceptance criteria # - Design decisions and architecture # - Project steering rules and conventions # - Code examples and patterns ``` ### Step 4: Code Generation Generate code using AI or templates: ```bash # AI-based generation rice gen --spec my-feature --provider openai # Template-based generation rice gen --spec my-feature --use-templates ``` ### Step 5: Code Quality Enforcement Apply project standards to generated code: ```bash # Automatically adds: # - Doc comments for public types and functions # - Error handling for fallible operations # - Naming conventions (snake_case, camelCase, etc.) # - Unit tests (optional) ``` ### Step 6: Validation Validate generated code before writing: ```bash # Checks: # - Syntax errors # - Linting (clippy, eslint, pylint, etc.) # - Type checking (cargo check, tsc, mypy, etc.) # - All errors reported with file paths and line numbers ``` ### Step 7: Conflict Detection Detect file conflicts before writing: ```bash # Detects: # - Files that would be overwritten # - Computes diffs between old and new content # - Reports conflict details ``` ### Step 8: Output Writing Write files with rollback support: ```bash # Writes: # - Creates pre-write backups # - Writes files atomically (all-or-nothing) # - Restores backups on failure # - Reports all actions taken ``` --- ## Configuration ### Generation Settings Configure code generation in `.ricecoder/config.yaml`: ```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: true ``` ### Steering Rules Project-level steering rules guide code generation: ```yaml # .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: false ``` ### Template Configuration Configure template locations: ```yaml templates: paths: - .ricecoder/templates - ~/.ricecoder/templates - /usr/share/ricecoder/templates cache: true cache-ttl: 3600 ``` --- ## Usage Examples ### Example 1: Generate a REST API Create a specification: ```bash rice spec create user-api ``` Edit `requirements.md`: ```markdown # 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 user ``` Edit `design.md`: ```markdown # 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, } ``` ## Error Handling All endpoints return appropriate HTTP status codes and error messages. ``` Generate code: ```bash rice gen --spec user-api --provider openai --model gpt-4 ``` ### Example 2: Generate from Templates Use templates for consistent code structure: ```bash # 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}} ``` ### Example 3: Preview Changes Preview changes without writing: ```bash # 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 detected ``` ### Example 4: Handle Conflicts When conflicts are detected: ```bash 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): ``` ### Example 5: Review Generated Code Generate code with review: ```bash 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 patterns ``` --- ## Conflict Resolution ### Conflict Strategies When generated files conflict with existing files, choose a strategy: #### Skip Strategy Don't write conflicting files: ```bash rice gen --spec my-feature --conflict-strategy skip # Conflicting files are skipped # Non-conflicting files are written normally ``` #### Overwrite Strategy Write new content and backup original: ```bash rice gen --spec my-feature --conflict-strategy overwrite # Original files are backed up to .backup/ # New content is written # Backup location is reported ``` #### Merge Strategy Attempt intelligent merge: ```bash rice gen --spec my-feature --conflict-strategy merge # System attempts to merge changes # If merge fails, prompts for manual resolution ``` #### Prompt Strategy Ask for each conflict: ```bash rice gen --spec my-feature --conflict-strategy prompt # For each conflict: # - Shows diff # - Asks which strategy to use # - Applies chosen strategy ``` ### Viewing Conflicts View conflicts before resolving: ```bash rice gen --spec my-feature --dry-run # Shows all conflicts that would be detected # Displays diffs for each conflict ``` --- ## Validation ### Validation Checks Generated code is validated before writing: ```bash # 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 --strict ``` ### Validation Errors If validation fails, generation stops: ```bash 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 again ``` ### Skipping Validation Skip validation (not recommended): ```bash rice gen --spec my-feature --no-validate # Warning: Skipping validation # Generated code may have errors ``` --- ## Code Quality ### Automatic Improvements Generated code automatically includes: ```rust // 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 { validate_email(email)?; // ... implementation } // Naming conventions (snake_case in Rust) pub fn create_user_account() -> Result<(), Error> { // ... } ``` ### Enforcing Standards Project steering rules are applied: ```yaml # .ricecoder/steering.yaml code-quality: require-doc-comments: true require-error-handling: true naming-convention: snake_case ``` ### Optional Test Generation Generate unit tests: ```bash rice gen --spec my-feature --tests # Generates unit tests for all public functions # Tests cover happy paths and error cases ``` --- ## Rollback Support ### Automatic Backups Before writing files, backups are created: ```bash rice gen --spec my-feature # Backups created in .backup/ # Original files preserved # If generation fails, backups are restored ``` ### Manual Rollback Restore previous state: ```bash # Restore from backup rice gen --rollback # Restores all files from most recent backup # Reports which files were restored ``` ### Backup Management View and manage backups: ```bash # List backups rice backup list # Restore specific backup rice backup restore # Delete backup rice backup delete # Clean old backups rice backup clean --older-than 7d ``` --- ## Troubleshooting ### Issue: Generation fails with validation errors **Solution**: Fix the errors in the generated code or adjust the specification: ```bash # View validation errors rice gen --spec my-feature --verbose # Fix errors in specification # Try again rice gen --spec my-feature ``` ### Issue: Conflicts detected for all files **Solution**: Use skip strategy or adjust specification: ```bash # Skip conflicting files rice gen --spec my-feature --conflict-strategy skip # Or use merge strategy rice gen --spec my-feature --conflict-strategy merge ``` ### Issue: Generated code doesn't match specification **Solution**: Review the specification and adjust: ```bash # Check specification cat .ai/specs/my-feature/requirements.md # Adjust specification if needed # Try generation again rice gen --spec my-feature ``` ### Issue: Generation is slow **Solution**: Check provider and model: ```bash # 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 info ``` ### Issue: Out of memory during generation **Solution**: Reduce context size: ```yaml # .ricecoder/config.yaml generation: max-tokens: 2000 # Reduce from 4000 context-size: 50 # Reduce context ``` ### Issue: Generated code has wrong naming conventions **Solution**: Check steering rules: ```bash # View steering rules cat .ricecoder/steering.yaml # Update if needed rice config set naming.rust snake_case ``` ### Issue: Backups not being created **Solution**: Check file permissions: ```bash # Check backup directory ls -la .backup/ # Ensure write permissions chmod 755 .backup/ ``` ### Issue: Dry-run shows different output than actual generation **Solution**: This shouldn't happen. Report as a bug: ```bash # 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.txt ``` --- ## Advanced Usage ### Custom Templates Create custom templates for your project: ```bash # 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 } } EOF ``` Use custom templates: ```bash rice gen --spec my-feature --use-templates ``` ### Batch Generation Generate multiple features: ```bash # Generate multiple specs for spec in spec1 spec2 spec3; do rice gen --spec $spec done ``` ### Integration with CI/CD Generate code in CI/CD pipeline: ```bash # .github/workflows/generate.yml - name: Generate code run: rice gen --spec my-feature --validate ``` ### Programmatic Generation Use generation API: ```rust 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); ``` --- ## Performance ### Optimize Generation Speed ```yaml # .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: false ``` ### Optimize for Large Projects ```yaml generation: # Split generation into smaller steps batch-size: 5 # Cache templates template-cache: true # Parallel validation parallel-validation: true ``` --- ## Best Practices ### 1. Start with Clear Specifications Write detailed requirements and design before generating: ```markdown # Good specification - Clear user stories - Specific acceptance criteria - Detailed design decisions - Error handling strategy # Poor specification - Vague requirements - No acceptance criteria - Missing design details ``` ### 2. Use Dry-Run First Always preview changes before writing: ```bash rice gen --spec my-feature --dry-run # Review output rice gen --spec my-feature ``` ### 3. Review Generated Code Review generated code before committing: ```bash rice gen --spec my-feature --review # Read suggestions # Make adjustments if needed ``` ### 4. Keep Specifications Updated Update specifications as requirements change: ```bash # Edit specification vim .ai/specs/my-feature/requirements.md # Regenerate rice gen --spec my-feature ``` ### 5. Use Version Control Commit specifications and generated code: ```bash git add .ai/specs/my-feature/ git add src/ git commit -m "Generate my-feature from spec" ``` ### 6. Test Generated Code Run tests after generation: ```bash rice gen --spec my-feature cargo test ``` ### 7. Document Generation Process Document how code was generated: ```markdown # 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*