# Infrastructure

## Deployment Options

SOPHIAClaw supports multiple deployment modes to match different use cases and environments.

```
┌─────────────────────────────────────────────────────────────┐
│                   DEPLOYMENT OPTIONS                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │    Local     │  │   macOS App  │  │    Docker    │      │
│  │ Development  │  │  (Production)│  │  (Flexible)  │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ Linux Server │  │   Cloud VM   │  │   Tailscale  │      │
│  │  (Headless)  │  │  (Remote)    │  │  (Hybrid)    │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

## 1. Local Development

### Overview

Best for development, testing, and single-user scenarios.

### Requirements

- Node.js 22+
- pnpm
- Git

### Installation

```bash
# Clone repository
git clone https://github.com/sophiaclaw/sophiaclaw.git
cd sophiaclaw

# Install dependencies
pnpm install

# Build
pnpm build

# Run gateway
pnpm gateway run
```

### Configuration

```yaml
# ~/.sophiaclaw/config.yaml
gateway:
  mode: local
  bind: "127.0.0.1"
  port: 37521

channels:
  telegram:
    enabled: true
    polling: true # Use polling for local dev
```

### Pros

- ✅ Quick setup
- ✅ No external dependencies
- ✅ Easy debugging
- ✅ File system access

### Cons

- ❌ Not always-on
- ❌ No remote access
- ❌ Process stops when terminal closes

## 2. macOS App

### Overview

Native macOS application with menubar integration.

### Installation

```bash
# Download from GitHub releases
curl -L https://github.com/sophiaclaw/sophiaclaw/releases/latest/download/SOPHIAClaw-macOS.dmg -o SOPHIAClaw.dmg

# Mount and install
open SOPHIAClaw.dmg
cp -r /Volumes/SOPHIAClaw/SOPHIAClaw.app /Applications
```

### Or via Homebrew

```bash
brew install --cask sophiaclaw
```

### Features

- **Menubar App**: Lives in system tray
- **Auto-start**: Launch at login option
- **Native Notifications**: macOS notification center
- **Keychain Integration**: Secure credential storage
- **Automatic Updates**: Sparkle framework

### Architecture

```
┌─────────────────────────────────────────┐
│         SOPHIAClaw macOS App              │
│  ┌──────────┐  ┌──────────┐            │
│  │  SwiftUI │  │  MenuBar │            │
│  │   View   │  │ Controller│            │
│  └────┬─────┘  └────┬─────┘            │
│       │             │                  │
│       └──────┬──────┘                  │
│              ▼                         │
│  ┌──────────────────────────┐          │
│  │   Native Bridge (Swift)  │          │
│  │   - Keychain access      │          │
│  │   - File system          │          │
│  │   - Notifications        │          │
│  └────────────┬─────────────┘          │
└───────────────┼─────────────────────────┘
                │
                ▼ Node.js Runtime
┌─────────────────────────────────────────┐
│         Gateway Service                 │
│         (Bundled Node binary)           │
└─────────────────────────────────────────┘
```

### Configuration

App-specific config location:

```
~/Library/Application Support/SOPHIAClaw/
├── config.yaml
├── credentials/
└── logs/
```

### Pros

- ✅ Native macOS experience
- ✅ Always running
- ✅ Secure credential storage
- ✅ Automatic updates
- ✅ Professional appearance

### Cons

- ❌ macOS only
- ❌ Larger bundle size

## 3. Docker Deployment

### Overview

Containerized deployment for consistency and portability.

### Docker Compose

```yaml
# docker-compose.yml
version: "3.8"

services:
  sophiaclaw:
    image: sophiaclaw/gateway:latest
    container_name: sophiaclaw
    restart: unless-stopped

    ports:
      - "37521:37521"

    volumes:
      - ./data:/home/sophiaclaw/.sophiaclaw
      - /var/run/docker.sock:/var/run/docker.sock # For Docker-in-Docker tools

    environment:
      - NODE_ENV=production
      - SOPHIACLAW_TOKEN=${SOPHIACLAW_TOKEN}
      - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}

    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:37521/health"]
      interval: 30s
      timeout: 10s
      retries: 3
```

### Dockerfile

```dockerfile
FROM node:22-alpine

# Install dependencies
RUN apk add --no-cache git python3 make g++

# Create user
RUN addgroup -g 1000 sophiaclaw && \
    adduser -u 1000 -G sophiaclaw -s /bin/sh -D sophiaclaw

WORKDIR /app

# Copy package files
COPY package*.json pnpm-lock.yaml ./

