# Error Handling Guide

Comprehensive guide to Bangstack's error handling, recovery strategies, and troubleshooting.

## Table of Contents

- [Overview](#overview)
- [Error Classification](#error-classification)
- [Error Codes Reference](#error-codes-reference)
- [Recovery Strategies](#recovery-strategies)
- [Checkpoint and Rollback System](#checkpoint-and-rollback-system)
- [Retry Logic](#retry-logic)
- [Common Error Scenarios](#common-error-scenarios)
- [Troubleshooting Guide](#troubleshooting-guide)
- [Best Practices](#best-practices)

## Overview

Bangstack provides production-ready error handling with:

- **Enhanced Error Messages**: Clear, actionable error messages with recovery suggestions
- **Automatic Rollback**: Generation failures automatically rollback to last checkpoint
- **Intelligent Retry**: Automatic retry for transient failures with exponential backoff
- **Circuit Breakers**: Prevent cascading failures in service connections
- **Progress Tracking**: Resume from checkpoints after failures

## Error Classification

### Error Severity Levels

Bangstack classifies errors into four severity levels:

#### FATAL
**Cannot continue execution**

```
❌ FATAL: Invalid workflow structure: missing required field "stack"

   Code: INVALID_WORKFLOW_STRUCTURE

   💡 How to fix:
   1. Add the required field to your workflow YAML
      • Open your workflow file
      • Add the "stack" field
      • Ensure proper YAML formatting
      • Run bang verify to check
```

- Workflow structure issues
- Critical validation failures
- Missing required configuration

#### ERROR
**Can potentially recover**

```
🔴 ERROR: Component "api" depends on "redis" which doesn't exist

   Code: INVALID_DEPENDENCY_REFERENCE

   💡 How to fix:
   1. Add the missing component
   2. Remove the invalid dependency
```

- Invalid dependency references
- File operation failures
- Service connection issues
- Generation failures

#### WARNING
**Can continue with caution**

```
⚠️  WARNING: Repository has uncommitted changes

   Code: UNCOMMITTED_CHANGES
   Details: 3 file(s) with uncommitted changes

   💡 How to fix:
   1. Commit your changes
   2. Stash your changes
   3. Force the operation (not recommended)
```

- Uncommitted changes
- Manifest mismatches
- Partial generation
- Missing optional dependencies

#### INFO
**Informational only**

```
ℹ️  INFO: Using cached dependency resolution

   Code: CACHE_HIT
```

- Cache hits
- Optional optimizations
- Informational messages

### Failure Types

Bangstack automatically classifies failures for retry logic:

#### TRANSIENT
**Temporary failures, retry likely to succeed**

Examples:
- Network timeouts (ETIMEDOUT, ECONNREFUSED)
- Service unavailable (503, 502, 504)
- Rate limiting (429)
- Database deadlocks
- File system busy (EBUSY, EAGAIN)
- Temporary DNS failures (EAI_AGAIN)

**Retry Strategy**: Exponential backoff with jitter

#### PERMANENT
**Persistent failures, retry won't help**

Examples:
- Authentication failures (401, 403)
- Not found (404)
- Validation errors (400)
- Syntax errors
- Already exists conflicts (409)
- Permission denied

**Retry Strategy**: Fail immediately, don't retry

#### UNKNOWN
**Cannot classify, try limited retries**

Examples:
- Generic errors
- Unknown error codes
- Custom exceptions

**Retry Strategy**: Limited retries (3 attempts)

## Error Codes Reference

### Validation Errors

#### INVALID_WORKFLOW_STRUCTURE
**Workflow YAML structure is invalid**

```yaml
# ❌ Missing required field
workflow:
  id: my-app
  # Missing: version

# ✅ Correct
workflow:
  id: my-app
  version: 1.0.0
```

**Recovery**:
1. Check workflow schema
2. Add missing required fields
3. Run `bang verify` to validate

#### MISSING_REQUIRED_FIELD
**Required field is missing from configuration**

```yaml
# ❌ Missing port
stack:
  api:
    type: backend
    technology: typescript/express
    # Missing: port

# ✅ Correct
stack:
  api:
    type: backend
    technology: typescript/express
    port: 3000
```

**Recovery**:
1. Identify missing field from error message
2. Add field with appropriate value
3. Verify configuration

#### INVALID_COMPONENT_TYPE
**Component type is not supported**

```yaml
# ❌ Invalid type
stack:
  api:
    type: microservice  # Not a valid type

# ✅ Correct
stack:
  api:
    type: backend  # Valid types: frontend, backend
```

**Recovery**:
1. Check supported component types
2. Use: `frontend`, `backend`, or custom types
3. Update workflow configuration

#### INVALID_DEPENDENCY_REFERENCE
**Component depends on non-existent component**

```yaml
# ❌ Redis not defined
stack:
  api:
    expected_dependencies:
      - service: redis  # Doesn't exist in workflow

# ✅ Define the service
stages:
  local:
    infrastructure:
      services:
        redis:
          provider: local
```

**Recovery**:
1. Add missing service to infrastructure
2. Or remove invalid dependency
3. Verify all dependencies exist

#### CIRCULAR_DEPENDENCY
**Components have circular dependency**

```yaml
# ❌ Circular dependency
stack:
  api:
    dependsOn: [worker]
  worker:
    dependsOn: [api]  # Circular!

# ✅ Remove circular dependency
stack:
  api:
    dependsOn: []
  worker:
    dependsOn: [api]
```

**Recovery**:
1. Identify dependency cycle
2. Restructure dependencies
3. Use event-driven patterns instead

### File System Errors

#### FILE_NOT_FOUND
**File does not exist at expected location**

```bash
# Error when workflow file doesn't exist
bang generate missing.workflow.yaml

# ❌ ERROR: File not found: missing.workflow.yaml
```

**Recovery**:
1. Check file path spelling
2. Use absolute or relative paths correctly
3. Create missing file if needed

#### FILE_WRITE_ERROR
**Cannot write file to disk**

```bash
# Error when directory is read-only
bang generate workflow.yaml

# ❌ ERROR: Cannot write file: /output/src/index.ts
#    Details: EACCES: permission denied
```

**Recovery**:
1. Check file permissions: `ls -la /output`
2. Ensure write access: `chmod +w /output`
3. Check disk space: `df -h`
4. Verify directory exists

#### PERMISSION_DENIED
**Insufficient permissions to perform operation**

```bash
# Error when trying to write to protected directory
bang generate workflow.yaml -o /usr/local/app

# ❌ ERROR: Permission denied
```

**Recovery**:
1. Use sudo if appropriate: `sudo bang generate`
2. Choose different output directory
3. Fix permissions: `chown -R $USER /output`

#### DIRECTORY_NOT_EMPTY
**Target directory contains existing files**

```bash
# Error when generating into non-empty directory
bang generate workflow.yaml -o ./existing-project

# ⚠️  WARNING: Directory not empty
#    Found 15 files in /existing-project
```

**Recovery**:
1. Use `--force` to overwrite: `bang generate -f`
2. Choose different directory
3. Backup and remove existing files
4. Use `--merge` to merge with existing code

### Generation Errors

#### GENERATOR_FAILED
**Code generation failed for component**

```bash
# Error during component generation
Generating api component...

# 🔴 ERROR: Generator failed for component "api"
#    Details: Template render error at line 45
```

**Recovery**:
1. Check generator logs in `.bangstack/logs/`
2. Verify workflow configuration
3. Report bug if generator issue
4. Use `--skip api` to skip failed component

#### TEMPLATE_ERROR
**Template rendering failed**

```bash
# Error in template syntax
# 🔴 ERROR: Template error in backend/express
#    Details: Undefined variable 'component.port'
```

**Recovery**:
1. Check template syntax
2. Verify all required variables are provided
3. Update generator templates
4. Report template bug

#### PARTIAL_GENERATION
**Some components succeeded, others failed**

```bash
# Partial generation result
# ⚠️  WARNING: Generation partially completed
#    ✓ Succeeded: api, worker
#    ✗ Failed: frontend (Template error)
```

**Recovery**:
1. **Automated**: Run `bang generate --retry`
   - Skips successful components
   - Retries only failed ones

2. **Manual**: Fix errors and regenerate
   ```bash
   # Fix workflow issue
   vim workflow.yaml

   # Regenerate all
   bang generate workflow.yaml
   ```

### Infrastructure Errors

#### SERVICE_CONNECTION_FAILED
**Cannot connect to service**

```bash
# Error connecting to Redis
# 🔴 ERROR: Failed to connect to redis (local)
#    Details: ECONNREFUSED 127.0.0.1:6379
```

**Recovery**:
1. **Check service is running**
   ```bash
   docker-compose ps
   docker-compose logs redis
   ```

2. **Start service if stopped**
   ```bash
   docker-compose up -d redis
   ```

3. **Verify connection credentials**
   ```bash
   # Check environment variables
   echo $REDIS_URL

   # Test connection manually
   redis-cli ping
   ```

4. **Check network connectivity**
   ```bash
   # Test port connectivity
   nc -zv localhost 6379

   # Check firewall rules
   sudo ufw status
   ```

#### DATABASE_ERROR
**Database operation failed**

```bash
# Error during migration
# 🔴 ERROR: Database operation failed
#    Details: relation "users" already exists
```

**Recovery**:
1. Check database state
2. Run migrations: `npm run migrate`
3. Reset database if needed: `npm run db:reset`
4. Verify connection string

#### NETWORK_ERROR
**Network request failed**

```bash
# Error fetching remote resource
# 🔴 ERROR: Network error
#    Details: getaddrinfo ENOTFOUND api.example.com
```

**Recovery**:
1. Check internet connectivity
2. Verify DNS resolution: `nslookup api.example.com`
3. Check proxy settings
4. Try again (may be transient)

### Git Errors

#### NOT_A_GIT_REPO
**Operation requires Git repository**

```bash
# Error when using version management outside Git repo
bang version create 1.0.0

# 🔴 ERROR: Not a git repository
```

**Recovery**:
1. Initialize Git repo: `git init`
2. Add remote: `git remote add origin <url>`
3. Make initial commit: `git commit -m "Initial commit"`

#### UNCOMMITTED_CHANGES
**Repository has uncommitted changes**

```bash
# Warning when creating version with dirty working tree
bang version create 1.0.0

# ⚠️  WARNING: Repository has uncommitted changes
#    3 file(s) with uncommitted changes
```

**Recovery**:
1. **Commit changes**
   ```bash
   git add .
   git commit -m "Your message"
   bang version create 1.0.0
   ```

2. **Stash changes**
   ```bash
   git stash
   bang version create 1.0.0
   git stash pop
   ```

3. **Force operation** (not recommended)
   ```bash
   bang version create 1.0.0 --force
   ```

#### GIT_OPERATION_FAILED
**Git command failed**

```bash
# Error during Git operation
# 🔴 ERROR: Git operation failed
#    Details: fatal: tag '1.0.0' already exists
```

**Recovery**:
1. Check Git status: `git status`
2. Check Git logs: `git log`
3. Resolve conflicts if any
4. Use different operation

### Version Management Errors

#### VERSION_ALREADY_EXISTS
**Version tag already exists**

```bash
# Error when creating duplicate version
bang version create 1.0.0

# 🔴 ERROR: Version 1.0.0 already exists
#    Existing version: 1.0.0
#    Commit: abc123
#    Date: 2024-01-15
```

**Recovery**:
1. **Use different version**
   ```bash
   bang version list
   bang version create 1.1.0
   ```

2. **Delete existing tag** (dangerous)
   ```bash
   git tag -d 1.0.0
   git push origin :refs/tags/1.0.0
   bang version create 1.0.0
   ```

#### VERSION_NOT_FOUND
**Version does not exist**

```bash
# Error when referencing non-existent version
bang version diff 1.0.0 2.0.0

# 🔴 ERROR: Version 2.0.0 not found
```

**Recovery**:
1. List available versions: `bang version list`
2. Use correct version number
3. Create missing version if needed

#### INVALID_SEMVER
**Version does not follow semantic versioning**

```bash
# Error with invalid version format
bang version create v1.0

# 🔴 ERROR: Invalid semantic version: v1.0
#    Expected format: MAJOR.MINOR.PATCH (e.g., 1.0.0)
```

**Recovery**:
1. Use semantic versioning: `1.0.0`
2. Format: `MAJOR.MINOR.PATCH`
3. Don't use `v` prefix (it's added automatically)

#### MANIFEST_MISMATCH
**Dependency mismatch between workflow and code**

```bash
# Warning when code doesn't match workflow
bang verify workflow.yaml

# ⚠️  WARNING: Dependency mismatch
#    Missing: redis (declared in workflow but not in code)
#    Unexpected: mongodb (found in code but not in workflow)
```

**Recovery**:
1. **Update workflow to match code**
   ```yaml
   # Add missing service
   expected_dependencies:
     - service: mongodb
   ```

2. **Regenerate code to match workflow**
   ```bash
   bang generate workflow.yaml
   ```

3. **Run verification for details**
   ```bash
   bang verify workflow.yaml --detailed
   ```

## Recovery Strategies

### Automated Recovery

Some errors can be recovered automatically:

#### Retry Failed Components

```bash
# After partial generation failure
bang generate workflow.yaml --retry
```

**What it does**:
- Detects which components failed
- Skips already-generated components
- Retries only failed components
- Uses checkpoints for resume point

#### Regenerate Code to Match Workflow

```bash
# After manifest mismatch
bang generate workflow.yaml --force
```

**What it does**:
- Overwrites existing code
- Adds missing service clients
- Removes unused dependencies
- Updates configuration

#### Automatic Retry for Transient Failures

Bangstack automatically retries transient failures:

```typescript
// Network operations automatically retry
// 🔄 Retrying API call (attempt 1): ETIMEDOUT
// 🔄 Retrying API call (attempt 2): ECONNREFUSED
// ✓ Success on attempt 3
```

**Automatic retry for**:
- Network timeouts
- Service unavailable (503)
- Rate limiting (429)
- Database deadlocks
- File system busy

### Manual Recovery

Some errors require manual intervention:

#### Fix Workflow Configuration

```bash
# 1. Identify error
bang generate workflow.yaml
# ERROR: Invalid dependency reference

# 2. Edit workflow
vim workflow.yaml

# 3. Verify fix
bang verify workflow.yaml

# 4. Regenerate
bang generate workflow.yaml
```

#### Rollback to Previous Version

```bash
# 1. List versions
bang version list

# 2. Compare versions
bang version diff 1.0.0 2.0.0

# 3. Rollback
bang version rollback 1.0.0

# 4. Verify
bang verify workflow.yaml
```

#### Clean and Regenerate

```bash
# 1. Remove generated code
rm -rf src/ docker-compose.yml .github/

# 2. Clear checkpoint
rm -rf .bangstack/checkpoints/

# 3. Regenerate from scratch
bang generate workflow.yaml
```

#### Fix Service Connections

```bash
# 1. Check service status
docker-compose ps

# 2. View logs
docker-compose logs redis

# 3. Restart service
docker-compose restart redis

# 4. Test connection
redis-cli ping

# 5. Retry operation
bang generate workflow.yaml
```

## Checkpoint and Rollback System

### How Checkpoints Work

Bangstack creates checkpoints at each generation stage:

```
Generation Process:
├── VALIDATION ────────── Checkpoint 1
├── ANALYSIS ──────────── Checkpoint 2
├── INFRASTRUCTURE ────── Checkpoint 3
│   ├── Create docker-compose.yml
│   ├── Create .env files
│   └── Create database configs
├── COMPONENT_GENERATION ─ Checkpoint 4
│   ├── Generate api/ (Checkpoint 4a)
│   ├── Generate worker/ (Checkpoint 4b)
│   └── Generate frontend/ (Checkpoint 4c)
├── CONFIGURATION ─────── Checkpoint 5
│   ├── Create CI/CD configs
│   └── Create deployment configs
├── FINALIZATION ──────── Checkpoint 6
│   └── Create manifest
└── COMPLETE ──────────── Checkpoint 7
```

### Checkpoint Storage

Checkpoints are stored in `.bangstack/checkpoints/`:

```
.bangstack/
└── checkpoints/
    ├── cp_1234567890_a1b2c3d4.json
    ├── cp_1234567891_e5f6g7h8.json
    └── backups/
        ├── package.json.1234567890.backup
        └── docker-compose.yml.1234567891.backup
```

### Using Checkpoints

#### Check Current Progress

```bash
# View generation progress
bangstack status

# Output:
# 📊 Generation Progress:
#    Stage: component_generation
#    Progress: 57%
#    Current: api
#
#    Checkpoints:
#      ✓ validation
#      ✓ analysis
#      ✓ infrastructure
#      ○ component_generation (api)
#      ○ configuration
#      ○ finalization
#
#    💡 Can resume from last checkpoint
#       Run: bang generate workflow.yaml --resume
```

#### Resume from Checkpoint

```bash
# After failure, resume from last checkpoint
bang generate workflow.yaml --resume

# Output:
# 📊 Resuming from checkpoint: component_generation (api)
# ⏭️  Skipping completed stages: validation, analysis, infrastructure
# 🔄 Continuing with: api generation
```

#### Manual Rollback

```bash
# Rollback to last successful checkpoint
bangstack rollback

# Output:
# 🔄 Rolling back to checkpoint: infrastructure
#    ✓ Removed 15 created files
#    ✓ Restored 3 modified files
#    ✓ Removed 5 empty directories
```

#### Rollback to Specific Checkpoint

```bash
# List checkpoints
bangstack checkpoints list

# Output:
# Checkpoints:
#   1. cp_abc123 - validation (2024-01-15 10:00:00)
#   2. cp_def456 - analysis (2024-01-15 10:01:30)
#   3. cp_ghi789 - infrastructure (2024-01-15 10:03:15)

# Rollback to specific checkpoint
bangstack rollback cp_def456

# Output:
# 🔄 Rolling back to checkpoint: analysis
#    ✓ Removed all changes after this point
```

### What Gets Tracked

#### Files Created
```typescript
// Checkpoint tracks all new files
filesCreated: [
  '/output/src/index.ts',
  '/output/src/routes/users.ts',
  '/output/docker-compose.yml',
]
```

#### Files Modified
```typescript
// Checkpoint creates backup before modification
filesModified: [
  {
    path: '/output/package.json',
    backup: '.bangstack/checkpoints/backups/package.json.123.backup'
  },
]
```

#### Directories Created
```typescript
// Checkpoint tracks new directories
directoriesCreated: [
  '/output/src',
  '/output/src/routes',
  '/output/src/services',
]
```

### Rollback Behavior

#### What Rollback Does

1. **Removes Created Files**
   ```bash
   # Files created after checkpoint are deleted
   rm /output/src/new-feature.ts
   ```

2. **Restores Modified Files**
   ```bash
   # Files modified after checkpoint are restored
   cp .bangstack/checkpoints/backups/package.json.backup package.json
   ```

3. **Removes Empty Directories**
   ```bash
   # Only removes directories that are empty
   rmdir /output/src/new-feature/
   ```

4. **Removes Checkpoint Files**
   ```bash
   # Deletes checkpoint files after rollback point
   rm .bangstack/checkpoints/cp_*.json
   ```

#### What Rollback Preserves

- User-created files (not tracked by checkpoints)
- Non-empty directories
- Files in `.gitignore`
- External dependencies

### Checkpoint Cleanup

```bash
# After successful generation, cleanup old checkpoints
bang generate workflow.yaml --cleanup

# Keeps only COMPLETE checkpoint
# Removes intermediate checkpoints
# Removes backup files
```

## Retry Logic

### Retry Strategies

#### Exponential Backoff (Default)

```
Attempt 1: Immediate
Attempt 2: Wait 1s
Attempt 3: Wait 2s
Attempt 4: Wait 4s
Attempt 5: Wait 8s
```

**Used for**:
- Network operations
- Service connections
- API calls

**Configuration**:
```typescript
{
  maxAttempts: 5,
  strategy: RetryStrategy.EXPONENTIAL_BACKOFF,
  initialDelay: 1000,      // 1 second
  maxDelay: 30000,         // 30 seconds
  backoffMultiplier: 2,    // Double each time
}
```

#### Linear Backoff

```
Attempt 1: Immediate
Attempt 2: Wait 1s
Attempt 3: Wait 2s
Attempt 4: Wait 3s
Attempt 5: Wait 4s
```

**Used for**:
- Database operations
- File operations
- Predictable delays

**Configuration**:
```typescript
{
  maxAttempts: 3,
  strategy: RetryStrategy.LINEAR_BACKOFF,
  initialDelay: 1000,      // 1 second
}
```

#### Immediate Retry

```
Attempt 1: Immediate
Attempt 2: Immediate
Attempt 3: Immediate
```

**Used for**:
- Quick operations
- Optimistic retries
- Testing

**Configuration**:
```typescript
{
  maxAttempts: 3,
  strategy: RetryStrategy.IMMEDIATE,
}
```

### Failure Classification

Bangstack automatically classifies errors:

#### Transient Patterns

```typescript
// Network errors
ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENETUNREACH, EAI_AGAIN

// File system errors
EBUSY, EAGAIN, EMFILE, ENFILE

// HTTP errors
503 Service Unavailable
429 Too Many Requests
502 Bad Gateway
504 Gateway Timeout

// Database errors
connection refused, connection reset, deadlock, lock timeout

// Generic
temporary failure, try again
```

#### Permanent Patterns

```typescript
// Authentication
401 Unauthorized
403 Forbidden

// Not found
404 Not Found
does not exist

// Validation
400 Bad Request
invalid, malformed, syntax error

// Conflicts
409 Conflict
already exists
```

### Circuit Breaker

Prevents cascading failures:

```
States:
┌─────────┐
│ CLOSED  │ ──[5 failures]──> ┌──────┐
└─────────┘                    │ OPEN │
     ↑                         └──────┘
     │                            │
     │                            │ [60s timeout]
     │                            ↓
     │                      ┌───────────┐
     └──[success]───────────│ HALF-OPEN │
                            └───────────┘
```

**Behavior**:
- **CLOSED**: Normal operation, requests pass through
- **OPEN**: Too many failures, reject all requests
- **HALF-OPEN**: Testing recovery, allow one request

**Configuration**:
```typescript
const breaker = new CircuitBreaker(
  'api-service',
  5,      // Open after 5 failures
  60000   // Reset after 60 seconds
);

await breaker.execute(() => callAPI());
```

### Retry Examples

#### Network Operation

```typescript
import { RetryHelpers } from './utils/retry-manager';

// Automatically retries with exponential backoff
const data = await RetryHelpers.retryNetworkOperation(
  () => fetch('https://api.example.com/users'),
  'fetch user data'
);

// Output on failure:
// 🔄 Retrying fetch user data (attempt 1): ETIMEDOUT
// 🔄 Retrying fetch user data (attempt 2): ECONNREFUSED
// ✓ Success on attempt 3
```

#### File Operation

```typescript
import { RetryHelpers } from './utils/retry-manager';

// Retries with shorter delays for file operations
await RetryHelpers.retryFileOperation(
  () => fs.writeFile('output.json', data),
  'write output file'
);

// Output on failure:
// 🔄 Retrying write output file (attempt 1): EBUSY
// ✓ Success on attempt 2
```

#### Database Operation

```typescript
import { RetryHelpers } from './utils/retry-manager';

// Retries but skips syntax errors
const users = await RetryHelpers.retryDatabaseOperation(
  () => User.findAll(),
  'fetch users'
);

// Output:
// 🔄 Retrying fetch users (attempt 1): connection refused
// ✓ Success on attempt 2
```

#### Custom Retry Logic

```typescript
import { RetryManager, RetryStrategy } from './utils/retry-manager';

const result = await RetryManager.execute(
  async () => await performOperation(),
  {
    maxAttempts: 5,
    strategy: RetryStrategy.EXPONENTIAL_BACKOFF,
    initialDelay: 2000,
    maxDelay: 60000,
    timeout: 10000,  // 10s timeout per attempt

    onRetry: (attempt, error) => {
      console.log(`Retry ${attempt}: ${error.message}`);
      // Log to monitoring system
      reportToSentry(error);
    },

    shouldRetry: (error) => {
      // Don't retry authentication errors
      return !error.message.includes('401') &&
             !error.message.includes('403');
    }
  }
);

if (!result.success) {
  console.error(`Failed after ${result.attempts} attempts`);
  console.error(`Total time: ${result.totalTime}ms`);
  console.error(`Failure type: ${result.failureType}`);
}
```

## Common Error Scenarios

### Scenario 1: Generation Fails Midway

**Problem**: Generation fails while creating components

```bash
bang generate workflow.yaml

# Output:
# ✓ Validation complete
# ✓ Analysis complete
# ✓ Infrastructure generated
# 🔄 Generating api... ✓
# 🔄 Generating worker... ✗ ERROR: Template error
```

**Solution**:

```bash
# 1. Check what was generated
ls -la

# 2. View error details
cat .bangstack/logs/generation.log

# 3. Fix workflow issue
vim workflow.yaml

# 4. Resume from last checkpoint
bang generate workflow.yaml --resume

# 5. Or rollback and start fresh
bangstack rollback
bang generate workflow.yaml
```

### Scenario 2: Service Won't Connect

**Problem**: Generated code can't connect to service

```bash
npm run dev

# Output:
# 🔴 ERROR: Failed to connect to redis
#    ECONNREFUSED 127.0.0.1:6379
```

**Solution**:

```bash
# 1. Check if service is running
docker-compose ps

# 2. Start service if stopped
docker-compose up -d redis

# 3. Check logs for errors
docker-compose logs redis

# 4. Test connection
redis-cli ping

# 5. Verify environment variables
cat .env | grep REDIS

# 6. Restart application
npm run dev
```

### Scenario 3: Manifest Mismatch

**Problem**: Code doesn't match workflow

```bash
bang verify workflow.yaml

# Output:
# ⚠️  WARNING: Dependency mismatch
#    Missing: redis (in workflow, not in code)
#    Unexpected: mongodb (in code, not in workflow)
```

**Solution**:

**Option 1: Update workflow to match code**
```yaml
# Add mongodb to workflow
expected_dependencies:
  - service: mongodb
    usage: User data storage
```

**Option 2: Regenerate code to match workflow**
```bash
# Remove mongodb from workflow
# Then regenerate
bang generate workflow.yaml --force
```

**Option 3: Manual sync**
```bash
# Add missing service client
npm install redis ioredis

# Remove unused service client
npm uninstall mongodb
rm src/services/mongodb-client.ts
```

### Scenario 4: Version Conflicts

**Problem**: Cannot create version due to conflicts

```bash
bang version create 1.0.0

# Output:
# ⚠️  WARNING: Repository has uncommitted changes
# 🔴 ERROR: Version 1.0.0 already exists
```

**Solution**:

```bash
# 1. Commit changes first
git add .
git commit -m "feat: add new feature"

# 2. Use different version number
bang version list
bang version create 1.1.0

# 3. Or delete existing tag (if mistake)
git tag -d 1.0.0
bang version create 1.0.0
```

### Scenario 5: Port Already in Use

**Problem**: Cannot start service, port is busy

```bash
npm run dev

# Output:
# Error: listen EADDRINUSE: address already in use :::3000
```

**Solution**:

```bash
# 1. Find what's using the port
lsof -i :3000

# 2. Kill the process
kill -9 <PID>

# 3. Or change port in workflow
# Edit workflow.yaml
api:
  port: 3001  # Use different port

# 4. Regenerate config
bang generate workflow.yaml

# 5. Start application
npm run dev
```

### Scenario 6: Permission Denied

**Problem**: Cannot write files during generation

```bash
bang generate workflow.yaml -o /usr/local/app

# Output:
# 🔴 ERROR: Permission denied
#    Cannot create directory: /usr/local/app
```

**Solution**:

```bash
# Option 1: Use sudo (if appropriate)
sudo bang generate workflow.yaml -o /usr/local/app

# Option 2: Change output directory
bang generate workflow.yaml -o ~/my-app

# Option 3: Fix permissions
sudo chown -R $USER /usr/local/app
bang generate workflow.yaml -o /usr/local/app

# Option 4: Create directory first
mkdir -p ~/my-app
bang generate workflow.yaml -o ~/my-app
```

## Troubleshooting Guide

### Diagnostic Commands

```bash
# 1. Verify workflow structure
bang verify workflow.yaml

# 2. Check generation status
bangstack status

# 3. List checkpoints
bangstack checkpoints list

# 4. View logs
cat .bangstack/logs/generation.log

# 5. Check manifest
cat .bangstack/manifest.json

# 6. Validate generated code
npm run lint
npm run type-check

# 7. Test service connections
npm run test:integration
```

### Debug Mode

```bash
# Enable verbose logging
bang generate workflow.yaml --debug

# Output:
# [DEBUG] Loading workflow: workflow.yaml
# [DEBUG] Validating structure...
# [DEBUG] Resolving dependencies...
# [DEBUG] Creating checkpoint: validation
# [DEBUG] Generating component: api
# [DEBUG]   Template: backend/express
# [DEBUG]   Output: /output/api/
# [DEBUG]   Dependencies: redis, queue
```

### Common Issues

#### "Invalid workflow structure"

```bash
# Check YAML syntax
yamllint workflow.yaml

# Validate against schema
bang verify workflow.yaml

# Check for required fields
grep -E "(id|version|stack|stages)" workflow.yaml
```

#### "Command not found: bangstack"

```bash
# Install globally
npm install -g bangstack

# Or use npx
npx bang generate workflow.yaml

# Check installation
which bangstack
bang --version
```

#### "Module not found"

```bash
# Install dependencies
npm install

# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

# Check for missing peer dependencies
npm ls
```

#### "Cannot connect to Docker"

```bash
# Check Docker is running
docker ps

# Start Docker
# macOS: Open Docker Desktop
# Linux: sudo systemctl start docker

# Check Docker Compose
docker-compose --version
```

## Best Practices

### 1. Always Verify Before Generating

```bash
# Verify workflow first
bang verify workflow.yaml

# Then generate
bang generate workflow.yaml
```

### 2. Use Version Control

```bash
# Create versions for major changes
bang version create 1.0.0

# Compare versions before deploying
bang version diff 1.0.0 1.1.0

# Rollback if needed
bang version rollback 1.0.0
```

### 3. Enable Checkpoints

Checkpoints are enabled by default, but you can configure them:

```yaml
# workflow.yaml
workflow:
  options:
    checkpoints: true       # Enable checkpoints
    autoRollback: true      # Rollback on failure
    resume: true            # Allow resume from checkpoint
```

### 4. Handle Errors Gracefully

```typescript
// In your generated code
import { RetryHelpers } from './utils/retry-manager';
import { EnhancedError, ErrorFactory } from './utils/error-handler';

try {
  const data = await RetryHelpers.retryNetworkOperation(
    () => api.fetchData(),
    'fetch data from API'
  );
} catch (error) {
  if (error instanceof EnhancedError) {
    console.error(error.format());

    if (error.isRecoverable()) {
      const recovery = error.getAutomatedRecovery();
      console.log(`Attempting automated recovery: ${recovery.description}`);
      // Execute recovery
    }
  } else {
    throw ErrorFactory.serviceConnectionFailed('api', 'external', error.message);
  }
}
```

### 5. Monitor and Log Errors

```typescript
// Add error tracking
import { ErrorAggregator } from './utils/error-handler';

const errors = new ErrorAggregator();

// Collect errors during operation
errors.add(error1);
errors.add(error2);

// Report all errors
if (errors.hasErrors()) {
  console.error(errors.format());

  // Send to monitoring service
  await sendToSentry(errors.getErrors());
}
```

### 6. Test Error Scenarios

```typescript
// Test retry logic
describe('Retry Logic', () => {
  it('should retry transient failures', async () => {
    const mockFn = jest.fn()
      .mockRejectedValueOnce(new Error('ETIMEDOUT'))
      .mockRejectedValueOnce(new Error('ECONNREFUSED'))
      .mockResolvedValueOnce({ data: 'success' });

    const result = await RetryManager.execute(mockFn, {
      maxAttempts: 3,
      strategy: RetryStrategy.EXPONENTIAL_BACKOFF,
    });

    expect(result.success).toBe(true);
    expect(result.attempts).toBe(3);
  });

  it('should not retry permanent failures', async () => {
    const mockFn = jest.fn()
      .mockRejectedValue(new Error('401 Unauthorized'));

    const result = await RetryManager.execute(mockFn, {
      maxAttempts: 3,
    });

    expect(result.success).toBe(false);
    expect(result.attempts).toBe(1);
    expect(result.failureType).toBe(FailureType.PERMANENT);
  });
});
```

### 7. Document Custom Error Codes

If you add custom error codes:

```typescript
// Add to error-handler.ts
export enum ErrorCode {
  // ... existing codes

  // Custom codes
  CUSTOM_SERVICE_ERROR = 'CUSTOM_SERVICE_ERROR',
  CUSTOM_VALIDATION_ERROR = 'CUSTOM_VALIDATION_ERROR',
}

// Add factory method
export class ErrorFactory {
  static customServiceError(service: string, details: string): EnhancedError {
    return new EnhancedError({
      code: ErrorCode.CUSTOM_SERVICE_ERROR,
      severity: ErrorSeverity.ERROR,
      message: `Custom service error in ${service}`,
      details,
      recoveryStrategies: [
        {
          description: 'Check service logs',
          automated: false,
          steps: [
            'View service logs',
            'Identify root cause',
            'Apply fix',
          ],
        },
      ],
    });
  }
}
```

### 8. Clean Up After Success

```bash
# Clean up checkpoints after successful generation
bang generate workflow.yaml --cleanup

# Or manually
rm -rf .bangstack/checkpoints/
```

### 9. Use Circuit Breakers for External Services

```typescript
// Prevent cascading failures
import { CircuitBreaker } from './utils/retry-manager';

const breaker = new CircuitBreaker('external-api', 5, 60000);

router.get('/data', async (req, res) => {
  try {
    const data = await breaker.execute(() =>
      externalAPI.fetchData()
    );
    res.json(data);
  } catch (error) {
    if (error.message.includes('Circuit breaker')) {
      res.status(503).json({
        error: 'Service temporarily unavailable',
        retryAfter: 60,
      });
    } else {
      throw error;
    }
  }
});
```

### 10. Progressive Enhancement

Start simple, add complexity gradually:

```yaml
# Version 1.0.0: Basic API
stack:
  api:
    type: backend
    technology: typescript/express

# Version 1.1.0: Add caching
stack:
  api:
    type: backend
    technology: typescript/express
    expected_dependencies:
      - service: redis

# Version 1.2.0: Add queue
stack:
  api:
    type: backend
    technology: typescript/express
    expected_dependencies:
      - service: redis
      - service: queue
```

## Getting Help

### Documentation

- [Main Documentation](../README.md)
- [Workflow Schema](./WORKFLOW_SCHEMA.md)
- [CLI Commands](./CLI_COMMANDS.md)
- [Examples](../examples/)

### Support Channels

- **GitHub Issues**: Report bugs and errors
- **Discord**: Ask questions and get help
- **Stack Overflow**: Search for solutions
- **Email**: support@bangstack.com

### Reporting Errors

When reporting errors, include:

1. **Error message**: Full error output
2. **Workflow file**: Your workflow.yaml
3. **Command**: Exact command you ran
4. **Environment**: OS, Node version, Bangstack version
5. **Logs**: Contents of .bangstack/logs/
6. **Steps to reproduce**: Minimal reproduction steps

```bash
# Collect diagnostic info
bangstack diagnose > diagnostics.txt

# Attach to GitHub issue
```

---

**Last Updated**: 2024-01-15
**Bangstack Version**: 1.0.0
