# CI/CD Setup Guide

**Project**: CA Grow Ops Manager  
**Platform**: Forgejo Actions  
**Target**: nexus-vector

---

## Overview

This project uses **Forgejo Actions** (GitHub Actions compatible) for automated testing and deployment. The CI/CD pipeline automatically:

1. **Tests** code on every push and pull request
2. **Deploys** to production on push to `main` branch
3. **Runs migrations** automatically
4. **Performs health checks** after deployment

---

## Workflows

### 1. Test Workflow (`.forgejo/workflows/test.yml`)

**Triggers**:

- Push to `main` or `develop` branches
- Pull requests to `main`

**Jobs**:

- **Backend Tests**:
  - Spins up PostgreSQL and Redis services
  - Runs Prisma migrations
  - Executes Jest tests
  - Runs ESLint
  
- **Frontend Tests**:
  - Runs Vitest tests
  - Runs ESLint
  - Builds production bundle

**Duration**: ~5-10 minutes

---

### 2. Deploy Workflow (`.forgejo/workflows/deploy.yml`)

> [!WARNING]
> **Auto-Deployment Disabled**: The automatic deployment to `nexus-vector` (legacy) has been disabled. Deployments are now verified manually using the `./deploy.sh` script.

**Status**: Manual Trigger Only

**Steps**:

1. Prints information about usage of `./deploy.sh` for Test (`veridian`) and Prod (`tangible-aacorn`).

---

## Setup Instructions

### Step 1: Add SSH Private Key to Forgejo Secrets

The deployment workflow needs SSH access to nexus-vector.

#### 1.1 Generate SSH Key (if needed)

```bash
# On your local machine or nexus-vector
ssh-keygen -t ed25519 -C "forgejo-deploy" -f ~/.ssh/forgejo_deploy
```

#### 1.2 Add Public Key to nexus-vector

```bash
# Copy public key to nexus-vector
ssh admin@nexus-vector "echo '$(cat ~/.ssh/forgejo_deploy.pub)' >> ~/.ssh/authorized_keys"

# Test connection
ssh -i ~/.ssh/forgejo_deploy admin@nexus-vector "echo 'Connection successful'"
```

#### 1.3 Add Private Key to Forgejo Secrets

1. Navigate to repository: <https://git.runfoo.run/runfoo/ca-grow-ops-manager>
2. Go to **Settings** → **Secrets**
3. Click **Add Secret**
4. Name: `SSH_PRIVATE_KEY`
5. Value: Paste contents of `~/.ssh/forgejo_deploy` (the **private** key)
6. Click **Add Secret**

---

### Step 2: Enable Forgejo Actions

#### 2.1 Check Runner Status

```bash
# On nexus-vector
docker ps | grep runner
```

You should see:

```text
forgejo-runner   code.forgejo.org/forgejo/runner:3.3.0
```

#### 2.2 Enable Actions in Repository

1. Navigate to: <https://git.runfoo.run/runfoo/ca-grow-ops-manager>
2. Go to **Settings** → **Actions**
3. Enable **Actions** (if not already enabled)
4. Set **Default workflow permissions** to **Read and write**

---

### Step 3: Test the Workflows

#### 3.1 Test Workflow (Manual Trigger)

```bash
# Make a small change and push
cd /Users/ten/ANTIGRAVITY/777wolfpack/ca-grow-ops-manager
echo "# Test CI/CD" >> README.md
git add README.md
git commit -m "test: Trigger CI/CD pipeline"
git push origin main
```

#### 3.2 Monitor Workflow Execution

1. Go to: <https://git.runfoo.run/runfoo/ca-grow-ops-manager/actions>
2. Click on the latest workflow run
3. Watch the logs in real-time

**Expected**:

- ✅ Test workflow completes successfully
- ✅ Deploy workflow starts automatically
- ✅ Deployment completes with health check

---

### Step 4: Verify Deployment

```bash
# SSH to nexus-vector
ssh admin@nexus-vector

# Check service status
cd /srv/containers/ca-grow-ops-manager
docker compose ps

# Check health
curl http://localhost:8010/api/healthz

# View logs
docker compose logs -f --tail=50
```

---

## Workflow Details

### Test Workflow

```yaml
# Runs on: ubuntu-latest
# Services: PostgreSQL 15, Redis 7
# Node.js: 20.x

Backend:
  - npm ci
  - prisma generate
  - prisma migrate deploy
  - npm test
  - npm run lint

Frontend:
  - npm ci
  - npm test
  - npm run lint
  - npm run build
```

