> ## 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.

# User Management and Cleanup Guide

> Total Users: 1,223 Test Users: 1,191 (97% of all users) Recent Users: All 1,223 created in last 7 days

**Date:** 2026-01-20\
**Purpose:** Understanding and managing users in the database, including test users and Lovable integration

***

## Current User Status

### User Statistics

**Total Users:** 1,223\
**Test Users:** 1,191 (97% of all users)\
**Recent Users:** All 1,223 created in last 7 days

### User Breakdown by Type

| User Type  | Count  | Source                | Purpose                    |
| ---------- | ------ | --------------------- | -------------------------- |
| E2E Tests  | \~500+ | Automated test suites | End-to-end testing         |
| RLS Tests  | \~200+ | RLS test scenarios    | Row-level security testing |
| Debug/Test | \~300+ | Manual testing        | Development debugging      |
| Seed Data  | \~100+ | Seed files            | Staging test data          |
| Other      | \~32   | Production/real users | Actual application users   |

***

## User Sources

### 1. E2E Test Users

**Pattern:** `e2e-{test-name}-{timestamp}@test.com`

**Examples:**

* `e2e-auth-<timestamp>@test.com`
* `e2e-financial-<timestamp>@test.com`
* `e2e-leave-<timestamp>@test.com`

**Source:** Automated end-to-end test suites\
**Location:** `tests/e2e/` directory\
**Purpose:** Testing complete user flows

**Cleanup:** These are created during test runs and can be safely cleaned up if not needed.

***

### 2. RLS Test Users

**Pattern:** `rls-{scenario}-{test-number}-{timestamp}@example.com`

**Examples:**

* `rls-scenario-testN-<timestamp>@example.com`
* `rls-close-testN-<timestamp>@example.com`

**Source:** RLS (Row-Level Security) test scenarios\
**Location:** `tests/rls/` directory\
**Purpose:** Testing multi-tenant data isolation

**Cleanup:** These are created during RLS test runs and can be safely cleaned up.

***

### 3. Debug/Test Users

**Pattern:** `{role}-{purpose}-{timestamp}@test.com`

**Examples:**

* `admin-debug-<timestamp>@test.com`
* `regular-debug-<timestamp>@test.com`
* `test-user-a-fw-logs-<timestamp>@test.com`

**Source:** Manual testing and debugging\
**Purpose:** Development and troubleshooting

**Cleanup:** These can be cleaned up if no longer needed for debugging.

***

### 4. Seed Data Users

**Pattern:** `{role}@test-org-{name}.example` or `test.{name}.{num}@org{num}.staging.encoreos.io`

**Examples:**

* `admin@test-org-alpha.example`
* `manager@test-org-beta.example`
* `test.admin.N@orgN.staging.encoreos.io`

**Source:** Seed files in `supabase/seeds/`\
**Location:** `supabase/seeds/base/02_users.sql`\
**Purpose:** Staging environment test data

**Cleanup:** These should remain in staging but should NOT be in production.

***

### 5. Lovable Integration

**Status:** Lovable is connected to the project

**What Lovable Does:**

* Auto-generates `src/integrations/supabase/client.ts`
* Auto-generates `src/integrations/supabase/types.ts`
* Manages `.env` file (when configured)
* Deploys edge functions automatically
* **Does NOT create users directly**

**Lovable Users:**

* Lovable does NOT create test users in the database
* Any users you see are from:
  * Automated test suites (E2E, RLS)
  * Manual testing/debugging
  * Seed data (staging only)
  * Real user signups

**Lovable Deployment:**

* Lovable may deploy to `.lovable.app` domains
* If you use Lovable deployment URLs, add them to Supabase redirect URLs
* See `docs/development/SUPABASE_VERCEL_SETUP_FIX.md` for configuration

***

## User Cleanup Options

### Option 1: Clean Up Test Users (Recommended - Use Script)

**⚠️ WARNING:** Only run this in production if you're sure you want to remove test users.

**✅ RECOMMENDED: Use the automated cleanup script:**

