# Workflow Enforcement Plugin Specification

## Overview

The Workflow Enforcement Plugin detects todo lists in LLM responses and enforces sequential completion with tool calling verification and confirmation requirements. Ensures that when the LLM provides a todo list, it actually executes and completes each step.

**Location:** `plugins/workflow_enforcement_plugin.py`

**Version:** 1.0.0

## Features

### Todo Detection

- **Pattern matching**: Automatically detects todo lists in LLM responses
- **Multiple formats**: Supports various todo list formats (checkboxes, bullets, numbered)
- **Context extraction**: Preserves original request and LLM response context

### Sequential Enforcement

- **Step-by-step tracking**: Maintains current todo index
- **Verification required**: Each step must be verified via tool calls
- **User confirmation**: Requires user confirmation before proceeding
- **Bypass support**: Allows user to bypass or stop enforcement at any time

### State Management

- **Workflow states**: INACTIVE, TODO_DETECTED, ENFORCING, WAITING_CONFIRMATION, BLOCKED, COMPLETED
- **Todo item tracking**: Tracks completion, confirmation, attempts, failures
- **Timestamp logging**: Records start and completion times for each step

## Workflow States

```
┌─────────────────────┐
│     INACTIVE        │
│   (no workflow)    │
└─────────┬───────────┘
          │ LLM response with todos
          ↓
┌─────────────────────┐
│   TODO_DETECTED     │
│  (waiting confirm)  │
└─────────┬───────────┘
          │ User confirms
          ↓
┌─────────────────────┐
│     ENFORCING      │
│  (executing steps)  │
└─────────┬───────────┘
          │ Step complete
          ↓
┌─────────────────────┐
│ WAITING_CONFIRM    │
│  (step verification)│
└─────────┬───────────┘
          │ Verified / Bypass / Block
          ↓
┌─────────────────────┐
│    BLOCKED /       │ ←─────┐
│   COMPLETED        │       │
└─────────────────────┘       │
                              │ Bypass / Issue
                              │ (restart workflow)
```

## Configuration

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enabled` | boolean | `false` | Enable workflow enforcement (disabled by default) |
| `require_tool_calls` | boolean | `true` | Require tool calls for verification |
| `confirmation_timeout` | int | `300` | Confirmation timeout (seconds) |
| `bypass_keywords` | list | `["bypass", "skip", ...]` | Keywords to bypass enforcement |
| `auto_start_workflows` | boolean | `true` | Auto-start when todos detected |
| `show_progress_in_status` | boolean | `true` | Show workflow progress in status bar |

### Configuration File

Edit `~/.kollabor-cli/config.json`:

```json
{
  "workflow_enforcement": {
    "enabled": false,
    "require_tool_calls": true,
    "confirmation_timeout": 300,
    "bypass_keywords": ["bypass", "skip", "blocked", "issue", "problem"],
    "auto_start_workflows": true,
    "show_progress_in_status": true
  }
}
```

## Architecture

### Data Models

#### TodoItem

```python
@dataclass
class TodoItem:
    index: int
    text: str
    terminal_command: Optional[str] = None
    completed: bool = False
    confirmed: bool = False
    attempted: bool = False
    failure_reason: Optional[str] = None
    timestamp_started: Optional[datetime] = None
    timestamp_completed: Optional[datetime] = None
```

#### WorkflowContext

```python
@dataclass
class WorkflowContext:
    original_request: str
    todo_items: List[TodoItem]
    current_todo_index: int
    state: WorkflowState
    llm_response_with_todos: str
    bypass_requested: bool
    bypass_reason: str
    started_at: Optional[datetime]
    completed_at: Optional[datetime]
```

### Event Integration

| Event Type | Description |
|------------|-------------|
| `LLM_RESPONSE_POST` | Detects todo lists in responses |
| `TOOL_CALL_POST` | Verifies step completion via tool calls |
| `USER_INPUT_PRE` | Handles user confirmations and bypass |

### Custom Events

| Event | Data | Description |
|-------|------|-------------|
| `workflow_started` | `{original_request, todo_count}` | Emitted when workflow starts |
| `workflow_step_started` | `{step_index, step_text}` | Emitted when step starts |
| `workflow_step_completed` | `{step_index, duration}` | Emitted when step completes |
| `workflow_step_failed` | `{step_index, reason}` | Emitted when step fails |
| `workflow_completed` | `{total_duration}` | Emitted when workflow completes |
| `workflow_bypassed` | `{reason}` | Emitted when workflow bypassed |

## Todo Detection Patterns

### Supported Formats

Checkbox format:
```
todo:
  [ ] Step 1
  [ ] Step 2
  [x] Step 3
```

Bullet format:
```
todo:
  - Step 1
  - Step 2
```

Numbered format:
```
steps:
  1. Step 1
  2. Step 2
```

### Regex Patterns

```python
# Checkbox pattern
r'\[\s*\]\s*(.+?)(?:\n|$)'

# Bullet pattern
r'^\s*[-*]\s*(.+?)(?:\n|$)'

# Numbered pattern
r'^\s*\d+\.\s*(.+?)(?:\n|$)'
```

## Workflow Execution

### Detection Phase

1. LLM responds with todo list
2. Plugin detects todos via pattern matching
3. State transitions: INACTIVE → TODO_DETECTED
4. User prompted to confirm enforcement

### Enforcement Phase

5. User confirms: State → ENFORCING
6. Plugin sets current step index = 0
7. Emits `workflow_step_started` event
8. LLM executes step (may use tool calls)

### Verification Phase

9. Tool calls executed (if required)
10. Plugin receives `TOOL_CALL_POST` event
11. Verifies step completion
12. State → WAITING_CONFIRMATION
13. User confirms step completion

### Continuation

14. If more steps: Index++, state → ENFORCING, repeat from step 7
15. If all complete: State → COMPLETED
16. Emit `workflow_completed` event

## User Interaction

### Confirmation Prompt

```
Workflow Enforcement
═══════════════════════════════════════════════════════════════

