# Workflows & Execution Guide Define and execute complex multi-step automated processes with human oversight and risk assessment. **Status**: ✅ Complete **Phase**: Phase 2 - Alpha Enhanced Features (v0.1.2) **Last Updated**: December 4, 2025 --- ## Overview The RiceCoder Workflows module provides a declarative workflow definition language for orchestrating complex multi-step agentic operations. Workflows support conditional branching, error handling with automatic recovery, human approval gates, and risk-scored execution with safety constraints. ### Key Concepts - **Declarative workflows**: Define workflows in YAML with clear step dependencies - **State management**: Persist workflow state across restarts; pause and resume execution - **Error handling**: Automatic retry, skip, fail, or rollback on step failures - **Approval gates**: Human approval checkpoints for critical operations - **Risk scoring**: Automatic risk assessment with approval requirements for high-risk steps - **Progress tracking**: Real-time status updates with estimated completion time - **Activity logging**: Complete audit trail of all workflow activities --- ## Getting Started ### Basic Workflow Create a simple workflow in `.ricecoder/workflows/example.yaml`: ```yaml id: code-review-workflow name: Code Review Workflow description: Automated code review with human approval steps: - id: analyze name: Analyze Code type: agent agent: code-review config: scope: changed_files - id: review-approval name: Review Approval type: approval dependencies: [analyze] message: "Review findings and approve changes" timeout: 1h - id: apply-fixes name: Apply Fixes type: agent agent: refactor dependencies: [review-approval] approval_required: true on_error: rollback ``` ### Running a Workflow Execute a workflow: ```bash # Run workflow rice workflow run code-review-workflow # Run with parameters rice workflow run code-review-workflow --param scope=src/ # Run in dry-run mode (preview only) rice workflow run code-review-workflow --dry-run # Run with specific approval timeout rice workflow run code-review-workflow --approval-timeout 2h ``` ### Monitoring Workflow Execution View workflow status: ```bash # View current status rice workflow status code-review-workflow # View progress rice workflow progress code-review-workflow # View activity log rice workflow logs code-review-workflow # View risk assessment rice workflow risk-report code-review-workflow ``` ### Pausing and Resuming Pause and resume workflows: ```bash # Pause workflow rice workflow pause code-review-workflow # Resume workflow rice workflow resume code-review-workflow # Cancel workflow rice workflow cancel code-review-workflow ``` --- ## Workflow Definition ### Step Types Workflows support five step types: #### Agent Steps Execute an agent (code review, refactoring, etc.): ```yaml - id: analyze name: Analyze Code type: agent agent: code-review config: scope: changed_files checks: [naming, security, performance] timeout: 30s on_error: retry ``` #### Command Steps Execute shell commands: ```yaml - id: build name: Build Project type: command command: cargo build --release args: [] timeout: 5m on_error: fail ``` #### Condition Steps Branch based on previous step results: ```yaml - id: check-quality name: Check Code Quality type: condition condition: "analyze.severity_score < 5" then_steps: [apply-fixes] else_steps: [notify-team] dependencies: [analyze] ``` #### Parallel Steps Execute multiple steps concurrently: ```yaml - id: parallel-analysis name: Parallel Analysis type: parallel steps: [code-review, security-scan, performance-analysis] max_concurrency: 3 dependencies: [] ``` #### Approval Steps Request human approval: ```yaml - id: review-approval name: Review Approval type: approval message: "Review findings and approve changes" timeout: 1h default: reject dependencies: [analyze] ``` ### Step Dependencies Define execution order with dependencies: ```yaml steps: - id: step1 name: First Step type: agent agent: code-review - id: step2 name: Second Step type: agent agent: security-scan dependencies: [step1] # Runs after step1 completes - id: step3 name: Third Step type: agent agent: refactor dependencies: [step1, step2] # Runs after both complete ``` ### Error Handling Configure error handling for each step: ```yaml - id: risky-operation name: Risky Operation type: agent agent: refactor on_error: rollback # Options: fail, retry, skip, rollback # Retry configuration retry: max_attempts: 3 delay: 5s backoff: exponential # linear, exponential, fixed # Rollback configuration rollback: steps: [undo-changes] # Steps to execute on failure ``` ### Parameters Define workflow parameters: ```yaml id: parameterized-workflow name: Parameterized Workflow description: Workflow with parameters parameters: - name: scope type: string default: "src/" description: "Code scope to analyze" - name: severity_threshold type: string default: "warning" description: "Minimum severity level" enum: [critical, warning, info] steps: - id: analyze name: Analyze Code type: agent agent: code-review config: scope: ${scope} severity_threshold: ${severity_threshold} ``` ### Approval Gates Configure approval requirements: ```yaml - id: approval name: Approval Gate type: approval message: "Please review and approve" timeout: 1h default: reject # reject or approve # Approval requirements required_approvers: 2 allowed_roles: [admin, lead] ``` --- ## Configuration ### Workflow Configuration Configure workflows in `.ricecoder/config.yaml`: ```yaml workflows: # Default timeout for all steps default-timeout: 30m # Default approval timeout approval-timeout: 1h # Retry configuration retry: enabled: true max-attempts: 3 backoff: exponential # State persistence state: enabled: true location: ~/.ricecoder/workflows/state/ # Risk scoring risk-scoring: enabled: true threshold: 50 # Require approval for scores > 50 # Logging logging: enabled: true level: info location: ~/.ricecoder/workflows/logs/ ``` ### Risk Scoring Configuration Configure risk assessment: ```yaml risk-scoring: enabled: true threshold: 50 # Require approval for scores > 50 # Risk factors factors: impact: 0.4 # Data loss potential (0-1) reversibility: 0.3 # Ability to undo (0-1) complexity: 0.3 # Number of dependencies (0-1) # Safety constraints for high-risk operations safety-constraints: timeout: 5m memory-limit: 1GB cpu-limit: 50% file-handles-limit: 100 ``` ### Approval Configuration Configure approval requirements: ```yaml approval: # Approval timeout timeout: 1h # Default action on timeout default-on-timeout: reject # Required approvers required-approvers: 1 # Allowed roles allowed-roles: - admin - lead - reviewer ``` --- ## Usage Examples ### Example 1: Simple Sequential Workflow Execute steps in sequence: ```yaml id: simple-workflow name: Simple Workflow description: Execute steps sequentially steps: - id: step1 name: First Step type: agent agent: code-review - id: step2 name: Second Step type: agent agent: refactor dependencies: [step1] - id: step3 name: Third Step type: agent agent: test-generator dependencies: [step2] ``` Run it: ```bash rice workflow run simple-workflow ``` ### Example 2: Conditional Workflow Branch based on conditions: ```yaml id: conditional-workflow name: Conditional Workflow description: Branch based on code quality steps: - id: analyze name: Analyze Code type: agent agent: code-review - id: check-quality name: Check Quality type: condition condition: "analyze.severity_score < 5" then_steps: [apply-fixes] else_steps: [notify-team] dependencies: [analyze] - id: apply-fixes name: Apply Fixes type: agent agent: refactor - id: notify-team name: Notify Team type: command command: echo "Code quality issues found" ``` Run it: ```bash rice workflow run conditional-workflow ``` ### Example 3: Parallel Workflow Execute steps in parallel: ```yaml id: parallel-workflow name: Parallel Workflow description: Run multiple agents in parallel steps: - id: parallel-analysis name: Parallel Analysis type: parallel steps: [code-review, security-scan, performance-analysis] max_concurrency: 3 - id: aggregate name: Aggregate Results type: agent agent: result-aggregator dependencies: [parallel-analysis] ``` Run it: ```bash rice workflow run parallel-workflow ``` ### Example 4: Workflow with Approval Include approval gates: ```yaml id: approval-workflow name: Approval Workflow description: Workflow with approval gates steps: - id: analyze name: Analyze Code type: agent agent: code-review - id: approval name: Approval Gate type: approval message: "Review findings and approve changes" timeout: 1h dependencies: [analyze] - id: apply name: Apply Changes type: agent agent: refactor dependencies: [approval] approval_required: true on_error: rollback ``` Run it: ```bash rice workflow run approval-workflow ``` ### Example 5: Parameterized Workflow Use parameters: ```yaml id: parameterized-workflow name: Parameterized Workflow description: Workflow with parameters parameters: - name: scope type: string default: "src/" - name: checks type: string default: "naming,security" steps: - id: analyze name: Analyze Code type: agent agent: code-review config: scope: ${scope} checks: ${checks} ``` Run it: ```bash rice workflow run parameterized-workflow --param scope=src/main.rs --param checks=security ``` ### Example 6: Error Handling Workflow Configure error handling: ```yaml id: error-handling-workflow name: Error Handling Workflow description: Workflow with error handling steps: - id: risky-operation name: Risky Operation type: agent agent: refactor on_error: retry retry: max_attempts: 3 delay: 5s backoff: exponential - id: fallback name: Fallback Operation type: agent agent: code-review dependencies: [risky-operation] on_error: skip ``` Run it: ```bash rice workflow run error-handling-workflow ``` ### Example 7: Risk-Scored Workflow Automatic risk assessment: ```yaml id: risk-scored-workflow name: Risk-Scored Workflow description: Workflow with risk assessment steps: - id: analyze name: Analyze Code type: agent agent: code-review - id: high-risk-refactor name: High-Risk Refactor type: agent agent: refactor dependencies: [analyze] approval_required: true # Requires approval due to risk on_error: rollback ``` Run it: ```bash rice workflow run risk-scored-workflow ``` --- ## State Management ### Workflow State Workflows persist state automatically: ```bash # View workflow state rice workflow state code-review-workflow # Output: # Workflow: code-review-workflow # Status: Running # Current Step: analyze # Progress: 33% # Completed Steps: [step1] # Started: 2025-12-04 10:30:00 # Updated: 2025-12-04 10:35:00 ``` ### Pause and Resume Pause workflows and resume later: ```bash # Pause workflow rice workflow pause code-review-workflow # Resume workflow rice workflow resume code-review-workflow # Workflow resumes from paused step without re-executing completed steps ``` ### State Persistence State is persisted to disk: ```bash # View state file cat ~/.ricecoder/workflows/state/code-review-workflow.json # Output: # { # "workflow_id": "code-review-workflow", # "status": "paused", # "current_step": "analyze", # "completed_steps": ["step1"], # "step_results": {...}, # "started_at": "2025-12-04T10:30:00Z", # "updated_at": "2025-12-04T10:35:00Z" # } ``` --- ## Progress Tracking ### Real-Time Status View workflow progress: ```bash # View progress rice workflow progress code-review-workflow # Output: # Workflow: code-review-workflow # Status: Running # Progress: 66% (2/3 steps completed) # Current Step: review-approval # Estimated Completion: 2025-12-04 10:45:00 (10 minutes remaining) ``` ### Activity Log View all workflow activities: ```bash # View activity log rice workflow logs code-review-workflow # Output: # 2025-12-04 10:30:00 [INFO] Workflow started # 2025-12-04 10:30:05 [INFO] Step 'analyze' started # 2025-12-04 10:35:00 [INFO] Step 'analyze' completed (5 minutes) # 2025-12-04 10:35:01 [INFO] Step 'review-approval' started # 2025-12-04 10:35:02 [INFO] Waiting for approval ``` ### Metrics View workflow metrics: ```bash # View metrics rice workflow metrics code-review-workflow # Output: # Total Duration: 15 minutes # Step Durations: # - analyze: 5 minutes # - review-approval: 8 minutes (waiting for approval) # - apply-fixes: 2 minutes # Success Rate: 100% # Retry Count: 0 ``` --- ## Risk Assessment ### Risk Scoring Workflows automatically calculate risk scores: ```bash # View risk assessment rice workflow risk-report code-review-workflow # Output: # Risk Assessment Report # ==================== # # Overall Risk Score: 45/100 (Medium) # # Step Risk Scores: # - analyze: 10/100 (Low) # - review-approval: 20/100 (Low) # - apply-fixes: 75/100 (High) # # Risk Factors: # - Impact (data loss potential): 0.8 # - Reversibility (ability to undo): 0.6 # - Complexity (dependencies): 0.5 # # Approval Decisions: # - apply-fixes: Approved by admin at 2025-12-04 10:35:00 # # Safety Constraints Applied: # - Timeout: 5 minutes # - Memory Limit: 1GB # - CPU Limit: 50% ``` ### High-Risk Operations High-risk steps require approval: ```yaml - id: high-risk-operation name: High-Risk Operation type: agent agent: refactor approval_required: true # Requires approval on_error: rollback # Rollback on failure ``` ### Safety Constraints Safety constraints are applied to high-risk operations: ```yaml risk-scoring: safety-constraints: timeout: 5m memory-limit: 1GB cpu-limit: 50% file-handles-limit: 100 ``` --- ## Error Handling ### Retry Logic Automatically retry failed steps: ```yaml - id: step name: Step type: agent agent: code-review on_error: retry retry: max_attempts: 3 delay: 5s backoff: exponential ``` ### Skip on Error Skip failed steps and continue: ```yaml - id: step name: Step type: agent agent: code-review on_error: skip ``` ### Rollback on Error Rollback changes on failure: ```yaml - id: step name: Step type: agent agent: refactor on_error: rollback rollback: steps: [undo-changes] ``` ### Error Recovery Resume from last completed step: ```bash # Workflow fails at step 3 rice workflow run workflow-name # Fix the issue # Resume workflow rice workflow resume workflow-name # Workflow resumes from step 3 without re-executing steps 1-2 ``` --- ## Troubleshooting ### Issue: Workflow is stuck waiting for approval **Solution**: Check approval status and approve or reject: ```bash # View approval status rice workflow status workflow-name # Approve workflow rice workflow approve workflow-name # Or reject rice workflow reject workflow-name ``` ### Issue: Workflow step times out **Solution**: Increase timeout or reduce scope: ```bash # Increase timeout rice workflow run workflow-name --timeout 10m # Or edit workflow to increase step timeout # - id: step # timeout: 10m ``` ### Issue: Workflow fails with error **Solution**: Check error details and retry: ```bash # View error details rice workflow logs workflow-name # Retry workflow rice workflow resume workflow-name ``` ### Issue: Workflow state is corrupted **Solution**: Reset state and restart: ```bash # Reset state rice workflow reset workflow-name # Restart workflow rice workflow run workflow-name ``` ### Issue: Approval timeout expired **Solution**: Restart workflow with longer timeout: ```bash # Restart workflow with longer approval timeout rice workflow run workflow-name --approval-timeout 2h ``` ### Issue: High-risk operation blocked **Solution**: Approve high-risk operation: ```bash # View risk assessment rice workflow risk-report workflow-name # Approve operation rice workflow approve workflow-name ``` ### Issue: Workflow parameters not substituted **Solution**: Check parameter syntax and values: ```bash # View workflow definition cat .ricecoder/workflows/workflow-name.yaml # Check parameter syntax: ${param_name} # Run with parameters rice workflow run workflow-name --param param_name=value ``` ### Issue: Rollback failed **Solution**: Check rollback steps and fix: ```bash # View rollback steps cat .ricecoder/workflows/workflow-name.yaml # Check rollback step configuration # Ensure rollback steps are valid # Retry workflow rice workflow resume workflow-name ``` --- ## Advanced Usage ### Custom Workflows Create custom workflows for your project: ```bash # Create workflow rice workflow create my-workflow # Edit workflow vim .ricecoder/workflows/my-workflow.yaml # Run workflow rice workflow run my-workflow ``` ### Workflow Composition Compose workflows into larger workflows: ```yaml id: master-workflow name: Master Workflow description: Composed of multiple workflows steps: - id: workflow1 name: First Workflow type: workflow workflow: workflow-1 - id: workflow2 name: Second Workflow type: workflow workflow: workflow-2 dependencies: [workflow1] ``` ### Integration with CI/CD Run workflows in CI/CD pipeline: ```yaml # .github/workflows/workflow.yml - name: Run workflow run: rice workflow run code-review-workflow - name: Check workflow status run: | status=$(rice workflow status code-review-workflow | grep Status) if [[ $status == *"Failed"* ]]; then exit 1 fi ``` ### Programmatic Usage Use workflows programmatically: ```rust use ricecoder_workflows::{WorkflowEngine, Workflow}; let engine = WorkflowEngine::new(); let workflow = Workflow::from_file("workflows/example.yaml")?; let state = engine.execute(&workflow).await?; println!("Status: {:?}", state.status); ``` --- ## Best Practices ### 1. Start Simple Begin with simple sequential workflows: ```yaml steps: - id: step1 type: agent agent: code-review - id: step2 type: agent agent: refactor dependencies: [step1] ``` ### 2. Use Meaningful Names Use clear, descriptive names: ```yaml - id: analyze-code-quality name: Analyze Code Quality type: agent agent: code-review ``` ### 3. Add Error Handling Always configure error handling: ```yaml - id: step type: agent agent: refactor on_error: retry retry: max_attempts: 3 delay: 5s ``` ### 4. Use Approval Gates Add approval gates for critical operations: ```yaml - id: approval type: approval message: "Review and approve changes" timeout: 1h ``` ### 5. Monitor Progress Check workflow progress regularly: ```bash rice workflow progress workflow-name ``` ### 6. Review Logs Review activity logs for issues: ```bash rice workflow logs workflow-name ``` ### 7. Test Workflows Test workflows in dry-run mode: ```bash rice workflow run workflow-name --dry-run ``` ### 8. Document Workflows Document workflow purpose and steps: ```yaml id: my-workflow name: My Workflow description: | This workflow performs code review and applies fixes. It requires approval before applying changes. ``` --- ## See Also - [Quick Start Guide](./Quick-Start.md) - Get started with RiceCoder - [Multi-Agent Framework](./Multi-Agent-Framework.md) - Learn about agents - [Configuration Guide](./Configuration.md) - Configure RiceCoder - [CLI Commands](./CLI-Commands.md) - Learn all CLI commands - [Architecture Overview](./Architecture-Overview.md) - System architecture - [Troubleshooting Guide](./Troubleshooting.md) - Solve common problems --- *Last updated: December 4, 2025*