# Install dependencies
RUN npm install -g pnpm && pnpm install --frozen-lockfile

# Copy source
COPY . .

# Build
RUN pnpm build

# Change ownership
RUN chown -R sophiaclaw:sophiaclaw /app

USER sophiaclaw

EXPOSE 37521

CMD ["pnpm", "gateway", "run"]
```

### Building

```bash
# Build image
docker build -t sophiaclaw:latest .

# Run
docker run -d \
  -p 37521:37521 \
  -v $(pwd)/data:/home/sophiaclaw/.sophiaclaw \
  -e SOPHIACLAW_TOKEN=$SOPHIACLAW_TOKEN \
  --name sophiaclaw \
  sophiaclaw:latest
```

### Kubernetes (Advanced)

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sophiaclaw
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sophiaclaw
  template:
    metadata:
      labels:
        app: sophiaclaw
    spec:
      containers:
        - name: gateway
          image: sophiaclaw/gateway:latest
          ports:
            - containerPort: 37521
          env:
            - name: SOPHIACLAW_TOKEN
              valueFrom:
                secretKeyRef:
                  name: sophiaclaw-secrets
                  key: sophiaclaw-token
          volumeMounts:
            - name: data
              mountPath: /home/sophiaclaw/.sophiaclaw
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: sophiaclaw-data
```

### Pros

- ✅ Consistent environment
- ✅ Easy scaling
- ✅ Isolation
- ✅ Version pinning
- ✅ CI/CD friendly

### Cons

- ❌ Slightly more complex setup
- ❌ Resource overhead
- ❌ File system access limited

## 4. Linux Server

### Overview

Headless deployment on Linux servers (VPS, bare metal, etc.).

### System Requirements

- Ubuntu 22.04+ / Debian 12+ / RHEL 9+
- 4GB RAM minimum
- 10GB storage
- Systemd

### Installation

```bash
# Install Node.js 22
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt-get install -y nodejs

# Install pnpm
npm install -g pnpm

# Install SOPHIAClaw
npm install -g sophiaclaw

# Verify
sophiaclaw --version
```

### Systemd Service

```ini
# /etc/systemd/system/sophiaclaw.service
[Unit]
Description=SOPHIAClaw Gateway
After=network.target

[Service]
Type=simple
User=sophiaclaw
Group=sophiaclaw
WorkingDirectory=/home/sophiaclaw
ExecStart=/usr/bin/sophiaclaw gateway run
Restart=always
RestartSec=10
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
```

### Service Management

```bash
# Enable service
sudo systemctl enable sophiaclaw

# Start
sudo systemctl start sophiaclaw

# Check status
sudo systemctl status sophiaclaw

# View logs
sudo journalctl -u sophiaclaw -f
```

### Reverse Proxy (Nginx)

```nginx
# /etc/nginx/sites-available/sophiaclaw
server {
    listen 443 ssl http2;
    server_name gateway.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://127.0.0.1:37521;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

### Pros

- ✅ Production-ready
- ✅ Always-on
- ✅ Service management
- ✅ Reverse proxy support
- ✅ Log aggregation

### Cons

- ❌ Requires Linux knowledge
- ❌ Server maintenance

## 5. Cloud VM Deployment

### AWS EC2

```bash
# Launch instance
aws ec2 run-instances \
  --image-id ami-0c02fb55956c7d316 \
  --instance-type t3.medium \
  --key-name my-key \
  --security-group-ids sg-xxxxx

# User data script
#!/bin/bash
apt-get update
apt-get install -y nodejs npm
npm install -g sophiaclaw
sophiaclaw gateway run &
```

### Google Cloud Platform

```bash
# Create VM
gcloud compute instances create sophiaclaw \
  --zone=us-central1-a \
  --machine-type=e2-medium \
  --image-family=ubuntu-2204-lts \
  --image-project=ubuntu-os-cloud

# SSH and install
gcloud compute ssh sophiaclaw --zone=us-central1-a
```

### Azure

```bash
# Create VM
az vm create \
  --resource-group myResourceGroup \
  --name sophiaclaw \
  --image Ubuntu2204 \
  --size Standard_B2s \
  --generate-ssh-keys
