# Post-MVP Architecture Enhancements

This document outlines architectural improvements to implement after the MVP launch.

## 1. Events System

**Priority**: High
**Complexity**: High
**Impact**: Enables event-driven architectures and decoupled systems

### Concept

Allow workflows to emit and subscribe to events, enabling:
- Event-driven microservices
- Async workflow triggers
- Audit trails and notifications
- Decoupled system components

### Example

```yaml
# Event definitions
events:
  user-logged-in:
    payload:
      userId: string
      timestamp: datetime
      ipAddress: string

# Publisher (emits events)
endpoints:
  - id: login
    implementation:
      steps:
        - id: return-success
          action: respond
          status: 200

        - id: emit-login-event
          action: emit-event
          event: user-logged-in
          payload:
            userId: "{{ user.id }}"
            timestamp: "{{ now }}"
            ipAddress: "{{ request.ip }}"

# Subscribers (react to events)
workflows:
  - id: send-welcome-email
    trigger:
      event: user-logged-in
    steps:
      - action: send-email
        template: welcome
        to: "{{ event.payload.userId }}"

  - id: update-analytics
    trigger:
      event: user-logged-in
    steps:
      - action: track-event
        analytics: mixpanel
        event: login
```

### Implementation Notes

- Add `events` section to workflow schema
- Create event bus abstraction (RabbitMQ, Redis Pub/Sub, AWS EventBridge)
- Generate event emitter code in endpoints
- Generate event subscriber handlers
- Support both sync and async event processing

---

## 2. Workflow-to-Documentation Generator

**Priority**: Medium
**Complexity**: Low
**Impact**: Better developer experience for generated projects

### Concept

Automatically generate installation and setup documentation from workflow definitions, including multi-variant instructions (npm/yarn/pnpm/bun).

### Example

```yaml
# Workflow definition
deployment:
  database:
    setup_command: npm run migrate
    technology: postgresql/prisma
```

**Auto-generated documentation:**

````markdown
## Database Setup

Choose your package manager:

### Using npm
```bash
cd database
npm install
npm run migrate
```

### Using yarn
```bash
cd database
yarn install
yarn migrate
```

### Using pnpm
```bash
cd database
pnpm install
pnpm migrate
```

### Using bun
```bash
cd database
bun install
bun migrate
```

## Technology Details