### Deploy Workflow

```yaml
# Runs on: ubuntu-latest
# Target: nexus-vector via SSH

Steps:
  1. git pull origin main
  2. docker compose build --no-cache
  3. docker compose up -d db redis
  4. docker compose run --rm backend npx prisma migrate deploy
  5. docker compose up -d
  6. curl http://localhost:8010/api/healthz
```

---

## Troubleshooting

### Workflow Fails: "Permission denied (publickey)"

**Cause**: SSH private key not configured or incorrect

**Solution**:

1. Verify secret exists: Settings → Secrets → `SSH_PRIVATE_KEY`
2. Verify public key is in `~/.ssh/authorized_keys` on nexus-vector
3. Test SSH connection manually

---

### Workflow Fails: "Database migration failed"

**Cause**: Database schema conflict or connection issue

**Solution**:

```bash
# SSH to nexus-vector
ssh admin@nexus-vector
cd /srv/containers/ca-grow-ops-manager

# Check database status
docker compose logs db

# Reset database (⚠️ DESTRUCTIVE)
docker compose down -v
docker compose up -d db
docker compose exec backend npx prisma migrate deploy
```

---

### Workflow Fails: "Health check failed"

**Cause**: Service didn't start properly

**Solution**:

```bash
# Check container logs
docker compose logs backend
docker compose logs frontend

# Check container status
docker compose ps

# Restart services
docker compose restart
```

---

### Workflow Stuck: "Waiting for runner"

**Cause**: Forgejo runner is offline or busy

**Solution**:

```bash
# Check runner status
docker ps | grep runner

# Restart runner (if needed)
docker restart forgejo-runner

# Check runner logs
docker logs forgejo-runner
```

---

## Best Practices

### Branch Strategy

- **`main`**: Production branch (auto-deploys)
- **`develop`**: Development branch (tests only)
- **Feature branches**: `feature/task-name` (tests only)

### Workflow

```bash
# 1. Create feature branch
git checkout -b feature/add-authentication

# 2. Make changes and commit
git add .
git commit -m "feat: Add JWT authentication"

# 3. Push and create PR
git push origin feature/add-authentication

# 4. Tests run automatically on PR

# 5. Merge to main → Auto-deploys
```

### Commit Messages

Follow conventional commits:

- `feat:` New feature
- `fix:` Bug fix
- `docs:` Documentation
- `test:` Tests
- `chore:` Maintenance

---

## Monitoring Deployments

### View Deployment History

1. Go to: <https://git.runfoo.run/runfoo/ca-grow-ops-manager/actions>
2. Filter by **Deploy to Production**
3. View logs for each deployment

### Rollback

If deployment fails:

```bash
# SSH to nexus-vector
ssh admin@nexus-vector
cd /srv/containers/ca-grow-ops-manager

# Checkout previous commit
git log --oneline -n 5
git checkout <previous-commit-hash>

# Rebuild and restart
docker compose build
docker compose up -d
```

---

## Advanced Configuration

### Environment-Specific Deployments

To add staging environment:

1. Create `.forgejo/workflows/deploy-staging.yml`
2. Change target branch to `develop`
3. Change deployment path to `/srv/containers/ca-grow-ops-manager-staging`
4. Use different port (e.g., 8011)

### Notifications

Add Slack/Discord notifications:

```yaml
- name: Notify deployment
  if: always()
  run: |
    curl -X POST ${{ secrets.SLACK_WEBHOOK }} \
      -H 'Content-Type: application/json' \
      -d '{"text":"Deployment ${{ job.status }}"}'
```

---

## Security Checklist

- [x] SSH private key stored as Forgejo secret
- [x] Secrets not committed to repository
- [x] Workflow runs on trusted runner
- [x] Database migrations run before deployment
- [x] Health check verifies deployment
- [ ] Add deployment approval for production (optional)
- [ ] Add rollback automation (optional)

---

## Next Steps

1. ✅ Set up SSH key and Forgejo secret
2. ✅ Enable Actions in repository
3. ✅ Push code to trigger first deployment
4. ⏭️ Monitor deployment logs
5. ⏭️ Verify service health
6. ⏭️ Set up monitoring alerts (optional)

---

**Created**: 2025-12-08  
**Last Updated**: 2025-12-08  
**Maintained By**: Development team
