# Bot Spawner Service

## Overview

The Bot Spawner service is a microservice responsible for managing bot lifecycle operations in the BuzzTrail platform. It provides API endpoints for spawning, monitoring, and managing AI bot instances that integrate with the LiveKit/Tavus infrastructure.

**Tech Stack:**
- Node.js 20 (Express.js)
- Python 3.11 (for bot runtime)
- Supabase (database)
- NX (monorepo build system)

**Port:** 3001 (default, configurable via `PORT` environment variable)

---

## Prerequisites

### Local Development

To develop and run the bot-spawner service locally, you need:

1. **Node.js 20.x**
   ```bash
   node --version  # Should output v20.x.x
   ```
   Install from: https://nodejs.org/

2. **pnpm**
   ```bash
   pnpm --version  # Should output 10.x or higher
   ```
   Install:
   ```bash
   npm install -g pnpm
   ```

3. **Python 3.11** (for bot runtime)
   ```bash
   python3.11 --version  # Should output Python 3.11.x
   ```
   Install via:
   - **macOS**: `brew install python@3.11`
   - **Ubuntu/Debian**:
     ```bash
     sudo add-apt-repository ppa:deadsnakes/ppa
     sudo apt update
     sudo apt install python3.11 python3.11-venv python3.11-dev
     ```

4. **Docker** (for containerized builds and deployment)
   ```bash
   docker --version  # Should output Docker version 20.x or higher
   ```
   Install from: https://www.docker.com/products/docker-desktop

### Environment Variables

Create a `.env` file in the repository root or export these variables:

```bash
# Supabase Configuration (required)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-supabase-anon-key

# Service Configuration (optional)
PORT=3001                    # Service port (default: 3001)
NODE_ENV=development         # Environment (development|production)
PYTHON_VERSION=3.11          # Python runtime version (set automatically in Docker)
```

---

## Local Development

### 1. Install Dependencies

From the **repository root**:

```bash
pnpm install
```

This installs all dependencies for the entire monorepo.

### 2. Build the Service

```bash
pnpm nx build bot-spawner
```

Output will be in: `dist/apps/bot-spawner/`

### 3. Run the Service

#### Development Mode (with hot reload):

```bash
pnpm nx serve bot-spawner
```

The service will start on port 3001 (or `PORT` env var if set).

#### Production Mode:

```bash
# Build first
pnpm nx build bot-spawner

# Run the built output
node dist/apps/bot-spawner/main.js
```

### 4. Verify the Service

**Health Check Endpoint:**

```bash
curl http://localhost:3001/health
```

Expected response:
```json
{
  "status": "healthy",
  "timestamp": "2025-10-21T...",
  "bots_active": 0,
  "python_version": "3.11",
  "service": "bot-spawner",
  "node_version": "v20.x.x"
}
```

**Root Endpoint:**

```bash
curl http://localhost:3001/
```

Expected response:
```json
{
  "service": "bot-spawner",
  "version": "1.0.0",
  "status": "running",
  "endpoints": {
    "health": "/health"
  }
}
```

---

## Docker Build

### Build the Docker Image

From the **repository root** (important - the Dockerfile expects to be run from the monorepo root):

```bash
docker build -f apps/bot-spawner/Dockerfile -t bot-spawner .
```

**Build time:** Approximately 5-10 minutes (depending on your machine and network)

**Image size:** Approximately 1.5-2GB (includes Node.js 20, Python 3.11, and all dependencies)

### Run the Docker Container

```bash
docker run -p 3001:3001 \
  -e SUPABASE_URL=https://your-project.supabase.co \
  -e SUPABASE_KEY=your-supabase-key \
  bot-spawner
```

### Test the Dockerized Service

```bash
# Health check
curl http://localhost:3001/health

# Verify Python version in container
docker exec -it <container-id> python3.11 --version
```

### Multi-Architecture Build (for Railway/ARM64)

If deploying to Railway or other platforms that use ARM64:

```bash
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -f apps/bot-spawner/Dockerfile \
  -t bot-spawner:latest \
  .
```

---

## Dockerfile Architecture

The Dockerfile is optimized for fast iteration using layer caching:

### Layer Structure

1. **System Packages** (rarely changes)
   - Base: Ubuntu 24.04
   - Build tools: curl, ca-certificates, gnupg
   - Cached indefinitely unless base image updates

2. **Node.js 20** (rarely changes)
   - Installed from NodeSource official repository
   - Verified installation
   - Cached until Node.js version changes

3. **Python 3.11** (rarely changes)
   - Installed from deadsnakes PPA (validated in Phase 0 diagnostic)
   - Includes: python3.11-venv, python3.11-dev
   - Proven to work on Railway platform
   - Cached until Python version changes

