# Executor HTTP API with Debugging Support

This module provides HTTP API endpoints for executing Haibun features remotely via REST calls, with full support for **persistent execution contexts**, **step-by-step debugging**, and **breakpoint management**.

## Overview

The `ExecutorApiStepper` extends the existing web server infrastructure to expose key methods from `Executor.ts` via HTTP endpoints. This allows you to:

1. **Execute features remotely** - Send feature content as JSON and get execution results
2. **Validate features** - Check feature syntax and step resolution without execution
3. **Debug features interactively** - Set breakpoints, step through execution, inspect state
4. **Maintain execution contexts** - Keep stepper state around for development and debugging
5. **Integrate with prompters** - Use HTTP-based prompting for interactive debugging

## Key Features

### 🔧 Persistent Execution Contexts
- Execution contexts are kept alive between API calls
- Each context maintains its own stepper instances and world state
- Automatic cleanup after configurable timeout (default: 60 minutes)
- Context reuse for iterative development

### 🐛 Interactive Debugging
- Set breakpoints on specific step actions or stepper names
- Step-by-step execution with pause/continue controls
- Real-time step history and current execution state
- HTTP-based prompter integration for web debugging UIs

### 🔍 Monitoring & Inspection
- View active execution contexts and their status
- Inspect step history and execution timeline
- Monitor breakpoints and pending prompts
- Track context activity and lifecycle

## Setup

1. Include both `WebServerStepper` and `ExecutorApiStepper` in your steppers configuration
2. Use the step `setup executor API at {path}` to configure the API endpoints
3. Start the web server with your usual Haibun process

## API Endpoints

### POST /api/executor/features
Execute one or more features and return results. Now supports execution contexts and debugging.

**Request Body:**
```json
{
  "features": [
    {
      "path": "/optional/path.feature",
      "content": "Feature step 1\nFeature step 2"
    }
  ],
  "steppers": ["@haibun/web-http", "@haibun/core"],
  "options": {
    "LOG_LEVEL": "debug"
  },
  "contextId": "existing-context-id",  // Optional: reuse context
  "debug": true                        // Optional: enable debugging
}
```

**Response:**
```json
{
  "success": true,
  "contextId": "ctx-1640995200000-abc123",  // Context ID for future calls
  "result": {
    "ok": true,
    "featureResults": [
      {
        "path": "/optional/path.feature",
        "ok": true,
        "stepCount": 2,
        "failedSteps": 0
      }
    ],
    "summary": {
      "totalFeatures": 1,
      "passedFeatures": 1,
      "failedFeatures": 0
    }
  }
}
```

### GET /api/executor/contexts
List all active execution contexts.

**Response:**
```json
{
  "contexts": [
    {
      "id": "ctx-1640995200000-abc123",
      "isRunning": false,
      "isPaused": false,
      "createdAt": 1640995200000,
      "lastActivity": 1640995300000,
      "stepCount": 15,
      "breakpointCount": 2
    }
  ]
}
```

### GET /api/executor/contexts/:id
Get detailed information about a specific execution context.

**Response:**
```json
{
  "id": "ctx-1640995200000-abc123",
  "isRunning": false,
  "isPaused": false,
  "currentStep": {
    "featureStep": { "in": "click button", "path": "/test.feature" },
    "action": { "actionName": "click", "stepperName": "WebPlaywright" },
    "timestamp": 1640995250000
  },
  "stepHistory": [
    // Last 20 steps
  ],
  "breakpoints": ["WebPlaywright.click", "debug.*"],
  "pendingPrompts": [
    {
      "id": "prompt-123",
      "message": "Continue execution?",
      "options": ["continue", "step", "abort"]
    }
  ],
  "createdAt": 1640995200000,
  "lastActivity": 1640995300000
}
```

### POST /api/executor/contexts/:id/breakpoints
Add or remove breakpoints for a context.

**Request Body:**
```json
{
  "operation": "add",           // "add" or "remove"
  "action": "click",           // Step action name
  "stepperName": "WebPlaywright" // Optional: specific stepper
}
```

**Response:**
```json
{
  "breakpoints": ["WebPlaywright.click", "debug.*"]
}
```

### POST /api/executor/contexts/:id/prompts/:promptId
Respond to a pending prompt in a context.

**Request Body:**
```json
{
  "response": "continue"  // Response to the prompt
}
```

**Response:**
```json
{
  "success": true
}
```

### DELETE /api/executor/contexts/:id
Clean up and remove an execution context.

**Response:**
```json
{
  "success": true
}
```

### POST /api/executor/validate
Validate feature syntax and step resolution without execution.

**Request Body:**
```json
{
  "features": [
    {
      "path": "/test.feature",
      "content": "Feature step 1\nFeature step 2"
    }
  ],
  "steppers": ["@haibun/web-http"]
}
```

