> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Staging Environment Setup Guide

> Version: 2.0.0 Last Updated: 2026-01-15 Purpose: Create a Supabase staging environment using branches to validate migrations before production.

**Version:** 2.0.0\
**Last Updated:** 2026-01-15\
**Purpose:** Create a Supabase staging environment using branches to validate migrations before production.

***

## Overview

This guide uses **Supabase Branches** (recommended) for staging instead of creating a separate project. Branches provide:

* ✅ Isolated database environment
* ✅ Automatic migration sync via GitHub
* ✅ Cost-effective (included in plan)
* ✅ Easy switching between environments

**Alternative:** If branching is not available on your plan, see [Option B: Separate Project](#option-b-create-separate-project-alternative).

***

## Option A: Use Supabase Branch (Recommended)

### Step 1: Verify Prerequisites

**Use MCP:**

```typescript theme={null}
// Check current project
mcp_supabase_get_project_url()
// Expected: https://<project-ref>.supabase.co

// List existing branches
mcp_supabase_list_branches()
// Expected: Shows existing branches (if any)
```

**Use CLI:**

```bash theme={null}
# Verify CLI installed
supabase --version
# Expected: Supabase CLI 1.x.x

# Verify logged in
supabase projects list
# Expected: Lists your projects
```

### Step 2: Create Persistent Staging Branch

**Use CLI (Required for creation):**

```bash theme={null}
# Create persistent staging branch
supabase --experimental branches create --persistent staging

# Note the branch project ID from output
# Example: Created branch staging with project ID: <branch-project-id>
```

### Step 3: Verify Branch Creation

**Use MCP:**

```typescript theme={null}
// List branches to confirm creation
mcp_supabase_list_branches()
// Expected: Shows 'staging' with status 'active'
```

### Step 4: Link Local Project to Staging Branch

**Use CLI:**

```bash theme={null}
# Link to staging branch
supabase link --project-ref <staging-branch-project-id>

# Verify link
supabase status
# Expected: Shows linked to staging branch
```

### Step 5: Apply All Migrations

**Use CLI:**

```bash theme={null}
# Push all migrations to staging branch
supabase db push

# Expected: All 393+ migrations apply successfully
```

**Use MCP to verify:**

```typescript theme={null}
// List applied migrations
mcp_supabase_list_migrations()
// Expected: 393+ migrations listed
```

### Step 6: Verify Database State

**Use MCP:**

```typescript theme={null}
// List all tables
mcp_supabase_list_tables({ schemas: ["public"] })

// Verify table counts by module
mcp_supabase_execute_sql({
  query: `
    SELECT 
      CASE 
        WHEN table_name LIKE 'pf_%' THEN 'PF'
        WHEN table_name LIKE 'hr_%' THEN 'HR'
        WHEN table_name LIKE 'fa_%' THEN 'FA'
        WHEN table_name LIKE 'fw_%' THEN 'FW'
        WHEN table_name LIKE 'rh_%' THEN 'RH'
        WHEN table_name LIKE 'gr_%' THEN 'GR'
        WHEN table_name LIKE 'fm_%' THEN 'FM'
        WHEN table_name LIKE 'lo_%' THEN 'LO'
        WHEN table_name LIKE 'it_%' THEN 'IT'
        ELSE 'Other'
      END as module,
      COUNT(*) as table_count
    FROM information_schema.tables
    WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
    GROUP BY module
    ORDER BY module;
  `
})
```

**Expected Table Counts:**

| Module                | Prefix | Expected  |
| --------------------- | ------ | --------- |
| Platform Foundation   | pf\_   | \~74      |
| Human Resources       | hr\_   | \~94      |
| Finance & Accounting  | fa\_   | \~46      |
| Forms & Workflow      | fw\_   | \~54      |
| Recovery Housing      | rh\_   | \~51      |
| Governance & Risk     | gr\_   | \~49      |
| Facilities Management | fm\_   | \~22      |
| Leadership OS         | lo\_   | \~29      |
| IT Service Management | it\_   | \~35      |
| **Total**             |        | **\~465** |

### Step 7: GitHub Integration Setup (Recommended)

**Purpose:** Auto-deploy migrations when pushing to `staging` Git branch.

**Via Supabase Dashboard:**

1. Go to Project Settings → Integrations → GitHub
2. Click "Connect to GitHub"
3. Authorize repository access
4. Configure branch mapping:
   * `main` Git branch → Supabase `main` project
   * `staging` Git branch → Supabase `staging` branch

**Verify Integration:**

1. Create a test Git branch
2. Add a simple migration
3. Push to Git
4. Check Supabase dashboard for auto-deployment

### Step 8: Set Environment Variable

**For local development:**

```bash theme={null}
# Set staging project ID
export SUPABASE_PROJECT_ID=<staging-branch-project-id>

# Or add to .env.local (don't commit)
echo "SUPABASE_PROJECT_ID=<staging-branch-project-id>" >> .env.local
```

***

## Option B: Create Separate Project (Alternative)

Use this if branching is not available on your Supabase plan.

### Step 1: Create Staging Project

1. Go to [Supabase Dashboard](https://supabase.com/dashboard)

2. Click "New Project"

3. Configure:
   * **Name:** `encoreos-staging`
   * **Database Password:** Generate strong password (save securely)
   * **Region:** Same as production project
   * **Pricing Plan:** Free tier is sufficient for testing

4. Wait for project to be provisioned (\~2 minutes)

### Step 2: Link and Apply Migrations

```bash theme={null}
# Get staging project reference ID from dashboard URL
# https://supabase.com/dashboard/project/{project-ref}

# Link to staging project
supabase link --project-ref <staging-project-ref>

# Apply all migrations
supabase db push

# Verify
supabase migration list
```

### Step 3: Verify Database State

Same as Option A, Step 6.

***

## Quick Verification Checklist

Run these to verify staging is set up correctly:

### MCP Checks

* [ ] `mcp_supabase_list_branches()` shows staging branch
* [ ] `mcp_supabase_list_tables()` returns \~465 tables
* [ ] `mcp_supabase_list_migrations()` shows 393+ migrations
* [ ] `mcp_supabase_get_advisors({ type: "security" })` returns no critical issues

### CLI Checks

* [ ] `supabase status` shows linked to staging
* [ ] `supabase migration list` shows all migrations applied

***

## Troubleshooting

### Issue: Branch creation fails

**Symptom:** `supabase --experimental branches create` returns error

**Solutions:**

1. Check Supabase plan includes branching feature
2. Ensure CLI is latest version: `npm install -g supabase`
3. Verify authentication: `supabase login`

### Issue: Cannot link to branch

**Symptom:** `supabase link --project-ref` fails

**Solutions:**

1. Verify branch project ID is correct (from dashboard or MCP)
2. Check if project exists: `supabase projects list`
3. Re-authenticate if needed: `supabase login`

### Issue: Migration fails with "relation already exists"

**Symptom:** `supabase db push` reports errors

**Solutions:**

1. Some migrations may have been partially applied
2. Check migration history in Supabase dashboard
3. If safe, reset and reapply: `supabase db reset` (WARNING: deletes data)

### Issue: Table counts don't match expected

**Symptom:** MCP returns fewer tables than expected

**Solutions:**

1. Check for migration errors in Supabase dashboard → Database → Migrations
2. Some tables may be in other schemas (check `auth`, `storage`)
3. Verify all migrations applied: `mcp_supabase_list_migrations()`

### Issue: GitHub integration not auto-deploying

**Symptom:** Pushing to Git doesn't trigger migration deployment

**Solutions:**

1. Verify GitHub integration is connected in dashboard
2. Check branch mapping is correct
3. Review webhook delivery logs in GitHub repository settings
4. Ensure migration files are in `supabase/migrations/` directory

***

## Seeding Staging Database

After migrations are applied, seed the staging database with test data.

### Seed File Structure

```
supabase/seeds/
├── base/                  # Core data (run first)
│   ├── 01_organizations.sql
│   ├── 02_users.sql
│   └── 03_sites.sql
└── modules/               # Module data (run after base)
    ├── 04_hr.sql
    ├── 05_fa.sql
    └── ... (06-11 for other modules)
```

### Generate Seed Files

```bash theme={null}
# Generate all seed files
npm run generate:seeds -- --all --orgs 2 --employees 50

# Generate specific module
npm run generate:seeds -- --module hr
```

### Validate Seeds

```bash theme={null}
npm run validate:seeds -- --verbose
```

### Apply Seeds to Staging

```bash theme={null}
# Dry run first (no changes)
npm run db:seed:dev -- --dry-run

# Apply for real
npm run db:seed:dev
```

### Verify Seed Data

Using Supabase MCP:

```bash theme={null}
mcp_supabase_execute_sql --query "SELECT COUNT(*) FROM pf_organizations WHERE id LIKE '00000000-%'"
```

**Expected:** 2 organizations (seed data uses `00000000-` prefix UUIDs)

### Safety Guidelines

* ⚠️ **NEVER** run seeds in production
* Seeds use deterministic UUIDs (`00000000-` prefix)
* Seeds use test email domain (`@staging.encoreos.io`)
* Always verify project/branch before seeding

For detailed instructions, see Staging Verification Runbook.

***

## Next Steps

Once staging is set up and seeded:

1. **Run SQL Audits:** See [SQL\_AUDIT\_INSTRUCTIONS.md](SQL_AUDIT_INSTRUCTIONS.md)
2. **Create Fix Migrations:** Use templates in `supabase/migrations/TEMPLATE_*.sql`
3. **Generate TypeScript Types:** See [TYPE\_GENERATION\_GUIDE.md](TYPE_GENERATION_GUIDE.md)
4. **Test Application:** Point app at staging environment variables
5. **Verify Environment Isolation:** Run `npm run test:isolation`

***

## Related Documentation

* [Completion Plan](COMPLETION_PLAN.md) - Full migration plan
* [MCP Usage Guide](../development/MCP_USAGE.md) - When to use MCP vs CLI
* [Supabase Branching](https://supabase.com/docs/guides/deployment/branching) - Official docs

***

**Last Updated:** 2026-01-15\
**Version:** 2.0.0