4. **pnpm** (rarely changes)
   - Installed globally via npm
   - Cached until pnpm version changes

5. **Dependencies** (changes occasionally)
   - Only copies `package.json` and `pnpm-lock.yaml`
   - Runs `pnpm install --frozen-lockfile`
   - **Rebuilds only when dependencies change**
   - This is where most build time is spent

6. **Application Code** (changes frequently)
   - Copies entire source tree
   - **Rebuilds on every code change**
   - Previous layers remain cached

7. **Build Application** (changes frequently)
   - Runs `pnpm nx build bot-spawner`
   - Output: `dist/apps/bot-spawner/`
   - Fast due to incremental NX builds

### Build Optimization Tips

1. **Only change code?** Layers 1-5 are cached → Fast build (~1-2 minutes)
2. **Added dependencies?** Layers 1-4 are cached → Medium build (~5-7 minutes)
3. **Changed Node/Python version?** Full rebuild → Slow build (~10-15 minutes)

### .dockerignore

The `.dockerignore` file excludes:
- `node_modules` (reinstalled in Docker)
- `dist` (rebuilt in Docker)
- `.git`, `.claude`, `docs` (not needed at runtime)
- Test files (`*.test.ts`, `*.spec.ts`)
- IDE files (`.vscode`, `.idea`)

This reduces build context from ~2GB to ~500MB, speeding up builds significantly.

---

## Deployment

### Railway Deployment

The bot-spawner service is designed for Railway deployment with the following configuration:

**Build Configuration:**
- Build Command: (handled by Dockerfile)
- Start Command: (handled by Dockerfile CMD)

**Environment Variables:**
Set these in the Railway dashboard or via CLI:
```bash
SUPABASE_URL=your-supabase-url
SUPABASE_KEY=your-supabase-key
PORT=3001  # Railway will override this with $PORT
```

**Health Check:**
Railway will automatically health-check `/health` endpoint.

**Deployment via CLI:**
```bash
# Link to Railway project (first time only)
railway link

# Deploy
railway up
```

**Deployment via GitHub:**
Push to the connected branch, and Railway will auto-deploy.

### Manual Deployment (Other Platforms)

For platforms like AWS ECS, Google Cloud Run, Azure Container Apps:

1. Build and push the image:
   ```bash
   docker build -f apps/bot-spawner/Dockerfile -t your-registry/bot-spawner .
   docker push your-registry/bot-spawner
   ```

2. Configure environment variables in your platform
3. Expose port 3001 (or configure `PORT` env var)
4. Set health check endpoint: `/health`

---

## Troubleshooting

### Build Issues

**Issue: `pnpm install` fails with "lockfile not up to date"`**

Solution:
```bash
# From repository root
pnpm install
# Commit the updated pnpm-lock.yaml
```

**Issue: Docker build fails at "COPY package.json"`**

Solution: Ensure you're running the build from the repository root, not the app directory:
```bash
# Wrong:
cd apps/bot-spawner && docker build -f Dockerfile .

# Correct:
docker build -f apps/bot-spawner/Dockerfile .
```

**Issue: Build context is too large (>1GB)****

Solution: Check your `.dockerignore` is properly excluding:
```bash
# Should be excluded:
node_modules/
dist/
.git/
```

### Runtime Issues

**Issue: Service starts but health check fails with "Database connection failed"`**

Solution: Verify Supabase credentials:
```bash
# Check environment variables are set
echo $SUPABASE_URL
echo $SUPABASE_KEY

# Test Supabase connection manually
curl "${SUPABASE_URL}/rest/v1/active_bots?select=count" \
  -H "apikey: ${SUPABASE_KEY}"
```

**Issue: Python 3.11 not found in container**

Solution: Verify Python installation in the Docker image:
```bash
docker run -it bot-spawner python3.11 --version
# Should output: Python 3.11.x
```

If Python is missing, rebuild the Docker image (layer caching may have caused issues).

**Issue: Port 3001 already in use**

Solution: Use a different port:
```bash
PORT=3002 node dist/apps/bot-spawner/main.js
# Or for Docker:
docker run -p 3002:3001 -e PORT=3001 bot-spawner
```

**Issue: NX build fails with "Cannot find module"`**

Solution: Ensure all dependencies are installed:
```bash
pnpm install
pnpm nx reset  # Clear NX cache
pnpm nx build bot-spawner
```

### Docker Build Performance

**Issue: Docker build is very slow (>15 minutes)**

Solutions:
1. Use BuildKit for parallel layer builds:
   ```bash
   DOCKER_BUILDKIT=1 docker build -f apps/bot-spawner/Dockerfile .
   ```

2. Pre-pull the base image:
   ```bash
   docker pull ubuntu:24.04
   ```