**Response:**
```json
{
  "success": true,
  "validation": {
    "featuresCount": 1,
    "totalSteps": 2,
    "features": [
      {
        "path": "/test.feature",
        "stepCount": 2,
        "valid": true
      }
    ]
  }
}
```

### GET /api/executor/status
Health check endpoint with context information.

**Response:**
```json
{
  "status": "ready",
  "timestamp": "2025-06-26T10:30:00.000Z",
  "version": "1.0.0",
  "activeContexts": 3,
  "runningContexts": 1
}
```

## Usage Examples

### Basic Execution
```gherkin
# In your feature file:
Given webserver is listening
When setup executor API at /api/executor
Then webserver is listening
```

### Development Workflow with Debugging
```bash
# 1. Start execution with debugging enabled
curl -X POST http://localhost:8123/api/executor/features \
  -H "Content-Type: application/json" \
  -d '{
    "features": [{"content": "click button\nverify result"}],
    "steppers": ["@haibun/web-playwright"],
    "debug": true
  }'
# Returns: {"contextId": "ctx-123", "result": {...}}

# 2. Set breakpoints for debugging
curl -X POST http://localhost:8123/api/executor/contexts/ctx-123/breakpoints \
  -H "Content-Type: application/json" \
  -d '{
    "operation": "add",
    "action": "click",
    "stepperName": "WebPlaywright"
  }'

# 3. Execute with context reuse (will hit breakpoint)
curl -X POST http://localhost:8123/api/executor/features \
  -H "Content-Type: application/json" \
  -d '{
    "features": [{"content": "click submit button"}],
    "contextId": "ctx-123"
  }'

# 4. Check context status and pending prompts
curl http://localhost:8123/api/executor/contexts/ctx-123

# 5. Respond to prompt to continue execution
curl -X POST http://localhost:8123/api/executor/contexts/ctx-123/prompts/prompt-456 \
  -H "Content-Type: application/json" \
  -d '{"response": "continue"}'

# 6. Clean up when done
curl -X DELETE http://localhost:8123/api/executor/contexts/ctx-123
```

### Integration with Web UI
```html
<!-- Example debugging UI integration -->
<script>
async function executeWithDebugging() {
  // Start execution with debugging
  const response = await fetch('/api/executor/features', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      features: [{content: document.getElementById('feature').value}],
      debug: true
    })
  });

  const {contextId} = await response.json();

  // Poll for prompts and handle interactively
  const checkPrompts = async () => {
    const context = await fetch(`/api/executor/contexts/${contextId}`).then(r => r.json());

    if (context.pendingPrompts.length > 0) {
      const prompt = context.pendingPrompts[0];
      const userResponse = confirm(prompt.message) ? 'continue' : 'abort';

      await fetch(`/api/executor/contexts/${contextId}/prompts/${prompt.id}`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({response: userResponse})
      });
    }

    if (context.isRunning) {
      setTimeout(checkPrompts, 1000);  // Continue polling
    }
  };

  checkPrompts();
}
</script>
```

## Benefits

- **Remote Execution**: Execute Haibun features from other applications or services
- **Persistent Contexts**: Keep stepper state alive between API calls for iterative development
- **Interactive Debugging**: Set breakpoints, step through execution, and inspect state in real-time
- **Web-based Debugging**: HTTP prompter integration enables web-based debugging UIs
- **Context Management**: Automatic cleanup and lifecycle management of execution contexts
- **Development Workflow**: Perfect for feature development, testing, and debugging
- **CI/CD Integration**: Easily integrate with build pipelines and external tools
- **Validation**: Check feature syntax before execution
- **Monitoring**: Status endpoint and context inspection for health checks
- **Stepper Lifecycle Integration**: Full integration with stepper cycles and TWorld.prompter subscribers

## Advanced Features

### Stepper Lifecycle Integration
The API integrates with Haibun's stepper lifecycle system:
- **beforeStep**: Tracks step execution and handles breakpoints
- **afterStep**: Records step results and timing
- **onFailure**: Pauses execution on failures for debugging

### TWorld.prompter Integration
Uses Haibun's prompter subscriber system:
- **HttpPrompter**: Custom prompter for HTTP-based interactions
- **Subscriber Management**: Automatic subscription/unsubscription
- **Multiple Prompters**: Works alongside existing prompters (ReadlinePrompter, ButtonPrompter)

### Context Lifecycle
- **Automatic Creation**: Contexts created on first execution request
- **Reuse**: Same context can be reused across multiple executions
- **Timeout Management**: Automatic cleanup after inactivity
- **Resource Management**: Proper cleanup of steppers and world state

## Error Handling

All endpoints return appropriate HTTP status codes:
- `200` - Success
- `400` - Bad Request (invalid input)
- `500` - Internal Server Error (execution failure)

Error responses include descriptive messages to help with debugging.