Detected 3 tasks from LLM response:

  [ ] Step 1: Set up database connection
  [ ] Step 2: Create user table
  [ ] Step 3: Add test data

Enforce sequential completion with tool call verification?

[y] Yes, enforce workflow  [n] No, continue normally  [s] Skip this workflow
```

### Step Progress

```
Workflow Progress
═══════════════════════════════════════════════════════════════

Current step (1/3):

  [✓] Step 1: Set up database connection  (completed in 2.3s)
  [→] Step 2: Create user table              (in progress)
  [ ] Step 3: Add test data

Waiting for tool call verification...
```

### Bypass Confirmation

```
Workflow Bypass
═══════════════════════════════════════════════════════════════

Bypass workflow enforcement?

Reason: User requested bypass (keyword: "bypass")

Options:
  [c] Confirm bypass  [r] Resume workflow  [b] Block workflow
```

## Status Display

### Progress Indicator

```
Workflow: 1/3 complete (2m30s)
```

Colors:
- In progress: cyan
- Complete: green
- Blocked: red
- Bypassed: yellow

## Implementation Checklist

### Core Functionality
- [x] Todo list detection (multiple formats)
- [x] Sequential step tracking
- [x] State machine implementation
- [x] Tool call verification
- [x] User confirmation flow
- [x] Bypass support

### Configuration
- [x] Enable/disable enforcement
- [x] Tool call requirement
- [x] Confirmation timeout
- [x] Bypass keywords
- [x] Auto-start option
- [x] Status display

### Error Handling
- [x] Step failure tracking
- [x] Timeout handling
- [x] Bypass flow
- [x] State recovery

## Error Handling

### Common Errors

| Error | Cause | Resolution |
|-------|-------|------------|
| No tool calls detected | Tool call requirement enabled but no calls | Disable `require_tool_calls` or ensure LLM uses tools |
| Confirmation timeout | User didn't confirm within timeout | Workflow blocked, user can resume |
| Step execution failed | Command/tool failed | Check failure reason, retry or bypass |
| Invalid state | State machine inconsistency | Reset workflow, restart enforcement |

### Recovery Strategies

- **Retry step**: User can request retry of failed step
- **Bypass step**: Skip current step and continue
- **Resume workflow**: Return to ENFORCING state
- **Reset workflow**: Start over from step 0

## Usage Examples

### Basic Workflow

**User:**
```
Set up a new PostgreSQL database with user authentication
```

**LLM response:**
```
I'll set up PostgreSQL with authentication. Here's the plan:

todo:
  [ ] Step 1: Install PostgreSQL
  [ ] Step 2: Create database and user
  [ ] Step 3: Set up authentication
  [ ] Step 4: Test connection

Let me start with installation...
```

**Plugin enforcement:**
1. Detects 4 todo items
2. Prompts user to enforce workflow
3. User confirms
4. LLM executes Step 1 with tool calls
5. Plugin verifies tool call
6. User confirms Step 1 completion
7. Repeat for Steps 2-4
8. Workflow completed

### Bypass Workflow

**User:**
```
Actually, let's bypass this workflow and just use SQLite instead
```

**Plugin:**
- Detects "bypass" keyword
- Prompts for bypass confirmation
- Transitions to BLOCKED state
- Emits `workflow_bypassed` event

### Resume Blocked Workflow

**User:**
```
Continue with the PostgreSQL workflow from where we left off
```

**Plugin:**
- Returns to ENFORCING state
- Resumes at current step
- Continues verification

## Best Practices

### When to Enable

Enable workflow enforcement when:
- Working with complex, multi-step tasks
- LLM tends to forget steps
- You want tool call verification
- Sequential execution is critical

### When to Disable

Disable when:
- Quick one-off tasks
- Tasks with variable/unknown steps
- LLM reliably completes all steps
- Flexibility is more important than enforcement

### Configuration Tips

- **require_tool_calls**: True for reliability, False for flexibility
- **confirmation_timeout**: Longer for complex steps (600s), shorter for quick tasks (60s)
- **bypass_keywords**: Customize based on your workflow vocabulary
- **show_progress_in_status**: True for transparency, False for cleaner UI

## Related Documentation

- /docs/reference/hook-system-sdk.md - Hook system
- /docs/reference/tool-calling.md - Tool call verification
- /docs/features/workflows.md - Workflow management

## Advanced Features

### Custom Verification Rules

Future enhancement: define custom verification criteria per step type.

### Workflow Templates

Future enhancement: save and reuse workflow templates.

### Conditional Steps

Future enhancement: steps that execute only based on previous step results.

## Troubleshooting

### Workflow Not Starting

1. Check if plugin is enabled
2. Verify todo format matches supported patterns
3. Check `auto_start_workflows` setting
4. Review logs for detection errors

### Steps Not Verifying

1. Check `require_tool_calls` setting
2. Ensure LLM is using tool calls
3. Verify tool call events are firing
4. Check event bus integration

### Workflow Stuck

1. Check if waiting for user confirmation
2. Verify confirmation timeout hasn't expired
3. Check if workflow is in BLOCKED state
4. Review failure reasons in todo items