```bash theme={null}
# Step 1: Dry-run to identify test users (no changes)
npm run db:cleanup:test-users -- --dry-run --env production

# Step 2: Preview what would be deleted
npm run db:cleanup:test-users -- --env production

# Step 3: Actually delete (requires --confirm flag)
npm run db:cleanup:test-users -- --env production --confirm
```

**Manual SQL Alternative (if script unavailable):**

```sql theme={null}
-- Identify test users (dry-run first)
SELECT id, email, created_at 
FROM auth.users
WHERE email LIKE '%test%' 
   OR email LIKE '%example%'
   OR email LIKE 'e2e-%'
   OR email LIKE 'rls-%'
   OR email LIKE '%debug%'
   OR email LIKE '%staging%'
ORDER BY created_at DESC;

-- Delete test users (CAREFUL - this is permanent!)
-- Only run after verifying the SELECT query above
DELETE FROM auth.users
WHERE email LIKE '%test%' 
   OR email LIKE '%example%'
   OR email LIKE 'e2e-%'
   OR email LIKE 'rls-%'
   OR email LIKE '%debug%'
   OR email LIKE '%staging%';
```

**Before Running:**

1. ✅ Verify you're in the correct environment (production vs staging)
2. ✅ Run the SELECT query first to see what will be deleted
3. ✅ Consider backing up first
4. ✅ Check if any test users have important data

**See:** `docs/development/TEST_USER_CLEANUP_GUIDE.md` for complete cleanup guide.

***

### Option 2: Archive Test Users (Safer)

**⚠️ IMPORTANT:** You cannot directly modify the `auth.users` table schema as it's managed by Supabase. Use one of these safe alternatives:

#### Alternative A: Use raw\_user\_meta\_data JSONB

Mark users as archived using their existing metadata field:

```sql theme={null}
-- Mark test users as archived via metadata
UPDATE auth.users
SET raw_user_meta_data = raw_user_meta_data || '{"archived": true}'::jsonb
WHERE email LIKE '%test%' 
   OR email LIKE '%example%'
   OR email LIKE 'e2e-%'
   OR email LIKE 'rls-%'
   OR email LIKE '%debug%'
   OR email LIKE '%staging%';

-- Query to filter out archived users
SELECT * FROM auth.users 
WHERE (raw_user_meta_data->>'archived')::boolean IS NOT TRUE;
```

#### Alternative B: Use Application-Level Table (Recommended)

Create a separate table to track archived user status:

```sql theme={null}
-- Create tracking table
CREATE TABLE IF NOT EXISTS pf_user_archive_status (
  user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
  archived BOOLEAN DEFAULT false,
  archived_at TIMESTAMPTZ,
  archived_by UUID REFERENCES auth.users(id),
  reason TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS
ALTER TABLE pf_user_archive_status ENABLE ROW LEVEL SECURITY;

-- Allow platform admins to manage
CREATE POLICY "Platform admins manage archive status"
ON pf_user_archive_status
FOR ALL
USING (pf_has_system_role(auth.uid(), 'platform_admin'));

-- Archive test users
INSERT INTO pf_user_archive_status (user_id, archived, archived_at)
SELECT id, true, now()
FROM auth.users
WHERE email LIKE '%test%' 
   OR email LIKE '%example%'
   OR email LIKE 'e2e-%'
   OR email LIKE 'rls-%'
   OR email LIKE '%debug%'
   OR email LIKE '%staging%'
ON CONFLICT (user_id) DO UPDATE SET archived = true, archived_at = now();

-- Query non-archived users by joining
SELECT u.* FROM auth.users u
LEFT JOIN pf_user_archive_status a ON a.user_id = u.id
WHERE a.archived IS NOT TRUE OR a.user_id IS NULL;
```

***

### Option 3: Clean Up by Date

Remove users created during a specific time period (e.g., test run):

```sql theme={null}
-- Delete users created in last 7 days (if all are test users)
DELETE FROM auth.users
WHERE created_at > NOW() - INTERVAL '7 days'
  AND (email LIKE '%test%' OR email LIKE '%example%' OR email LIKE 'e2e-%' OR email LIKE 'rls-%');
```

