# Bangstack

> **Generate production-ready full-stack applications from a single YAML file**

Bangstack transforms high-level workflow definitions into complete, tested, deployable applications. Define your stack once, and Bangstack generates everything: frontend components, backend APIs, database schemas, tests, Docker configs, CI/CD pipelines, and environment files.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue.svg)](https://www.typescriptlang.org/)

## ✨ Features

- 🎯 **Declarative Workflows** - Define your entire application in YAML
- 🏗️ **Flexible Stack System** - Support for any tech stack (frontend, backend, database, cms, oms, etc.)
- ⚡ **Production-Ready Code** - Generates TypeScript React components, Express APIs, tests, and documentation
- 🔄 **DAG-Based Execution** - Intelligent dependency resolution for complex workflows
- 🎨 **Multiple Generators** - React, TypeScript/Express, Markdown docs, tests, CI/CD, and more
- 🚀 **CLI Tool** - Powerful command-line interface for generation and validation
- 📌 **Version Management** - Git-based versioning with dependency tracking and safe rollbacks
- 🔍 **Dependency Verification** - Automatic detection of infrastructure service usage and mismatches
- 🧪 **Complete Test Generation** - Unit tests (Vitest/Jest), integration tests, and E2E tests (Playwright)
- 🐳 **Docker Support** - Multi-container orchestration with docker-compose.yml and health checks
- 🔄 **CI/CD Pipelines** - GitHub Actions workflows for testing, building, and deployment
- 🔐 **Environment Configuration** - Automatic .env file generation for development, test, and production
- 📦 **CLI/npm Package Generation** - Create publishable CLI tools with Commander.js
- 📦 **Preset Stacks** - Quick start with MERN, Next.js + tRPC, Django + React, and more
- 🎨 **Extended UI Schema** - Custom pages, navigation menus, forms, and protected routes with authentication
- 📄 **Declarative Documentation** - Intent-based documentation generation (setup guides, API reference, tutorials, architecture, best practices)
- ⚡ **Event-Driven Architecture** - Redis pub/sub event bus with automatic event type generation
- 🔌 **Real-time Updates** - WebSocket server and React hooks for live frontend updates
- 🎯 **Convention-Based Events** - Automatic event emission from CRUD operations

## 🚀 Quick Start

### Installation

```bash
npm install -g bangstack
```

### Explore Available Generators

Before creating your project, see what Bangstack can generate:

```bash
bang list-generators --verbose
```

This shows all available generators with usage examples, organized by category (frontend, backend, database, testing, documentation).

### Create a New Project

```bash
# Initialize with a preset
bangstack init my-app --preset mern

# Or start with an example
bangstack init my-app --example

# Or create from scratch
bangstack init my-app
```

### Your First Workflow

Create a simple CRUD API workflow (or use one from `examples/`):

```bash
cd my-app
# Copy an example workflow
cp ../bangstack/examples/simple-crud-api.workflow.yaml ./workflow.yaml
```

### Validate Your Workflow

Before generating, validate your workflow to catch errors early:

```bash
bang validate workflow.yaml
```

Bangstack provides **context-aware error messages** with examples:

```
✖ Validation errors in workflow.yaml:

1. workflow.version
   Error: Version is required
   → Use semantic versioning like "1.0.0"

   Example:
   ✗ version: ""
   ✓ version: 1.0.0

✓ Validation passed!
```

### Generate Code

```bash
bang generate workflow.yaml --output ./generated
```

Watch the **real-time progress indicators** as Bangstack generates your code:

```
⠋ Writing Files (45/62) api/src/routes/tasks.ts
```

That's it! You now have a complete application with:
- ✅ React frontend with TypeScript and Vite
- ✅ Express backend API with TypeScript
- ✅ Database client setup
- ✅ Complete test suite (unit, integration, E2E)
- ✅ Docker Compose orchestration
- ✅ GitHub Actions CI/CD pipelines
- ✅ Environment configuration files
- ✅ Comprehensive documentation

### Run Your Application

```bash
cd generated

# Install dependencies
npm install

# Start with Docker Compose (recommended)
docker-compose up

# Or run services separately
cd api && npm run dev      # Backend on :3000
cd web-app && npm run dev  # Frontend on :5173
```

### Next Steps

- **Customize your workflow**: Edit `workflow.yaml` and regenerate
- **Validate changes**: Run `bang validate workflow.yaml` before regenerating
- **Browse examples**: Check `examples/` for more complex workflows
- **Read the docs**: See the [Documentation](#-documentation) section below

## 📄 Declarative Documentation

Bangstack features an **Intent-Based Documentation System** that automatically generates comprehensive, technology-specific documentation from your workflow definition. Instead of writing docs manually, you declare WHAT documentation you need, and Bangstack generates it based on your actual application structure.

### Documentation Intents

Define documentation in your workflow YAML using intents:

```yaml
documentation:
  intents:
    - type: setup_guide
      audience: developer
      overwrite: always

    - type: api_reference
      audience: developer
      overwrite: always

    - type: tutorial
      audience: developer
      overwrite: always
      topics:
        - create_endpoint
        - add_authentication
        - create_model

    - type: architecture
      audience: developer
      overwrite: always

    - type: best_practices
      audience: developer
      overwrite: always

    - type: troubleshooting
      audience: both
      overwrite: if_missing
```

### Available Documentation Types

- **setup_guide** - Environment setup, dependencies, and getting started
- **api_reference** - Complete API documentation with models, endpoints, authentication
- **tutorial** - Step-by-step guides for common tasks (create endpoints, add auth, models, etc.)
- **architecture** - System architecture, technology stack, data models, deployment
- **best_practices** - Technology-specific coding standards and best practices
- **troubleshooting** - Common issues and their solutions

### Technology-Aware Content

Documentation adapts to your technology stack:

**TypeScript/Express Tutorial:**
```typescript
// Step 1: Define the Route
import { Router } from 'express';
import { PrismaClient } from '@prisma/client';

router.get('/', async (req, res) => {
  const items = await prisma.item.findMany();
  res.json(items);
});
```

**Python/Flask Tutorial:**
```python
# Step 1: Create a Blueprint
from flask import Blueprint, jsonify
from models import db, Item

items_bp = Blueprint('items', __name__)

@items_bp.route('/items', methods=['GET'])
def get_items():
    items = Item.query.all()
    return jsonify([item.to_dict() for item in items])
```

### Features

- ✅ **Auto-generated** - Extracts info from models, endpoints, relationships
- ✅ **Technology-specific** - Different content for TypeScript/Express vs Python/Flask
- ✅ **Always in sync** - Regenerates with your code
- ✅ **Customizable** - Control topics, audience, overwrite policies
- ✅ **Organized** - Creates docs/ directory with index

Generated documentation includes:
- Model field tables with types and descriptions
- API endpoint documentation with examples
- Intelligent example values (emails, UUIDs, dates)
- Authentication setup (Clerk, JWT, etc.)
- Database relationships
- Step-by-step tutorials
- Architecture diagrams
- Best practices for your specific stack

## 📚 Documentation

Bangstack provides comprehensive documentation to help you build production-ready applications:

### 🚀 Getting Started
- **[Quick Reference](./docs/QUICK-REFERENCE.md)** - Cheat sheet for common commands and patterns
- **[Build a Blog in 5 Minutes](./docs/tutorials/BUILD-A-BLOG-IN-5-MINUTES.md)** - Hands-on tutorial to get started

### 📖 Tutorials
- **[Build a Blog in 5 Minutes](./docs/tutorials/BUILD-A-BLOG-IN-5-MINUTES.md)** - Complete blog with authentication
- **[Add Authentication](./docs/tutorials/ADD-AUTHENTICATION.md)** - JWT, OAuth, RBAC, and MFA guide
- **[Build Custom Generators](./docs/tutorials/CUSTOM-GENERATORS.md)** - Extend Bangstack with your own generators

### 📘 Core Guides
- **[Extended Schema Guide](./docs/EXTENDED-SCHEMA-GUIDE.md)** - Complete workflow schema reference
- **[Workflow Best Practices](./docs/WORKFLOW-BEST-PRACTICES.md)** - Tips for effective workflows
- **[API Reference](./docs/API-REFERENCE.md)** - Programmatic API documentation
- **[Generator Framework](./docs/GENERATOR-FRAMEWORK.md)** - How generators work

### 🔍 Full Documentation Index
See **[Documentation Index](./docs/INDEX.md)** for the complete guide to all 20+ documentation files, organized by topic and skill level

## 📖 Example

Here's a simple workflow that generates a complete authentication system:

```yaml
workflow:
  id: user-authentication
  version: 1.0.0
  name: User Authentication
  description: Complete user login workflow

stack:
  web-app:
    type: frontend
    technology: react
    components:
      - id: login-form
        name: LoginForm
        description: User login interface

        state:
          - name: email
            type: string
            initial: ""
          - name: password
            type: string
            initial: ""
          - name: isLoading
            type: boolean
            initial: false

        actions:
          - id: handle-submit
            trigger: form-submit
            steps:
              - id: call-login-api
                action: api-call
                api_workflow: api.login-endpoint
                payload:
                  email: "{{ state.email }}"
                  password: "{{ state.password }}"
                onSuccess:
                  - action: redirect
                    path: /dashboard

  api:
    type: backend
    technology: typescript/express
    dependsOn: [database]
    endpoints:
      - id: login-endpoint
        path: /api/auth/login
        method: POST
        implementation:
          steps:
            - id: validate-request
              action: validate-schema
            - id: find-user
              action: database-query
              database: users
            - id: verify-password
              action: crypto-compare
              implementation: bcrypt
            - id: generate-token
              action: generate-jwt
              expiresIn: 7d
            - id: return-success
              action: respond
              status: 200

  database:
    type: database
    technology: postgresql
    tables:
      - name: users
        required_fields:
          - name: id
            type: uuid
            primary_key: true
          - name: email
            type: string
            unique: true
          - name: passwordHash
            type: string
```

### Generated Output (59 files)

From this single workflow file, Bangstack generates:

**Frontend (14 files)**
```
web-app/
├── src/
│   ├── components/
│   │   ├── LoginForm.tsx              # React component with state management
│   │   ├── LoginForm.module.css       # Scoped styles
│   │   └── LoginForm.types.ts         # TypeScript types
│   ├── api/
│   │   └── client.ts                  # Type-safe API client
│   ├── test/
│   │   ├── setup.ts                   # Test setup with jest-dom
│   │   └── components/
│   │       └── LoginForm.test.tsx     # Unit tests
│   └── main.tsx                       # App entry point
├── e2e/
│   ├── login.spec.ts                  # E2E tests
│   └── playwright.config.ts           # Playwright config
├── package.json                       # Dependencies
├── tsconfig.json                      # TypeScript config
├── tsconfig.node.json                 # Node TypeScript config
├── vite.config.ts                     # Vite + Vitest config
├── .env.example                       # Environment template
├── .env.development                   # Dev environment
├── .env.test                          # Test environment
└── index.html                         # HTML template
```

**Backend (18 files)**
```
api/
├── src/
│   ├── routes/
│   │   ├── login-endpoint.ts          # Express route handler
│   │   └── index.ts                   # Routes index
│   ├── types/
│   │   └── login-endpoint.types.ts    # Request/response types
│   ├── middleware/
│   │   └── index.ts                   # JWT auth middleware
│   ├── database/
│   │   └── client.ts                  # PostgreSQL client
│   ├── test/
│   │   ├── setup.ts                   # Test setup
│   │   ├── unit/
│   │   │   └── login-endpoint.test.ts # Unit tests
│   │   └── integration/
│   │       └── login-endpoint.test.ts # Integration tests
│   └── index.ts                       # Server entry point
├── package.json
├── tsconfig.json
├── jest.config.js                     # Jest configuration
├── .env.example                       # Environment template
├── .env.development                   # Dev environment
├── .env.test                          # Test environment
└── Dockerfile                         # Container image
```

**Database (4 files)**
```
database/
├── .env.example                       # Environment template
├── .env.development                   # Dev environment
├── .env.test                          # Test environment
└── init.sql                           # Schema initialization
```

**Documentation (8 files)**
```
docs/
├── user/
│   ├── how-to-log-in.md              # User guide
│   └── README.md                      # User docs index
├── developer/
│   ├── authentication-api-reference.md # API reference
│   └── README.md                      # Developer docs index
├── architecture.md                    # Architecture overview
├── testing.md                         # Testing guide
└── README.md                          # Main documentation
```

**CI/CD (3 files)**
```
.github/workflows/
├── test.yml                           # Test workflow
├── build.yml                          # Build workflow
└── deploy.yml                         # Deploy workflow
```

**Docker & Deployment (5 files)**
```
.
├── docker-compose.yml                 # Multi-container orchestration
├── start.sh                           # Start script
├── stop.sh                            # Stop script
├── web-app/Dockerfile                 # Frontend container
└── api/Dockerfile                     # Backend container
```

**Project Root (7 files)**
```
.
├── README.md                          # Project documentation
├── package.json                       # Root package.json
├── .gitignore                         # Git ignore rules
├── tsconfig.json                      # TypeScript config
├── .dockerignore                      # Docker ignore rules
├── ARCHITECTURE.md                    # Architecture docs
└── TESTING.md                         # Testing guide
```

## 🛠️ CLI Commands

### `bang generate`

Generate code from a workflow file:

```bash
bang generate <workflow> [options]

Options:
  -o, --output <directory>  Output directory (default: "./generated")
  -d, --dry-run            Show what would be generated without writing files
  -v, --verbose            Show detailed output
```

**Examples:**
```bash
# Generate with default output
bang generate workflow.yaml

# Custom output directory
bang generate workflow.yaml --output ./src

# Dry run to preview
bang generate workflow.yaml --dry-run --verbose

# Resume from last checkpoint after failure
bang generate workflow.yaml --resume
```

#### Checkpoint & Resume System

Bangstack automatically creates checkpoints during generation, allowing you to resume if the process is interrupted:

**Features:**
- **Automatic Checkpoints**: Progress is saved at each generation stage
- **Resume After Failure**: Use `--resume` to continue from the last checkpoint
- **Automatic Rollback**: Failed generations are automatically rolled back
- **Retry Logic**: Transient failures (network, disk) are automatically retried

**Example:**
```bash
# Start generation (creates checkpoints automatically)
bang generate large-app.workflow.yaml

# If interrupted or fails, resume from last checkpoint
bang generate large-app.workflow.yaml --resume

# Disable checkpoints (not recommended for large workflows)
bang generate workflow.yaml --no-checkpoint

# Disable automatic retry
bang generate workflow.yaml --no-retry
```

**Checkpoint Information:**
```
Generation Summary:
  ✓ Files generated: 62

Checkpoint Status:
  Stage: complete
  Progress: 100%

💡 Checkpoints are stored in `.bangstack/checkpoints/` and cleaned up after successful generation
```

### `bang validate`

Validate workflow files:

```bash
bangstack validate <workflow> [options]

Options:
  -d, --directory  Validate all workflow files in a directory
```

**Examples:**
```bash
# Validate single file
bangstack validate workflow.yaml

# Validate entire directory
bangstack validate ./workflows --directory
```

### `bang list-generators`

List all available code generators:

```bash
bang list-generators [options]

# Alias
bang list

Options:
  -v, --verbose           Show detailed information about each generator
  -c, --category <name>   Filter by category (frontend, backend, database, test, documentation)
```

**Basic Output:**
```
┌────────────────────────────────────────────────┐
│ Bangstack Generators                           │
│ Available code generators for your workflows   │
└────────────────────────────────────────────────┘

Frontend Frameworks
✓ React Frontend Generator
  Generates React components with TypeScript

Backend Languages
✓ TypeScript/Express Backend Generator
  Generates Express API with TypeScript

Database Generators
✓ Prisma Database Generator
  Generates Prisma schema and migrations
✓ Drizzle ORM Database Generator
  Generates Drizzle schemas and migrations

Testing Frameworks
✓ Frontend Unit Test Generator
✓ Backend Integration Test Generator
✓ E2E Test Generator
✓ CLI Unit Test Generator

Summary
  Frontend Frameworks    1
  Backend Languages      1
  Database Generators    2
  Testing Frameworks     4
  Total                  9

ℹ Run `bang list-generators --verbose` for detailed information
ℹ Run `bang list-generators --category <category>` to filter by category
```

**Verbose Output (with --verbose):**
```bash
bang list --verbose --category database

Frontend Frameworks
✓ Prisma Database Generator
  Generates Prisma schema and migrations
  Usage in workflow: `stack.database.technology: "prisma"`
  Database: prisma

✓ Drizzle ORM Database Generator
  Generates Drizzle schemas and migrations
  Usage in workflow: `stack.database.technology: "drizzle"`
  Database: drizzle
```

### `bang init`

Initialize a new project:

```bash
bangstack init [project-name] [options]

Options:
  -p, --preset <preset>  Use a preset stack
  --example             Create with example workflow
```

**Available Presets:**
- `mern` - MongoDB, Express, React, Node.js
- `next-trpc` - Next.js + tRPC + Prisma
- `django-react` - Django REST framework + React

**Examples:**
```bash
# Initialize with MERN preset
bangstack init my-app --preset mern

# Initialize with example workflow
bangstack init my-app --example

# Show available presets
bangstack init
```

## 🔄 Version Management

Bangstack provides powerful version management to help you safely evolve your application architecture over time. Track changes, detect dependency mismatches, and rollback to previous versions with confidence.

### Why Version Management?

When you modify your workflow configuration (e.g., changing from Redis to Upstash, adding new services), you need to ensure:
1. The YAML configuration and generated code stay in sync
2. Infrastructure service changes don't break existing code
3. You can safely rollback to previous working versions

**Example Problem**: You deploy version 1.0 with Redis. Then you create version 2.0 using email service. After testing, you decide to rollback the YAML to 1.0, but your implementation code still references email service - causing runtime errors!

**Solution**: Bangstack's version management system tracks dependencies, detects mismatches, and provides warnings before problems occur.

### Expected Dependencies

Declare what infrastructure services each component should use:

```yaml
stack:
  api:
    type: backend
    technology: typescript/express
    # Declare expected infrastructure dependencies
    expected_dependencies:
      - service: redis
        usage: "Session storage and caching"
        required: true
      - service: queue
        usage: "Background job processing"
        required: true

stages:
  local:
    infrastructure:
      services:
        redis:
          provider: local
          connection: redis://localhost:6379
        queue:
          provider: local
          connection: bullmq://localhost:6379
```

Bangstack will:
- Generate service clients for each dependency
- Track which services are actually used in your code
- Warn you if code uses services not declared in YAML
- Warn you if YAML declares services not used in code

### `bang verify`

Verify your workflow against the current codebase state without generating any files:

```bash
bang verify <workflow> [options]

Options:
  -o, --output <directory>  Output directory to check against (default: cwd)
  -v, --verbose            Show detailed output
```

**What it checks:**
- ✅ Workflow YAML validity
- ✅ Expected vs detected dependency mismatches
- ✅ Orphaned client files from removed services
- ✅ Version differences from last generation

**Example Output:**

```bash
bang verify workflow.yaml -o ./generated

📊 Verification Report

Workflow: My Application
Version: 2.0.0

Current State:
  Generated: 10/12/2025, 4:13:26 PM
  Version: 1.0.0

Changes Detected:
  📦 Version: 1.0.0 → 2.0.0

  Infrastructure Services:
    ➖ Removed: redis
    ➕ Added: upstash

Component Dependencies:

  ⚠️  api (typescript/express):
     Expected: upstash, queue
     Detected: redis, queue
     Missing dependency: 'upstash' expected but not found in code
     Unexpected dependency: 'redis' found but not declared in YAML

  ✓ cache (typescript/express):
     Expected: upstash
     Detected: upstash

Recommendations:
  • Remove or update redis-client.ts (no longer used)
  • Implement upstash service integration in api component
  • Run: bang generate workflow.yaml -o ./generated

Summary: ⚠️  2 warnings found - manual review required
Exit Code: 1
```

**Exit Codes:**
- `0` - No issues found, ready to generate
- `1` - Warnings found, manual review required

**Use in CI/CD:**
```yaml
# .github/workflows/verify.yml
- name: Verify workflow integrity
  run: bang verify workflow.yaml -o ./src
```

### `bang version create`

Create a new version with git tagging:

```bash
bang version create <version> [options]

Options:
  -m, --message <message>  Version message (optional)
```

**What it does:**
1. Validates repository is clean (no uncommitted changes)
2. Validates version follows semver format (e.g., 1.2.0)
3. Updates workflow YAML with new version
4. Commits the change
5. Creates git tag: `v<version>`

**Example:**

```bash
# Create version 2.0.0
bang version create 2.0.0 -m "Switch from Redis to Upstash"

✓ Repository is clean
✓ Version 2.0.0 is valid semver
✓ Updated workflow version to 2.0.0
✓ Committed changes
✓ Created tag v2.0.0

Version 2.0.0 created successfully!
```

### `bang version rollback`

Rollback to a previous version with safety checks:

```bash
bang version rollback <version> [options]

Options:
  --force  Skip confirmation prompt
```

**What it does:**
1. Validates repository is clean
2. Reads manifest from target version
3. Compares with current state
4. **Warns about infrastructure service changes**
5. **Warns about dependency mismatches**
6. Shows git diff
7. Prompts for confirmation
8. Checks out the version tag

**Example:**

```bash
# Rollback from v2.0.0 (upstash) to v1.0.0 (redis)
bang version rollback 1.0.0

📊 Rollback Analysis

Current Version: 2.0.0
Target Version: 1.0.0

⚠️  Warnings:

Infrastructure Services:
  Services will be removed: upstash
    → Client files may exist: upstash-client.ts

  Services will be added: redis
    → Client files may be missing: redis-client.ts

Dependencies:
  Component 'api' code uses: [upstash, queue]
    → But v1.0.0 expects: [redis, queue]

  Component 'cache' code uses: [upstash]
    → But v1.0.0 expects: [redis]

Git Changes:
  M workflow.yaml
  - upstash configuration
  + redis configuration

⚠️  After rollback, you should:
  1. Run: bang verify workflow.yaml -o ./generated
  2. Run: bang generate workflow.yaml -o ./generated
  3. Update implementation code to use redis instead of upstash

Continue with rollback? (y/N): y

✓ Checked out version v1.0.0
✓ Repository is now at v1.0.0

Next steps:
  bang verify workflow.yaml -o ./generated
  bang generate workflow.yaml -o ./generated
```

### `bang version list`

List all available versions:

```bash
bang version list [options]

Options:
  --limit <number>  Limit number of versions shown
```

**Example Output:**

```bash
bang version list

Available Versions:

v2.0.0  abc1234  2025-10-12  Switch from Redis to Upstash
v1.1.0  def5678  2025-10-10  Add queue service
v1.0.0  ghi9012  2025-10-08  Initial version

Total: 3 version(s)
```

### `bang version diff`

Compare two versions:

```bash
bang version diff <from-version> <to-version> [options]

Options:
  --manifest-only  Show only manifest differences
```

**Example:**

```bash
bang version diff 1.0.0 2.0.0

📊 Version Comparison

From: v1.0.0 → To: v2.0.0

Manifest Changes:
  Version: 1.0.0 → 2.0.0

  Infrastructure Services:
    ➖ Removed: redis
    ➕ Added: upstash

  Components:
    api:
      Expected dependencies changed:
        - redis → upstash

Git Diff:
  --- a/workflow.yaml
  +++ b/workflow.yaml
  @@ -1,5 +1,5 @@
   workflow:
  -  version: 1.0.0
  +  version: 2.0.0
  ...
```

## 🎯 Version Management Best Practices

### 1. Always Verify Before Regenerating

```bash
# Good workflow
bang verify workflow.yaml -o ./src
bang generate workflow.yaml -o ./src
```

### 2. Create Versions for Infrastructure Changes

```bash
# When changing services (redis → upstash)
bang version create 2.0.0 -m "Migrate to Upstash"
bang generate workflow.yaml -o ./src
git add .
git commit -m "Generate code for v2.0.0"
```

### 3. Test Before Creating Versions

```bash
# Test your changes first
bang generate workflow.yaml -o ./test-output --dry-run
bang verify workflow.yaml -o ./test-output

# Then create version
bang version create 2.0.0
```

### 4. Use Verify in CI/CD

```yaml
# .github/workflows/verify.yml
name: Verify Workflow Integrity

on: [push, pull_request]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Bangstack
        run: npm install -g bangstack
      - name: Verify workflow
        run: bang verify workflow.yaml -o ./src
      - name: Check for drift
        if: failure()
        run: |
          echo "⚠️ Workflow configuration has drifted from code!"
          echo "Run: bang generate workflow.yaml -o ./src"
          exit 1
```

### 5. Document Version Changes

```bash
# Good version messages
bang version create 2.0.0 -m "Switch Redis to Upstash for serverless"
bang version create 2.1.0 -m "Add SQS queue for async processing"

# Not helpful
bang version create 2.0.0 -m "Update config"
```

## 🔧 Troubleshooting

### Issue: "Unexpected dependency found"

**Problem:**
```
⚠️  api (typescript/express):
   Expected: redis
   Detected: redis, queue
   Unexpected dependency on 'queue' found in: service-manager.ts
```

**Solution:**
Your code uses the `queue` service but it's not declared in YAML. Either:

1. **Add to YAML** (if intentional):
```yaml
stack:
  api:
    expected_dependencies:
      - service: redis
        usage: "Caching"
      - service: queue  # Add this
        usage: "Background jobs"
```

2. **Remove from code** (if unintentional):
```typescript
// Remove queue import and usage
import { queueClient } from './clients/queue-client';  // Remove this
```

### Issue: "Missing dependency"

**Problem:**
```
⚠️  api (typescript/express):
   Expected: redis, queue
   Detected: redis
   Missing dependency: 'queue' expected but not found in code
```

**Solution:**
YAML declares `queue` but your code doesn't use it. Either:

1. **Implement in code**:
```typescript
// Add to your code
import { queueClient } from './clients/queue-client';

// Use it
await queueClient.enqueue('email', { to: user.email });
```

2. **Remove from YAML** (if not needed):
```yaml
expected_dependencies:
  - service: redis
    usage: "Caching"
  # Remove queue if not needed
```

### Issue: "Orphaned client files"

**Problem:**
```
Recommendations:
  • Remove or update redis-client.ts (no longer used)
```

**Solution:**
You switched from redis to upstash, but redis-client.ts still exists:

```bash
# Option 1: Regenerate (will clean up)
bang generate workflow.yaml -o ./src

# Option 2: Manually remove
rm src/clients/redis-client.ts
```

### Issue: Version rollback but code still uses new service

**Problem:**
Rolled back YAML from v2.0 (upstash) to v1.0 (redis), but code still imports upstash.

**Solution:**
```bash
# After rollback, regenerate code
bang version rollback 1.0.0
bang generate workflow.yaml -o ./src

# Or manually update implementation files
# Replace upstash imports with redis
```

### Multi-Language Support

**Currently Supported:**
- ✅ TypeScript/JavaScript (Node, React, Express, Nest, Next.js, etc.)

**Not Yet Supported:**
- ⚠️ Rust, Go, Python, Java, etc.

For unsupported languages, the analyzer will skip with a warning:
```
Component Dependencies:

  ⚠️  rust-api (rust):
     Expected: redis
     Detected: (analysis not supported)
     Dependency analysis not supported for 'rust'
     Please manually verify dependencies match your YAML
```

**Workaround:** Manually ensure your code matches YAML declarations.

## 🏗️ Architecture

Bangstack consists of four main components:

### 1. **Workflow Parser**
- Parses YAML workflow files
- Validates with Zod schemas
- Supports single files or directories
- Comprehensive error messages

### 2. **Execution Engine**
- Builds DAGs (Directed Acyclic Graphs) from workflow steps
- Performs topological sorting for execution order
- Detects circular dependencies
- Validates component references and relationships

### 3. **Generator Framework**
- Pluggable architecture for extensibility
- Automatic registration system
- Support for multiple output formats
- Context-aware generation

### 4. **CLI Tool**
- Beautiful terminal output (chalk + ora)
- Comprehensive error handling
- Progress indicators
- Verbose and dry-run modes

```
┌─────────────────┐
│  Workflow YAML  │
└────────┬────────┘
         │
         v
┌─────────────────┐
│ Workflow Parser │
│   (Zod Schema)  │
└────────┬────────┘
         │
         v
┌─────────────────┐
│ Execution Engine│
│  (DAG Builder)  │
└────────┬────────┘
         │
         v
┌─────────────────┐     ┌──────────────────┐
│ Generator       │────>│  React           │
│ Framework       │────>│  Express         │
│                 │────>│  Tests           │
│                 │────>│  Docker          │
│                 │────>│  CI/CD           │
│                 │────>│  Environment     │
│                 │────>│  Documentation   │
└─────────────────┘     └──────────────────┘
         │
         v
┌─────────────────┐
│ Generated Code  │
│  (59+ files)    │
└─────────────────┘
```

## 📚 Workflow Schema

The workflow schema is designed to be comprehensive yet intuitive:

### Core Structure

```yaml
workflow:
  id: string                    # Unique identifier
  version: string               # Semantic version
  name: string                  # Human-readable name
  description: string           # Description
  actors: []                    # Who interacts with this workflow
  domains: []                   # Domain tags
  relationships: []             # Related workflows

stack:
  [component-name]:
    type: string                # frontend, backend, database, cli, etc.
    technology: string          # react, typescript/express, typescript/node, etc.
    dependsOn: []              # Dependencies on other components
    config: {}                 # Component-specific config
    components: []             # UI components (for frontend)
    endpoints: []              # API endpoints (for backend)
    tables: []                 # Database tables (for database)
    commands: []               # CLI commands (for cli)

documentation:
  user_docs: []               # User-facing documentation
  developer_docs: []          # Developer documentation

testing:
  unit_tests: []              # Unit test specifications
  integration_tests: []       # Integration test specifications
  e2e_tests: []              # End-to-end test specifications

environment:
  development: {}             # Dev environment config
  production: {}              # Prod environment config

deployment:
  [component-name]:
    build_command: string     # Build command
    start_command: string     # Start command
    health_check: {}          # Health check config
```

### Key Features

- **Flexible Stack System**: Define any component type (frontend, backend, cms, oms, etl, etc.)
- **Dependency Management**: Declare dependencies between stack components
- **Template Variables**: Use `{{ variable.path }}` for dynamic values
- **Multi-Actor Support**: Define workflows for customers, developers, admins, etc.
- **Step Dependencies**: Use `depends_on` for execution ordering

See [WORKFLOW-SCHEMA.md](./docs/WORKFLOW-SCHEMA.md) for complete documentation.

## 🎯 Use Cases

### 1. **Rapid Prototyping**
Define your application architecture and generate a working prototype in minutes:
```bash
bangstack init prototype --preset mern
bang generate workflows/prototype.workflow.yaml
cd generated && npm install && npm run dev
```

### 2. **Documentation Sync**
Keep your documentation always in sync with your code:
```yaml
documentation:
  user_docs:
    - title: Getting Started
      sections:
        - heading: Installation
          content: |
            Install the app by running...
```

### 3. **Multi-Stack Applications**
Generate different tech stacks for different components:
```yaml
stack:
  admin-panel:
    type: frontend
    technology: react

  customer-portal:
    type: frontend
    technology: vue

  api:
    type: backend
    technology: typescript/express

  background-jobs:
    type: backend
    technology: python/celery
```

### 4. **Team Collaboration**
Define workflows that serve multiple actors:
```yaml
workflow:
  actors:
    - type: customer
      role: end-user
    - type: developer
      role: frontend
    - type: developer
      role: backend
```

## 🔌 Extending Bangstack

### Create a Custom Generator

```typescript
import { FrontendGenerator, GeneratorContext, GenerationResult } from 'bangstack';

export class VueGenerator implements FrontendGenerator {
  id = 'vue-frontend';
  name = 'Vue.js Frontend Generator';
  description = 'Generates Vue 3 components';
  framework = 'vue';

  generate(context: GeneratorContext): GenerationResult {
    // Your generation logic here
    return {
      files: [
        {
          path: 'src/App.vue',
          content: '<template>...</template>',
          overwrite: true,
        },
      ],
    };
  }
}

// Register it
import { globalRegistry } from 'bangstack';
globalRegistry.registerFrontendGenerator(new VueGenerator());
```

### Create a Preset

Presets are defined in `src/cli/commands/init.ts`:

```typescript
const PRESETS = {
  'my-stack': {
    name: 'My Custom Stack',
    description: 'My preferred tech stack',
    stack: {
      frontend: {
        type: 'frontend',
        technology: 'vue',
      },
      backend: {
        type: 'backend',
        technology: 'go/fiber',
      },
    },
  },
};
```

## 🧪 Testing

Run the test suite:

```bash
npm test
```

**Test Coverage:**
- ✅ Workflow Parser - YAML parsing and validation
- ✅ DAG Engine - Dependency resolution and execution ordering
- ✅ Workflow Engine - End-to-end workflow execution
- ✅ Generator Registry - Plugin registration and management
- ✅ React Generator - Frontend component and configuration generation
- ✅ TypeScript/Express Generator - Backend API generation
- ✅ TypeScript CLI Generator - CLI application generation
- ✅ Markdown Generator - Documentation generation
- ✅ Frontend Test Generator - Vitest and Playwright test generation
- ✅ Backend Test Generator - Jest test generation
- ✅ CLI Test Generator - Jest unit tests for CLI commands
- ✅ E2E Test Generator - End-to-end test scaffolding
- ✅ Docker Generator - Container and orchestration generation
- ✅ GitHub Actions Generator - CI/CD pipeline generation
- ✅ Environment Generator - Configuration file generation
- ✅ Event Types Generator - TypeScript event interfaces and type guards
- ✅ Event Bus Generator - Redis pub/sub event infrastructure
- ✅ Event Handlers Generator - Event subscriber implementations
- ✅ WebSocket Server Generator - Real-time server infrastructure
- ✅ WebSocket Client Generator - React hooks for WebSocket subscriptions

**E2E Testing Infrastructure (v0.4.3+):**
- ✅ File Generation Smoke Tests - Verifies files are actually written to disk
- ✅ Database Configuration Tests - Tests Prisma/Drizzle generation
- ✅ Authentication Tests - Tests auth middleware generation
- ✅ Event-Driven Architecture Tests - Tests event infrastructure generation

All generators are fully tested with comprehensive test suites. E2E tests ensure generated code is actually written to disk and structured correctly, catching bugs like the v0.4.1 issue where files weren't being generated.

## 📝 Examples

See the [examples](./examples) directory for complete workflow examples:

- **[simple-crud-api.workflow.yaml](./examples/simple-crud-api.workflow.yaml)** - Simple CRUD API for task management (perfect for getting started)
- **[user-authentication.workflow.yaml](./examples/user-authentication.workflow.yaml)** - Complete authentication system with frontend + backend
- **[task-manager-complete.workflow.yaml](./examples/task-manager-complete.workflow.yaml)** - Full-stack task management application with event-driven architecture
- **[example-event-driven.workflow.yaml](./examples/example-event-driven.workflow.yaml)** - Event-driven architecture with Redis pub/sub and WebSocket real-time updates
- **[ecommerce-api](./examples/ecommerce-api/)** - E-commerce API with multiple endpoints
- **[saas-fullstack](./examples/saas-fullstack/)** - Complete SaaS platform example
- **[api-platform](./examples/api-platform/)** - API platform with authentication and rate limiting

### CLI Application Example

Generate a publishable npm CLI tool:

```yaml
workflow:
  id: hello-cli-package
  version: 1.0.0
  name: Hello CLI Package
  description: A simple CLI tool that can be published to npm

stack:
  hello-cli:
    type: cli
    technology: typescript/node
    description: A simple CLI application

    config:
      bin_name: hello-cli

    commands:
      - id: greet-command
        name: greet
        description: Greets the user with a friendly message

        arguments:
          - name: name
            description: Name to greet
            required: false
            default: World

        implementation:
          steps:
            - id: format-greeting
              action: format-string
              template: "Hello, {{name}}!"
            - id: output-greeting
              action: console-output
              color: green

testing:
  unit_tests:
    - component: hello-cli.greet-command
      scenarios:
        - displays default greeting message
        - displays custom greeting with provided name
```

**Generated Output (13+ files):**
```
hello-cli/
├── src/
│   ├── cli.ts                     # Main CLI entry point
│   └── commands/
│       ├── greet.ts               # Command implementation
│       ├── greet.test.ts          # Jest unit tests
│       └── index.ts               # Command registration
├── bin/
│   └── cli.js                     # Executable entry point
├── package.json                   # With bin configuration
├── tsconfig.json
├── jest.config.js
├── README.md
└── .env.*                         # Environment files
```

**Usage:**
```bash
# Install and test locally
cd hello-cli && npm install && npm run build
npm link

# Run the CLI
hello-cli greet
hello-cli greet Alice

# Publish to npm
npm login
npm publish
```

## 🗺️ Roadmap

### v0.1.0 - MVP
- ✅ React Frontend Generator with TypeScript
- ✅ TypeScript/Express Backend Generator
- ✅ TypeScript CLI Generator with Commander.js
- ✅ Database Schema Generation (PostgreSQL)
- ✅ Test Generators (Vitest, Jest, Playwright, CLI)
- ✅ Docker & Docker Compose Generation
- ✅ GitHub Actions CI/CD Pipelines
- ✅ Environment Configuration Management

### v0.2.0 - Documentation & Versioning
- ✅ Intent-Based Documentation System (6 template types: setup, API reference, tutorials, architecture, best practices, troubleshooting)
- ✅ Technology-Aware Documentation (TypeScript/Express, Python/Flask, React, Prisma)
- ✅ Version Management with Git Integration
- ✅ Dependency Tracking and Verification
- ✅ AST-based Code Analysis (TypeScript)

### v0.3.0 - Extended Schema
- ✅ Extended Workflow Schema with technology section
- ✅ Advanced UI configuration (pages, forms, navigation)
- ✅ Authentication scaffolding support
- ✅ ORM integrations (Prisma, Drizzle)

### v0.4.0 - Event-Driven Architecture
- ✅ Event type definition and generation
- ✅ Redis pub/sub event bus infrastructure
- ✅ Automatic event emission from CRUD endpoints
- ✅ Event handler generation with subscriber pattern
- ✅ WebSocket server for real-time updates
- ✅ React hooks for WebSocket event subscriptions
- ✅ Event flow documentation and troubleshooting guides
- ✅ Comprehensive test coverage for event generators

### v0.4.3 (Current) - Quality & Testing
- ✅ E2E test infrastructure for file generation verification
- ✅ Database configuration E2E tests
- ✅ Authentication setup E2E tests
- ✅ Event-driven architecture E2E tests
- ✅ Improved prepublishOnly script (lint + test + build)
- ✅ Enhanced code quality gates

### v0.5.0 (Next Release)
- [ ] Database Migration Generator (Prisma, Drizzle)
- [ ] Additional example workflows (CRUD app, API service, todo app)
- [ ] Improved error messages and validation
- [ ] Workflow schema documentation
- [ ] CLI improvements (better progress indicators, dry-run enhancements)

### v0.3.0
- [ ] Vue.js Frontend Generator
- [ ] Python/FastAPI Backend Generator
- [ ] OpenAPI/Swagger Documentation Generator
- [ ] Database seeding and fixtures
- [ ] Authentication scaffolding templates

### v1.0.0
- [ ] Visual Workflow Builder (Web UI)
- [ ] AI-Powered Workflow Generation
- [ ] Code Inference (Generate workflows from existing codebases)
- [ ] Workflow Marketplace
- [ ] Plugin system for custom generators

See [FUTURE-CONSIDERATIONS.md](./docs/FUTURE-CONSIDERATIONS.md) for detailed roadmap.

## 🤝 Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

### Development Setup

```bash
# Clone the repository
git clone https://github.com/mogullabs/bangstack.git
cd bangstack

# Install dependencies
npm install

# Build the project
npm run build

# Link for local testing
npm link

# Run tests
npm test

# Run linter
npm run lint
```

## 📄 License

MIT License - see [LICENSE](./LICENSE) for details.

## 🙏 Acknowledgments

Built with:
- [TypeScript](https://www.typescriptlang.org/) - Type-safe JavaScript
- [Zod](https://zod.dev/) - TypeScript-first schema validation
- [Commander.js](https://github.com/tj/commander.js) - CLI framework
- [Chalk](https://github.com/chalk/chalk) - Terminal styling
- [Ora](https://github.com/sindresorhus/ora) - Terminal spinners

## 📬 Support

- 📖 [Documentation](./docs)
- 🐛 [Issue Tracker](https://github.com/mogullabs/bangstack/issues)
- 💬 [Discussions](https://github.com/mogullabs/bangstack/discussions)

---

**Built with ❤️ by the Bangstack team**

**Generate less, build more.** 🚀
