# AI Smart Scheduling Deployment Runbook

## Overview

This runbook covers deployment of the AI Smart Scheduling feature (Spec 026).

**Feature Branch**: `feature/026-ai-smart-scheduling`

## Pre-Deployment Checklist

- [ ] All unit tests passing (`./test.sh --testsuite unit`)
- [ ] All integration tests passing (`./test.sh --testsuite integration`)
- [ ] PHPStan clean (`./vendor/bin/phpstan analyse`)
- [ ] CSS build successful (`php conductor build-css --minify`)
- [ ] Code review approved
- [ ] QA sign-off received
- [ ] Rollback plan documented

## Environment Variables

Ensure these are configured in all target environments:

| Variable | Required | Description |
|----------|----------|-------------|
| `OPENAI_API_KEY` | Yes | OpenAI API key |
| `ABLY_KEY` | Yes | Ably API key (already configured) |
| `OPENAI_MODEL` | No | Model override (optional) |
| `AI_SCHEDULE_MAX_RUNS_PER_WEEK` | No | Rate limit (default: 5) |

See [Environment Configuration](./ai-scheduling-env.md) for details.

## Database Migrations

### Migration Files

The following migrations must be run:

1. `20260108_001_ai_schedule_suggestions.json` - AI suggestions table
2. `20260108_002_ai_schedule_usage.json` - Usage tracking table
3. `20260108_003_ai_schedule_jobs.json` - Job status table
4. `20260108_004_stores_ai_prefs.json` - Store AI preferences
5. `20260108_005_users_hours_prefs.json` - User hours preferences
6. `20260108_006_schedule_shifts_ai_columns.json` - Shift AI columns
7. `20260108_007_ai_session_logs.json` - Session logging
8. `20260108_008_hourly_staffing_metrics.json` - Staffing metrics
9. `20260108_009_ai_schedule_permissions.json` - Permissions
10. `20260108_010_ai_suggestions_unique_pending.json` - Unique constraint
11. `20260108_011_stores_pay_period_start.json` - Pay period tracking

### Running Migrations

```bash
# From userfrosting directory
php conductor run

# Or run specific migration
php conductor run --file=20260108_001_ai_schedule_suggestions.json
```

### Verify Migrations

```sql
-- Check tables exist
SHOW TABLES LIKE 'ai_%';

-- Check permissions created
SELECT * FROM permissions WHERE slug LIKE '%ai_schedule%';

-- Check store preferences column
DESCRIBE stores;
-- Should include: ai_scheduling_enabled, ai_default_priorities, etc.
```

## Deployment Steps

### 1. Staging Deployment

```bash
# 1. Merge to staging branch
git checkout staging
git merge feature/026-ai-smart-scheduling

# 2. Deploy to staging
./deploy.sh staging

# 3. Run migrations on staging
ssh staging 'cd /var/www/buyerkiosk && php userfrosting/conductor run'

# 4. Verify staging
curl https://staging.buyerkiosk.com/ou00/api/schedule/ai/usage
```

### 2. Staging Verification

- [ ] API endpoints responding correctly
- [ ] Real-time notifications working (Ably)
- [ ] OpenAI integration functional
- [ ] UI modal opens and displays correctly
- [ ] Rate limiting enforced
- [ ] Permissions working (access control)

### 3. Production Deployment

```bash
# 1. Create release tag
git tag -a v2026.01.XX-ai-scheduling -m "AI Smart Scheduling (Spec 026)"
git push origin v2026.01.XX-ai-scheduling

# 2. Deploy to production
./deploy.sh production

# 3. Run migrations on production
ssh production 'cd /var/www/buyerkiosk && php userfrosting/conductor run'

# 4. Clear caches
ssh production 'cd /var/www/buyerkiosk && php userfrosting/conductor cache:clear'
```

### 4. Production Verification

- [ ] Spot check 2-3 stores for functionality
- [ ] Verify no error spikes in logs
- [ ] Check OpenAI API connectivity
- [ ] Monitor Ably channel activity

## Feature Flags

The feature is controlled by permission system:

```php
// Store must have permission enabled
$app->user->checkAccess('uri_schedule_ai')

// Apply permission separate
$app->user->checkAccess('uri_schedule_ai_apply')
```

### Enable for Specific Stores

```sql
-- Grant permission to a role
INSERT INTO permission_role (permission_id, role_id)
SELECT p.id, r.id
FROM permissions p, roles r
WHERE p.slug = 'uri_schedule_ai'
AND r.name = 'Store Manager';
```

### Disable Feature (Emergency)

```sql
-- Revoke permission from all roles
DELETE FROM permission_role
WHERE permission_id IN (
    SELECT id FROM permissions WHERE slug LIKE 'uri_schedule_ai%'
);
```

## Rollback Procedure

### Quick Disable (No Rollback)

If issues arise but rollback is not needed:

```sql
-- Disable AI scheduling permissions
DELETE FROM permission_role
WHERE permission_id IN (
    SELECT id FROM permissions WHERE slug LIKE 'uri_schedule_ai%'
);
```

### Full Rollback

```bash
# 1. Revert to previous release
git checkout v2026.01.XX-previous
./deploy.sh production

# 2. Keep migrations (data is safe)
# OR if data issues, restore from backup

# 3. Clear caches
ssh production 'php userfrosting/conductor cache:clear'
```

### Migration Rollback (If Needed)

```sql
-- Remove AI-specific data (preserves schema)
TRUNCATE TABLE ai_schedule_suggestions;
TRUNCATE TABLE ai_schedule_jobs;
TRUNCATE TABLE ai_schedule_usage;
TRUNCATE TABLE ai_session_logs;
```

## Monitoring

### Key Metrics

1. **API Response Times**
   - `/api/schedule/ai/generate` - Should be < 1s (async dispatch)
   - `/api/schedule/ai/suggestions` - Should be < 500ms

2. **OpenAI Integration**
   - Job completion rate
   - Average generation time (target: < 30s)
   - Error rate

3. **Usage Patterns**
   - Runs per store per week
   - Apply rate (suggestions applied vs dismissed)

### Log Locations

```bash
# Application logs
tail -f logs/error_log

# TaskEngine worker logs
tail -f logs/task-worker.log

# Check for AI-specific errors
grep "AiScheduling" logs/error_log
```

### Alerting

Set up alerts for:
- OpenAI API errors (rate limit, auth failures)
- Job failure rate > 10%
- Generation time > 60 seconds

## Support Contacts

- **Feature Owner**: [Owner Name]
- **Backend Lead**: [Lead Name]
- **DevOps**: [DevOps Contact]
- **OpenAI Account**: [Account Manager]

## Related Documentation

- [API Documentation](../api/ai-scheduling-api.md)
- [Environment Configuration](./ai-scheduling-env.md)
- [OpenAI Integration Pattern](../patterns/openai-integration.md)
- [SDD](../specs/026-ai-smart-scheduling/solution-design.md)