This project uses **Prisma** for database management.
- [Prisma Documentation](https://prisma.io/docs)
- Database provider: **PostgreSQL**
````

### Implementation Notes

- Create `SetupDocumentationGenerator`
- Parse `deployment` section for setup commands
- Generate multi-variant installation instructions
- Include technology-specific notes and links
- Auto-detect and document environment variables

---

## 3. Reusable Nested Workflows

**Priority**: Medium
**Complexity**: Medium
**Impact**: DRY principle, reusable business logic

### Concept

Define workflows once and call them like functions from multiple places.

### Example

```yaml
# Define reusable workflow
workflows:
  shared:
    - id: validate-auth-token
      name: Validate Authentication Token
      inputs:
        - token: string
      outputs:
        - userId: string
        - isValid: boolean
      steps:
        - id: verify-jwt
          action: verify-jwt
          token: "{{ inputs.token }}"
        - id: check-expiry
          action: check-token-expiry
        - id: return-result
          action: return
          outputs:
            userId: "{{ verify-jwt.payload.userId }}"
            isValid: true

# Use in multiple endpoints
endpoints:
  - id: get-profile
    implementation:
      steps:
        - id: validate
          workflow: validate-auth-token
          inputs:
            token: "{{ request.headers.authorization }}"
        - id: fetch-profile
          depends_on: [validate]
          action: database-query
          filter: { id: "{{ validate.outputs.userId }}" }

  - id: update-settings
    implementation:
      steps:
        - id: validate
          workflow: validate-auth-token  # Reused!
          inputs:
            token: "{{ request.headers.authorization }}"
        - id: update
          depends_on: [validate]
          action: database-update
```

### Implementation Notes

- Add `workflows.shared` section to schema
- Support workflow inputs/outputs
- Update DAG engine to handle nested execution plans
- Generate reusable functions in code
- Support recursive workflow calls (with depth limits)

---

## 4. Structured Service/Implementation System

**Priority**: Low
**Complexity**: Medium
**Impact**: Better than string hints, type-safe integrations

### Current Limitation

```yaml
steps:
  - action: crypto-compare
    implementation: bcrypt  # Just a string hint
```

### Proposed Enhancement

```yaml
# Define available implementations per action type
actions:
  crypto-compare:
    implementations:
      - id: bcrypt
        package: bcrypt
        version: "^5.1.0"
      - id: argon2
        package: argon2
        version: "^0.30.0"

# Use in workflow with auto-adaptation
steps:
  - action: crypto-compare
    service: bcrypt  # Type-checked against available implementations
    compare:
      plain: "{{ request.body.password }}"
      hashed: "{{ user.passwordHash }}"

  # OR auto-detect from stack
  - action: database-query
    service: ${{ stack.database.technology }}  # Automatically uses Prisma/Drizzle
    query:
      type: findOne
      filter: { email: "{{ request.body.email }}" }
```

### Implementation Notes

- Create action registry with available implementations
- Add validation for `service` field against registry
- Generate import statements for specified packages
- Support auto-detection from stack configuration
- Document available actions and their implementations

---

## 5. Smarter Backend Logic Generation

**Priority**: Medium
**Complexity**: High
**Impact**: More complete generated code

### Current State

Backend generator creates route stubs:

```typescript
// Generated stub
export async function loginEndpoint(req: Request, res: Response) {
  // TODO: Implement login logic
  res.json({ message: 'Not implemented' });
}
```

### Enhancement

Fully implement the logic from `implementation.steps`:

```yaml
implementation:
  steps:
    - id: validate-request
      action: validate-schema
    - id: find-user
      action: database-query
      database: users
      query: { type: findOne, filter: { email: "{{ request.body.email }}" }}
    - id: verify-password
      action: crypto-compare
      implementation: bcrypt
```

**Would generate:**

```typescript
export async function loginEndpoint(req: Request, res: Response) {
  try {
    // Step 1: Validate request
    const validation = validateSchema(req.body, loginSchema);
    if (!validation.valid) {
      return res.status(400).json({ message: 'Validation failed', errors: validation.errors });
    }

    // Step 2: Find user
    const user = await prisma.users.findUnique({
      where: { email: req.body.email }
    });
    if (!user) {
      return res.status(401).json({ message: 'Invalid email or password' });
    }

    // Step 3: Verify password
    const isValid = await bcrypt.compare(req.body.password, user.passwordHash);
    if (!isValid) {
      return res.status(401).json({ message: 'Invalid email or password' });
    }

    // Step 4: Generate token
    const token = jwt.sign(
      { userId: user.id, email: user.email },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({ token, user: { id: user.id, email: user.email, name: user.name }});
  } catch (error) {
    res.status(500).json({ message: 'Internal server error' });
  }
}
```

### Implementation Notes

- Create action-to-code mappings for each action type
- Template generation for common patterns
- Handle error cases and status codes
- Generate proper imports and dependencies
- Support custom action types via plugins

---

## 6. Docker Compose Orchestration Generator

**Priority**: High (but simple)
**Complexity**: Low
**Impact**: One-command project startup

### Concept

Generate `docker-compose.yml` to orchestrate all stack components.

### Example Output

```yaml
version: '3.8'

services:
  frontend:
    build: ./web-app
    ports:
      - "5173:5173"
    environment:
      - VITE_API_URL=http://localhost:3000
    depends_on:
      - backend

  backend:
    build: ./api
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://postgres:postgres@database:5432/myapp
      - JWT_SECRET=dev-secret-key
    depends_on:
      - database

  database:
    image: postgres:15
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=myapp
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:
```

### Implementation Notes

- Create `DockerComposeGenerator`
- Detect stack components and generate service definitions
- Map technologies to Docker images
- Generate Dockerfiles for each component
- Include volume definitions for data persistence
- Support environment-specific configurations

---

## Implementation Priority

1. **Docker Compose** (high value, low effort) - Include in near-term roadmap
2. **Events System** (high value, high effort) - Major feature for v2
3. **Workflow-to-Docs** (medium value, low effort) - Quick win for v1.1
4. **Nested Workflows** (medium value, medium effort) - v1.2+
5. **Backend Logic Generation** (medium value, high effort) - v2+
6. **Structured Services** (low value, medium effort) - As needed

---

## Notes

- All enhancements should maintain backward compatibility
- Schema changes should be optional (no breaking changes)
- Each feature should have comprehensive tests
- Documentation should be updated with examples