3. Check if `.dockerignore` is properly excluding large files:
   ```bash
   # Check build context size
   tar -czf - . | wc -c
   # Should be <500MB with proper .dockerignore
   ```

4. Use layer caching from previous builds (automatic in Docker)

---

## Development Workflow

### Making Code Changes

1. **Edit source files** in `apps/bot-spawner/src/`
2. **Rebuild**: `pnpm nx build bot-spawner`
3. **Test locally**: `node dist/apps/bot-spawner/main.js`
4. **Test in Docker** (optional):
   ```bash
   docker build -f apps/bot-spawner/Dockerfile -t bot-spawner .
   docker run -p 3001:3001 bot-spawner
   ```
5. **Commit and push** to deploy

### Adding Dependencies

1. **Install the package**:
   ```bash
   pnpm add <package-name>
   ```

2. **Update lockfile**:
   ```bash
   pnpm install
   ```

3. **Rebuild Docker image** (dependency layer will be invalidated):
   ```bash
   docker build -f apps/bot-spawner/Dockerfile -t bot-spawner .
   ```

### Testing Changes

**Unit Tests:**
```bash
pnpm nx test bot-spawner
```

**Integration Tests:**
```bash
# Start service
pnpm nx serve bot-spawner

# In another terminal, run tests
curl http://localhost:3001/health
```

**Docker Tests:**
```bash
# Build image
docker build -f apps/bot-spawner/Dockerfile -t bot-spawner .

# Run container
docker run -p 3001:3001 \
  -e SUPABASE_URL=$SUPABASE_URL \
  -e SUPABASE_KEY=$SUPABASE_KEY \
  bot-spawner

# Test endpoints
curl http://localhost:3001/health
```

---

## Architecture Notes

### Why Ubuntu 24.04?

Ubuntu 24.04 was chosen as the base image because:
1. **Validated in Phase 0**: The diagnostic service confirmed Python 3.11 + asyncio works perfectly on Railway with Ubuntu 24.04
2. **Deadsnakes PPA Support**: Easy installation of Python 3.11 via deadsnakes PPA
3. **Production Proven**: The slide-system service successfully uses the same configuration
4. **Long-term Support**: Ubuntu 24.04 LTS provides stability and security updates

### Why Python 3.11?

Python 3.11 was chosen over 3.12/3.13 because:
1. **Railway Compatibility**: Phase 0 diagnostic validated asyncio works correctly
2. **No Asyncio Hangs**: Python 3.13 has known asyncio initialization issues on Railway
3. **Mature Ecosystem**: Better library compatibility than 3.12/3.13
4. **Production Proven**: voice-agent service uses Python 3.11 successfully

### Multi-Runtime Strategy

The service uses both Node.js and Python:
- **Node.js 20**: API server (Express), Supabase client, NX build tools
- **Python 3.11**: Bot runtime for AI agents (will be used by bot spawning logic)

This dual-runtime approach allows the service to:
1. Serve a fast, event-driven API (Node.js)
2. Execute Python-based bot logic (Python 3.11)
3. Maintain compatibility with existing bot infrastructure

---

## Project Structure

```
apps/bot-spawner/
├── Dockerfile              # Multi-runtime Docker image
├── .dockerignore          # Build context exclusions
├── README.md              # This file
├── project.json           # NX build configuration
├── tsconfig.json          # TypeScript configuration
├── tsconfig.app.json      # App-specific TS config
└── src/
    ├── main.ts            # Express server entry point
    └── assets/            # Static assets
```

---

## Reference Materials

- **Phase 0 Diagnostic**: `.claude/epics/bot-spawner-extraction/diagnostic/`
  - Validated Python 3.11 + asyncio on Railway
  - Proven Ubuntu 24.04 configuration
- **Phase 0 Results**: `.claude/epics/bot-spawner-extraction/phase0-python-results.md`
  - Comprehensive test results
  - Performance benchmarks
- **Slide System Dockerfile**: `apps/slide-system/Dockerfile`
  - Production example with Python 3.11 + Node.js 20
  - Similar multi-runtime configuration

---

## Contributing

When making changes to the bot-spawner service:

1. **Test locally first** using `pnpm nx serve bot-spawner`
2. **Test Docker build** before pushing
3. **Update this README** if you change build/deployment processes
4. **Document environment variables** in this README
5. **Add troubleshooting notes** for common issues you encounter

---

## Support

For issues or questions:
- **Epic**: bot-spawner-extraction epic worktree
- **Issue**: #162 Stream B (Dockerfile & Build Configuration)
- **Phase 0 Diagnostic**: Validated configuration in `.claude/epics/bot-spawner-extraction/diagnostic/`
