Workflow Model Documentation
Overview​
The Workflow model enables automated orchestration of multi-step processes within CODITECT, supporting AI agent coordination, human approvals, and complex business logic. It provides a flexible engine for defining and executing reproducible workflows.
Model Structure​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
workflow_id | UUID | Unique workflow identifier | Primary key, auto-generated |
tenant_id | UUID | Associated tenant | Foreign key to Tenant |
project_id | UUID | Associated project | Foreign key to Project |
name | String | Workflow display name | Required, max 255 chars |
description | String | Detailed description | Required |
version | String | Semantic version | Format: X.Y.Z |
workflow_type | WorkflowType (Enum) | Category of workflow | Required |
status | WorkflowStatus (Enum) | Current state | Required |
definition | WorkflowDefinition | Complete workflow logic | Required |
trigger | WorkflowTrigger (Enum) | How workflow starts | Required |
schedule | Schedule (Optional) | For scheduled workflows | Cron format |
created_at | DateTime | Creation timestamp | Auto-set |
updated_at | DateTime | Last modification | Auto-updated |
created_by | UUID | Creating user | Foreign key to User |
WorkflowDefinition Structure​
| Field | Type | Description |
|---|---|---|
steps | Vec | Individual workflow steps |
transitions | Vec | Step connections and flow |
variables | Vec | Workflow-level variables |
error_handlers | Vec | Error handling strategies |
WorkflowStep Structure​
| Field | Type | Description |
|---|---|---|
step_id | String | Unique step identifier |
name | String | Step display name |
step_type | StepType (Enum) | Type of operation |
config | JSON | Step-specific configuration |
retry_policy | RetryPolicy (Optional) | Retry configuration |
timeout_seconds | u32 (Optional) | Maximum execution time |
StepType Enum​
enum StepType {
// Agent operations
AgentTask { agent_type: String },
AgentReview { review_criteria: Vec<String> },
// Control flow
Condition { expression: String },
Parallel { branches: Vec<String> },
Sequential { steps: Vec<String> },
// Data operations
Transform { transformation: String },
Validate { schema: JsonValue },
// External integrations
HttpRequest { method: String, url: String },
DatabaseQuery { query: String },
// Human tasks
Approval { approvers: Vec<Uuid> },
Manual { instructions: String },
}
WorkflowType Enum​
enum WorkflowType {
Development, // Code development workflows
Review, // Code/document review
Deployment, // Release and deployment
Testing, // Test execution
DataProcessing, // ETL and data workflows
Approval, // Multi-step approvals
Custom // Domain-specific
}
WorkflowStatus Enum​
enum WorkflowStatus {
Draft, // Being designed
Active, // Available for execution
Paused, // Temporarily disabled
Deprecated, // Phasing out
Archived // Historical record
}
WorkflowTrigger Enum​
enum WorkflowTrigger {
Manual, // User-initiated
Schedule, // Cron-based
Event { event_type: String }, // System events
Webhook { endpoint: String }, // External triggers
FileWatch { path: String }, // File system changes
GitHook { repository: String, branch: String }, // Git events
}
Database Schema​
Primary Storage Pattern​
Key: /{tenant_id}/workflows/{workflow_id}
Value: JSON serialized Workflow object
Secondary Indexes​
Project workflows: /{tenant_id}/workflows_by_project/{project_id} -> [workflow_ids]
Type index: /{tenant_id}/workflows_by_type/{workflow_type} -> [workflow_ids]
Status index: /{tenant_id}/workflows_by_status/{status} -> [workflow_ids]
Execution Storage​
# Workflow instances/runs
Key: /{tenant_id}/workflow_instances/{instance_id}
Value: WorkflowInstance object
# Step execution results
Key: /{tenant_id}/workflow_instances/{instance_id}/steps/{step_id}
Value: StepExecutionResult
Workflow Components​
Variables​
struct Variable {
name: String,
var_type: VariableType,
default_value: Option<JsonValue>,
required: bool,
}
enum VariableType {
String,
Number,
Boolean,
DateTime,
Json,
Array { item_type: Box<VariableType> },
}
Transitions​
struct Transition {
from_step: String,
to_step: String,
condition: Option<String>, // Expression language
priority: u8, // For multiple transitions
}
Error Handling​
struct ErrorHandler {
error_type: String,
handler_type: ErrorHandlerType,
retry_count: u8,
}
enum ErrorHandlerType {
Retry,
Skip,
Fail,
Compensate { compensation_step: String },
Notify { recipients: Vec<Uuid> },
}
Retry Policies​
struct RetryPolicy {
max_attempts: u8,
backoff_strategy: BackoffStrategy,
}
enum BackoffStrategy {
Fixed { delay_seconds: u32 },
Exponential { initial_delay: u32, multiplier: f32 },
Linear { delay_increment: u32 },
}
Example Workflow Definition​
Code Review Workflow​
{
"workflow_id": "123e4567-e89b-12d3-a456-426614174000",
"name": "Automated Code Review",
"workflow_type": "Review",
"definition": {
"steps": [
{
"step_id": "lint",
"name": "Run Linters",
"step_type": {
"AgentTask": { "agent_type": "code_analyzer" }
},
"config": {
"linters": ["eslint", "rustfmt", "black"],
"fail_on_error": false
}
},
{
"step_id": "security_scan",
"name": "Security Analysis",
"step_type": {
"AgentTask": { "agent_type": "security" }
},
"retry_policy": {
"max_attempts": 3,
"backoff_strategy": { "Fixed": { "delay_seconds": 30 } }
}
},
{
"step_id": "approve",
"name": "Human Review",
"step_type": {
"Approval": {
"approvers": ["mgr-uuid", "tech-lead-uuid"]
}
},
"timeout_seconds": 86400
}
],
"transitions": [
{ "from_step": "lint", "to_step": "security_scan" },
{ "from_step": "security_scan", "to_step": "approve" }
]
},
"trigger": {
"GitHook": {
"repository": "github.com/org/repo",
"branch": "main"
}
}
}
Related Code​
Source Files​
- Model Definition:
/src/models/workflow.rs - Repository:
/src/db/repositories/workflow_repository.rs - Engine:
/src/workflow_engine/- Executor:
executor.rs - State Machine:
state_machine.rs - Expression Evaluator:
expression.rs
- Executor:
- API Handler:
/src/api/handlers/workflow_handlers.rs - Tests:
/src/workflow_engine/tests/
Key Methods​
impl Workflow {
fn new(tenant_id: Uuid, project_id: Uuid, ...) -> Self
fn validate_definition(&self) -> Result<()>
fn can_execute(&self) -> bool
fn next_version(&mut self) -> String
}
impl WorkflowEngine {
async fn execute(&self, workflow_id: Uuid, inputs: HashMap<String, Value>) -> Result<ExecutionId>
async fn get_status(&self, execution_id: Uuid) -> Result<ExecutionStatus>
async fn cancel(&self, execution_id: Uuid) -> Result<()>
}
API Endpoints​
Create Workflow​
- POST
/api/workflows - Body:
CreateWorkflowRequest - Response:
Workflow - Auth: Developer or Admin
Execute Workflow​
- POST
/api/workflows/{workflow_id}/execute - Body:
{ inputs: {...} } - Response:
WorkflowExecution - Auth: Based on workflow permissions
Get Execution Status​
- GET
/api/workflow-executions/{execution_id} - Response:
WorkflowExecutionDetail - Auth: Workflow participant
List Workflows​
- GET
/api/workflows?project_id={uuid}&type={type}&status={status} - Response:
Vec<WorkflowSummary> - Auth: Project member
Execution Model​
Workflow Instance​
struct WorkflowInstance {
instance_id: Uuid,
workflow_id: Uuid,
status: InstanceStatus,
inputs: HashMap<String, Value>,
outputs: HashMap<String, Value>,
current_step: Option<String>,
step_results: HashMap<String, StepResult>,
started_at: DateTime<Utc>,
completed_at: Option<DateTime<Utc>>,
}
enum InstanceStatus {
Pending,
Running,
Paused,
Completed,
Failed,
Cancelled,
}
Step Execution​
- Pre-conditions evaluated
- Step logic executed based on type
- Post-conditions verified
- Transitions evaluated for next step
- Error handlers invoked if needed
Use Cases​
Development Workflow​
Code Push -> Lint -> Test -> Security Scan -> Deploy to Staging -> Approval -> Deploy to Prod
Data Processing Pipeline​
File Upload -> Validate -> Transform -> Load to DB -> Generate Report -> Notify
Multi-Agent Collaboration​
Requirements -> Test Writer Agent -> Coder Agent -> Reviewer Agent -> Approval -> Merge
Security Considerations​
-
Access Control
- Create: Developer role required
- Execute: Based on workflow config
- View: Project members
- Sensitive steps require elevated permissions
-
Input Validation
- Schema validation on inputs
- Expression sandboxing
- URL allowlisting for HTTP steps
- Query parameterization for DB steps
-
Execution Isolation
- Each instance runs in isolation
- Variable scoping enforced
- Resource limits applied
- Audit trail maintained
Performance Optimizations​
-
Execution Engine
- Async step execution
- Parallel branch optimization
- State persistence between steps
- Efficient transition evaluation
-
Storage
- Workflow definitions cached
- Hot paths pre-compiled
- Execution state in memory
- Results archived after completion
Monitoring & Observability​
- Step duration metrics
- Success/failure rates
- Resource utilization
- Queue depths
- Error frequency by type
Future Enhancements​
-
Visual Designer
- Drag-drop workflow builder
- Live execution visualization
- Debug mode with breakpoints
-
Advanced Features
- Sub-workflows
- Dynamic step generation
- External workflow marketplace
- Version control integration
Last Updated: 2025-08-29 Version: 1.0