***

## Preventing Test User Accumulation

### 1. Use Test Isolation

**For E2E Tests:**

* Use unique test user emails with timestamps
* Clean up test users after test runs
* Use test database or staging environment

**For RLS Tests:**

* Use deterministic test user IDs
* Clean up after test suite completes
* Consider using test fixtures that clean up automatically

### 2. Environment Separation

**Production:**

* ✅ No test users should exist
* ✅ Only real user signups
* ✅ Regular cleanup of any accidental test users

**Staging:**

* ✅ Test users are expected
* ✅ Seed data users are normal
* ✅ Can have test users for UAT

### 3. Automated Cleanup

**Consider adding cleanup scripts:**

```bash theme={null}
# Clean up test users older than 30 days
# Run as scheduled job or manual cleanup
```

***

## Lovable Integration Notes

### Lovable Connection

**What Lovable Manages:**

* ✅ Supabase client configuration
* ✅ TypeScript types generation
* ✅ Environment variables (when configured)
* ✅ Edge function deployment
* ❌ **Does NOT create users**

### Lovable Deployment URLs

If you deploy via Lovable to `.lovable.app` domains:

1. **Add to Supabase Redirect URLs:**

   ```toml theme={null}
   # In supabase/config.toml
   [remotes.production.auth]
   additional_redirect_urls = [
     # ... existing URLs ...
     "https://your-app.lovable.app/",
     "https://your-app.lovable.app/**",
   ]
   ```

2. **Sync Config:**

   ```bash theme={null}
   supabase db push
   ```

***

## Verification Queries

### Check User Distribution

```sql theme={null}
-- User types breakdown
SELECT 
  CASE 
    WHEN email LIKE 'e2e-%' THEN 'E2E Tests'
    WHEN email LIKE 'rls-%' THEN 'RLS Tests'
    WHEN email LIKE '%debug%' OR email LIKE '%test%' THEN 'Debug/Test'
    WHEN email LIKE '%example%' OR email LIKE '%staging%' THEN 'Seed Data'
    ELSE 'Production/Real'
  END as user_type,
  COUNT(*) as count
FROM auth.users
GROUP BY user_type
ORDER BY count DESC;
```

### Check Recent User Creation

```sql theme={null}
-- Users created in last 7 days
SELECT 
  DATE(created_at) as creation_date,
  COUNT(*) as users_created
FROM auth.users
WHERE created_at > NOW() - INTERVAL '7 days'
GROUP BY DATE(created_at)
ORDER BY creation_date DESC;
```

### Find Test Users

```sql theme={null}
-- All test users
SELECT id, email, created_at 
FROM auth.users
WHERE email LIKE '%test%' 
   OR email LIKE '%example%'
   OR email LIKE 'e2e-%'
   OR email LIKE 'rls-%'
   OR email LIKE '%debug%'
   OR email LIKE '%staging%'
ORDER BY created_at DESC;
```

***

## Recommendations

### For Production

1. **Immediate:** Review and clean up test users if they shouldn't be there
2. **Ongoing:** Set up automated cleanup for test users
3. **Monitoring:** Add alerts for unexpected user creation spikes
4. **Documentation:** Document which users are legitimate

### For Staging

1. **Expected:** Test users are normal in staging
2. **Seed Data:** Keep seed data users for UAT
3. **Cleanup:** Periodically clean up old test users (30+ days old)

### For Development

1. **Local:** Use local Supabase instance for testing
2. **Isolation:** Use separate test databases when possible
3. **Cleanup:** Clean up test users after development sessions

***

## Related Documentation

* **Test User Cleanup Guide:** `docs/development/TEST_USER_CLEANUP_GUIDE.md` - Complete cleanup procedures
* **Setup Fix Guide:** `docs/development/SUPABASE_VERCEL_SETUP_FIX.md`
* **Testing Guide:** `docs/development/VERIFICATION_TESTING_GUIDE.md`
* **Lovable Integration:** `AGENTS.md`
* **Environment Config:** [ENVIRONMENT\_CONFIG.md](/development/ENVIRONMENT_CONFIG)
