Skip to main content

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​

FieldTypeDescriptionConstraints
workflow_idUUIDUnique workflow identifierPrimary key, auto-generated
tenant_idUUIDAssociated tenantForeign key to Tenant
project_idUUIDAssociated projectForeign key to Project
nameStringWorkflow display nameRequired, max 255 chars
descriptionStringDetailed descriptionRequired
versionStringSemantic versionFormat: X.Y.Z
workflow_typeWorkflowType (Enum)Category of workflowRequired
statusWorkflowStatus (Enum)Current stateRequired
definitionWorkflowDefinitionComplete workflow logicRequired
triggerWorkflowTrigger (Enum)How workflow startsRequired
scheduleSchedule (Optional)For scheduled workflowsCron format
created_atDateTimeCreation timestampAuto-set
updated_atDateTimeLast modificationAuto-updated
created_byUUIDCreating userForeign key to User

WorkflowDefinition Structure​

FieldTypeDescription
stepsVecIndividual workflow steps
transitionsVecStep connections and flow
variablesVecWorkflow-level variables
error_handlersVecError handling strategies

WorkflowStep Structure​

FieldTypeDescription
step_idStringUnique step identifier
nameStringStep display name
step_typeStepType (Enum)Type of operation
configJSONStep-specific configuration
retry_policyRetryPolicy (Optional)Retry configuration
timeout_secondsu32 (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"
}
}
}

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
  • 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​

  1. Pre-conditions evaluated
  2. Step logic executed based on type
  3. Post-conditions verified
  4. Transitions evaluated for next step
  5. 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​

  1. Access Control

    • Create: Developer role required
    • Execute: Based on workflow config
    • View: Project members
    • Sensitive steps require elevated permissions
  2. Input Validation

    • Schema validation on inputs
    • Expression sandboxing
    • URL allowlisting for HTTP steps
    • Query parameterization for DB steps
  3. Execution Isolation

    • Each instance runs in isolation
    • Variable scoping enforced
    • Resource limits applied
    • Audit trail maintained

Performance Optimizations​

  1. Execution Engine

    • Async step execution
    • Parallel branch optimization
    • State persistence between steps
    • Efficient transition evaluation
  2. 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​

  1. Visual Designer

    • Drag-drop workflow builder
    • Live execution visualization
    • Debug mode with breakpoints
  2. Advanced Features

    • Sub-workflows
    • Dynamic step generation
    • External workflow marketplace
    • Version control integration

Last Updated: 2025-08-29 Version: 1.0