```

### Pros

- ✅ Scalable
- ✅ Managed infrastructure
- ✅ Global availability
- ✅ Backup/restore options

### Cons

- ❌ Ongoing cost
- ❌ Cloud dependency
- ❌ Network latency

## 6. Tailscale Hybrid

### Overview

Combine local gateway with Tailscale for secure remote access.

### Architecture

```
┌──────────────┐      Tailnet       ┌──────────────┐
│   Your Phone │◄──────────────────►│  Home/MAC    │
│   (Anywhere) │     WireGuard      │  (Gateway)   │
└──────────────┘                    └──────────────┘
         │                                 │
         │ Telegram/Discord                │ Local File
         │                                 │ System
         ▼                                 ▼
┌──────────────┐                    ┌──────────────┐
│  Telegram    │                    │  ~/.sophiaclaw│
│  Servers     │                    │  /workspace  │
└──────────────┘                    └──────────────┘
```

### Setup

```bash
# Install Tailscale
curl -fsSL https://tailscale.com/install.sh | sh

# Authenticate
tailscale up

# Get Tailscale IP
TAILSCALE_IP=$(tailscale ip -4)

# Configure SOPHIAClaw to bind to Tailscale interface
sophiaclaw config set gateway.bind $TAILSCALE_IP
```

### Pros

- ✅ Secure remote access
- ✅ No port forwarding
- ✅ End-to-end encryption
- ✅ Works behind NAT
- ✅ MagicDNS for easy addressing

### Cons

- ❌ Requires Tailscale account
- ❌ Both devices need Tailscale

## Deployment Comparison

| Feature            | Local  | macOS App | Docker | Linux Server | Cloud VM | Tailscale |
| ------------------ | ------ | --------- | ------ | ------------ | -------- | --------- |
| Ease of setup      | ⭐⭐⭐ | ⭐⭐⭐    | ⭐⭐   | ⭐⭐         | ⭐       | ⭐⭐      |
| Always-on          | ❌     | ✅        | ✅     | ✅           | ✅       | ✅        |
| Remote access      | ❌     | ❌        | ⚠️     | ✅           | ✅       | ✅        |
| Production ready   | ❌     | ✅        | ✅     | ✅           | ✅       | ✅        |
| File system access | ✅     | ✅        | ⚠️     | ✅           | ✅       | ✅        |
| Auto-updates       | ❌     | ✅        | ❌     | ❌           | ❌       | ❌        |
| Cost               | Free   | Free      | Free   | Hardware     | $$       | Free tier |

## Backup and Recovery

### Backup Strategy

```bash
# Automated daily backup
0 2 * * * /usr/local/bin/sophiaclaw-backup.sh

# Backup script
#!/bin/bash
BACKUP_DIR="/backup/sophiaclaw/$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"

# Config and data
tar czf "$BACKUP_DIR/config.tar.gz" ~/.sophiaclaw/config.yaml ~/.sophiaclaw/credentials/

# Sessions
tar czf "$BACKUP_DIR/sessions.tar.gz" ~/.sophiaclaw/sessions/

# Workspace
tar czf "$BACKUP_DIR/workspace.tar.gz" ~/.sophiaclaw/workspace/

# Upload to S3 (optional)
aws s3 sync "$BACKUP_DIR" s3://my-backups/sophiaclaw/
```

### Recovery

```bash
# Restore from backup
tar xzf config.tar.gz -C ~
tar xzf sessions.tar.gz -C ~
tar xzf workspace.tar.gz -C ~

# Restart gateway
sophiaclaw gateway restart
```

## Monitoring

### Health Checks

```bash
# Built-in health endpoint
curl http://localhost:37521/health

# JSON output
{
  "status": "healthy",
  "version": "2.0.0",
  "uptime": 86400,
  "memory": {
    "used": "256MB",
    "total": "512MB"
  },
  "channels": {
    "telegram": "connected",
    "discord": "connected"
  }
}
```

### Metrics (Prometheus)

```yaml
# Enable metrics endpoint
metrics:
  enabled: true
  port: 9090
  path: /metrics
```

### Alerting Rules

```yaml
# Alert when gateway down
- alert: GatewayDown
  expr: up{job="sophiaclaw"} == 0
  for: 5m
  labels:
    severity: critical
```

## Troubleshooting

### Common Issues

| Issue                  | Solution                                                       |
| ---------------------- | -------------------------------------------------------------- | -------------- |
| Port 37521 in use      | `lsof -ti:37521                                                | xargs kill -9` |
| Permission denied      | Check file ownership: `chown -R $USER ~/.sophiaclaw`           |
| Out of memory          | Increase Node heap: `NODE_OPTIONS="--max-old-space-size=4096"` |
| Channel not connecting | Check credentials and network                                  |
| High CPU usage         | Enable session compaction, purpleuce token limit               |
