# Task Flow Diagram

This diagram shows the flow of a task through the orchestration system.

```mermaid
sequenceDiagram
    participant User
    participant Brain as OrchestrationBrain
    participant Router as TaskRouter
    participant Risk as RiskGate
    participant Budget as BudgetEnforcer
    participant Agent
    participant Memory as Memory

    User->>Brain: Submit Task
    activate Brain

    Brain->>Router: Route Task
    activate Router
    Router->>Router: Check Agent Availability
    Router->>Router: Match Capabilities
    Router->>Budget: Check Budget
    Budget-->>Router: Budget OK/Exceeded
    Router-->>Brain: Selected Agent
    deactivate Router

    Brain->>Risk: Classify Risk
    activate Risk
    Risk->>Risk: Analyze Commands
    Risk->>Risk: Check File Paths
    Risk-->>Brain: Risk Level
    deactivate Risk

    alt LOW Risk
        Brain->>Agent: Execute Task (Auto-Approved)
    else MEDIUM Risk
        Brain->>User: Request Approval
        User-->>Brain: Approve/Reject
        alt Approved
            Brain->>Agent: Execute Task
        else Rejected
            Brain-->>User: Task Rejected
        end
    else HIGH Risk
        Brain->>User: Request Approval (Warning)
        User-->>Brain: Approve/Reject
        alt Approved
            Brain->>Agent: Execute Task
        else Rejected
            Brain-->>User: Task Rejected
        end
    else CRITICAL Risk
        Brain-->>User: Auto-Rejected (Blocked)
    end

    activate Agent
    Agent->>Memory: Read Context
    Memory-->>Agent: Context Data
    Agent->>Agent: Execute Task
    Agent->>Memory: Write Results
    Agent-->>Brain: StatusPacket
    deactivate Agent

    Brain->>Budget: Record Usage
    Brain-->>User: Task Complete
    deactivate Brain
```

## Flow Description

### 1. Task Submission
User submits a task through CLI, TUI, or REST API.

### 2. Task Routing
- Check which agents are available
- Match task requirements with agent capabilities
- Verify budget allows the operation
- Select the best agent for the task

### 3. Risk Classification
- Analyze commands for risk patterns
- Check file paths against blocklist
- Determine overall risk level

### 4. Approval Flow
Based on risk level:
- **LOW**: Auto-approved, immediate execution
- **MEDIUM**: Requires user confirmation
- **HIGH**: Requires explicit user approval with warning
- **CRITICAL**: Auto-rejected, blocked operations

### 5. Task Execution
- Agent reads context from memory
- Executes the task
- Writes results back to memory
- Returns status packet

### 6. Usage Recording
- Record token usage
- Update cost tracking
- Check budget alerts
