# Scripts Command Center - 0.1% Plan

> **Status:** ✅ COMPLETE - CC3 TESTED
> **Created:** Jan 17, 2026
> **CC1 Investigation Complete**
> **CC2 Build Complete**
> **CC3 Testing Complete:** Jan 17, 2026

---

## Executive Summary

Build a unified Scripts Command Center with brand guidelines enforcement, AI guardrails, and a curated script library. Every AI-generated message passes through compliance checking before reaching customers.

**The Goal:** Zero off-brand messages. Every outbound communication (AI or manual) reflects RateRight's voice.

---

## Investigation Findings

### What Exists

| Component | Location | Status |
|-----------|----------|--------|
| AI Message Writer | `admin/src/components/AIMessageWriter.jsx` | Full UI with tone selector, 3 suggestions |
| Nudge Templates | `admin/src/components/NudgeTemplates.jsx` | Stage-based templates with variables |
| SMS Templates Table | `sms_templates` in Supabase | Basic slug-based templates |
| Prompt Templates Table | `prompt_templates` in Supabase | Advanced with tone/reply_rate |
| AI Service | `src/services/ai.js` | 1369 lines, all AI generation |
| AI Routes | `src/routes/ai.js` | 1741 lines, all AI endpoints |
| Previous Script Plan | `docs/script-system-plan.md` | Call scripts only (never built) |

### AI Generation Points (CRITICAL - Need Compliance Filtering)

| Function | File:Line | Output Type | Customer-Facing? |
|----------|-----------|-------------|------------------|
| `draftMessage()` | ai.js:157 | SMS messages | **YES - PRIMARY** |
| `getObjectionResponse()` | ai.js:752 | Call suggestions | YES (said verbatim) |
| `generateIntelBrief()` | ai.js:25 | Opening line | YES (opening_line field) |
| `explainMessage()` | ai.routes:638 | Message analysis | No (internal) |
| `parseVoiceCommand()` | ai.js:392 | Command parsing | No (internal) |

### What's Missing

1. **Brand Guidelines System** - No tone rules, banned words, or required elements
2. **Compliance Checker** - No validation layer for AI output
3. **AI Guardrails** - AI prompts don't reference any compliance rules
4. **Needs Review Queue** - No flagging system for borderline messages
5. **Unified Script Library** - Templates are scattered across tables

---

## Feature Specifications

### SCC-1: Brand Guidelines Editor

**Database Schema:**
```sql
-- Brand guidelines configuration
CREATE TABLE IF NOT EXISTS brand_guidelines (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Tone & Voice
  tone_description TEXT NOT NULL DEFAULT 'Friendly, direct, Aussie mate vibes. Not corporate.',
  tone_keywords TEXT[] DEFAULT ARRAY['mate', 'hey', 'cheers', 'no worries', 'legend'],

  -- Banned content
  banned_words TEXT[] DEFAULT ARRAY['guaranteed', 'promise', 'best', 'cheapest', 'free'],
  banned_phrases TEXT[] DEFAULT ARRAY['act now', 'limited time', 'don''t miss out', 'once in a lifetime'],

  -- Required elements
  required_signature TEXT DEFAULT 'Cheers, [Name] - RateRight',
  must_include_cta BOOLEAN DEFAULT true,
  max_exclamation_marks INTEGER DEFAULT 1,

  -- Compliance rules
  no_false_claims BOOLEAN DEFAULT true,
  no_pressure_tactics BOOLEAN DEFAULT true,
  must_identify_as_rateright BOOLEAN DEFAULT true,

  -- Versioning
  version INTEGER DEFAULT 1,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  created_by TEXT
);

-- Guideline change history
CREATE TABLE IF NOT EXISTS brand_guideline_history (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  guideline_id UUID REFERENCES brand_guidelines(id),
  changed_by TEXT,
  change_type TEXT, -- 'create', 'update', 'activate'
  old_values JSONB,
  new_values JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Seed initial guidelines
INSERT INTO brand_guidelines (
  tone_description,
  tone_keywords,
  banned_words,
  banned_phrases,
  required_signature
) VALUES (
  'Friendly, direct, Aussie tradie vibes. We''re mates helping mates find work. Not corporate, not salesy. Just real people having real conversations.',
  ARRAY['mate', 'hey', 'cheers', 'no worries', 'legend', 'good on ya', 'too easy'],
  ARRAY['guaranteed', 'promise', 'best', 'cheapest', 'free', 'urgent', 'final', 'hurry'],
  ARRAY['act now', 'limited time', 'don''t miss out', 'once in a lifetime', 'last chance', 'exclusive offer'],
  'Cheers, {sender_name} - RateRight'
) ON CONFLICT DO NOTHING;
```

**Backend Endpoints:**
```
GET  /api/brand-guidelines       - Get active guidelines
PUT  /api/brand-guidelines       - Update guidelines
GET  /api/brand-guidelines/history - Get change history
```

**Frontend Page: `admin/src/pages/BrandGuidelines.jsx`**
- Split view: Tone on left, Rules on right
- Live preview panel showing example compliant message
- "Test Message" input to check compliance
- Change history timeline at bottom

---

### SCC-2: Script Library

**Database Schema:**
```sql
-- Unified script library
CREATE TABLE IF NOT EXISTS scripts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Basic info
  name VARCHAR(200) NOT NULL,
  description TEXT,
  category VARCHAR(50) NOT NULL, -- 'sms', 'call', 'email', 'objection'
  subcategory VARCHAR(50), -- 'cold', 'follow_up', 're_engagement', 'closing', 'nurture'

  -- Targeting
  target_type VARCHAR(20) DEFAULT 'both', -- 'worker', 'contractor', 'both'
  target_stage VARCHAR(50), -- Platform stage this script is for
  target_score_min INTEGER, -- Min lead score
  target_score_max INTEGER, -- Max lead score

  -- Content
  content TEXT NOT NULL, -- The actual script/template
  variables TEXT[], -- ['first_name', 'company', 'sender_name']
  notes TEXT, -- Internal notes for reps

  -- Compliance
  compliance_status VARCHAR(20) DEFAULT 'pending', -- 'approved', 'pending', 'rejected', 'needs_review'
  compliance_checked_at TIMESTAMPTZ,
  compliance_issues JSONB, -- [{issue: 'banned_word', word: 'guaranteed', position: 45}]
  reviewed_by TEXT,

  -- Performance
  times_used INTEGER DEFAULT 0,
  times_replied INTEGER DEFAULT 0,
  reply_rate DECIMAL(5,2) GENERATED ALWAYS AS (
    CASE WHEN times_used > 0 THEN (times_replied::DECIMAL / times_used * 100) ELSE 0 END
  ) STORED,
  avg_sentiment_score DECIMAL(3,2),

  -- Metadata
  is_seed BOOLEAN DEFAULT false, -- True for starter scripts
  is_active BOOLEAN DEFAULT true,
  created_by TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_scripts_category ON scripts(category, subcategory);
CREATE INDEX IF NOT EXISTS idx_scripts_compliance ON scripts(compliance_status);
CREATE INDEX IF NOT EXISTS idx_scripts_target ON scripts(target_type, target_stage);
```

**Backend Endpoints:**
```
GET    /api/scripts                - List with filters
GET    /api/scripts/:id            - Get single script
POST   /api/scripts                - Create script
PATCH  /api/scripts/:id            - Update script
DELETE /api/scripts/:id            - Soft delete
POST   /api/scripts/:id/use        - Record usage
GET    /api/scripts/analytics      - Performance stats
```

**Frontend Page: `admin/src/pages/ScriptLibrary.jsx`**
- Card grid view with compliance badge (green check / yellow warning / red x)
- Filters: Category, Subcategory, Target Type, Compliance Status
- Sort: Reply Rate, Times Used, Recent
- Quick stats on each card: usage count, reply rate, compliance status
- Click to expand full script with "Copy" and "Use" buttons

---

### SCC-3: Compliance Checker Service

**New Service: `src/services/compliance.js`**

```javascript
// Compliance check result structure
{
  passed: boolean,
  score: 0-100,        // Compliance score
  issues: [
    {
      type: 'banned_word' | 'banned_phrase' | 'tone' | 'length' | 'missing_element',
      severity: 'error' | 'warning' | 'info',
      message: 'Contains banned word: "guaranteed"',
      position: { start: 45, end: 55 },
      suggestion: 'Try: "We can help you find..."'
    }
  ],
  suggestions: string[],  // AI-generated fixes
  autoFixed: string | null  // Auto-corrected version if possible
}
```

**Core Functions:**
```javascript
// Check message against brand guidelines
async function checkCompliance(message, options = {}) { ... }

// Auto-fix minor issues
async function autoFixMessage(message) { ... }

// Get compliance status for script
async function validateScript(scriptId) { ... }

// Batch check for script library
async function batchValidate(scriptIds) { ... }
```

**Compliance Rules (in order of severity):**

| Rule | Severity | Auto-fixable? |
|------|----------|---------------|
| Contains banned word | ERROR | Sometimes |
| Contains banned phrase | ERROR | Sometimes |
| False claims (AI detected) | ERROR | No |
| Pressure tactics (AI detected) | ERROR | No |
| Missing CTA | WARNING | Yes |
| Too many exclamation marks | WARNING | Yes |
| Too long (>320 chars SMS) | WARNING | Yes |
| Missing signature | INFO | Yes |
| Tone mismatch (AI detected) | INFO | No |

---

### SCC-4: AI Guardrails Integration

**Modify `src/services/ai.js` - `draftMessage()` function**

Before (current):
```javascript
const prompt = `You are writing SMS messages for a RateRight sales rep...`;
```

After (with guardrails):
```javascript
// Inject brand guidelines into AI prompt
const guidelines = await getActiveBrandGuidelines();

const prompt = `You are writing SMS messages for a RateRight sales rep.

BRAND VOICE RULES (MUST FOLLOW):
- Tone: ${guidelines.tone_description}
- Use words like: ${guidelines.tone_keywords.join(', ')}
- NEVER use: ${guidelines.banned_words.join(', ')}
- NEVER use phrases: ${guidelines.banned_phrases.join(', ')}
- Max 1 exclamation mark per message
- Keep it conversational, not corporate
- Always include a clear next step

LEAD: ${lead.first_name}...`;
```

**Post-Generation Compliance Check:**
```javascript
// After AI generates message
const draft = await generateFromAI(prompt);

// Run compliance check
const compliance = await complianceService.checkCompliance(draft.message);

if (!compliance.passed) {
  // Try auto-fix for minor issues
  if (compliance.autoFixed) {
    draft.message = compliance.autoFixed;
    draft.autoFixed = true;
  } else {
    // Flag for review
    draft.needsReview = true;
    draft.complianceIssues = compliance.issues;
  }
}

return draft;
```

**Integration Points:**
1. `draftMessage()` - Primary SMS generation
2. `getObjectionResponse()` - Call script suggestions
3. `generateIntelBrief()` - Opening line only

---

### SCC-5: Needs Review Queue

**Database Schema:**
```sql
-- Messages flagged for review
CREATE TABLE IF NOT EXISTS compliance_queue (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Source
  source_type VARCHAR(50) NOT NULL, -- 'ai_draft', 'script', 'manual'
  source_id UUID, -- Reference to script or draft
  lead_id UUID REFERENCES leads(id),

  -- Content
  original_content TEXT NOT NULL,
  suggested_fix TEXT,
  issues JSONB NOT NULL, -- Compliance issues array

  -- Status
  status VARCHAR(20) DEFAULT 'pending', -- 'pending', 'approved', 'rejected', 'edited'
  reviewed_by TEXT,
  reviewed_at TIMESTAMPTZ,
  final_content TEXT, -- What was actually sent/saved

  -- Metadata
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_compliance_queue_status ON compliance_queue(status);
```

**Backend Endpoints:**
```
GET   /api/compliance/queue          - Get pending items
POST  /api/compliance/queue/:id/approve - Approve message
POST  /api/compliance/queue/:id/reject  - Reject message
POST  /api/compliance/queue/:id/edit    - Edit and approve
GET   /api/compliance/stats          - Review stats
```

**Frontend Component: `admin/src/components/ComplianceQueue.jsx`**
- Slide-over panel accessible from script library
- Shows pending count badge in nav
- Each item shows: original message, issues highlighted, suggested fix
- Actions: Approve, Edit & Approve, Reject
- Quick stats: reviewed today, approval rate

---

### SCC-6: Command Center Dashboard

**Frontend Page: `admin/src/pages/ScriptsCommandCenter.jsx`**

Layout:
```
+------------------+------------------+
| COMPLIANCE SCORE | NEEDS REVIEW     |
| 94%              | 3 items          |
| [==========    ] | [View Queue]     |
+------------------+------------------+
|                                     |
| SCRIPT LIBRARY                      |
| [SMS] [Call] [Email] [All]          |
|                                     |
| +------+ +------+ +------+ +------+ |
| |Script| |Script| |Script| |Script| |
| |  1   | |  2   | |  3   | |  4   | |
| +------+ +------+ +------+ +------+ |
|                                     |
+-------------------------------------+
| QUICK ACTIONS                       |
| [+ New Script] [Brand Guidelines]   |
|               [Bulk Compliance]     |
+-------------------------------------+
```

**Components:**
1. **Compliance Score Card** - Overall compliance percentage
2. **Needs Review Badge** - Count with link to queue
3. **Script Grid** - Filterable script library
4. **Quick Actions** - New script, guidelines, bulk check

---

## Seed Scripts (30 Total)

| Category | Count |
|----------|-------|
| SMS | 10 |
| Call | 10 |
| Objection Handlers | 8 |
| Email | 2 |
| **Total** | **30** |

**Coverage:**
- ✅ Both audiences (Contractors + Workers)
- ✅ Full funnel (Cold → Signup → Activation → Retention → Referral)
- ✅ Follow-up sequences (Day 3, Day 7, 30 days)
- ✅ 8 common objections handled
- ✅ Correct fee messaging (contractors FREE, workers 9.9%)
- ✅ SMS opt-out on re-engagement/marketing only (not required for active sales follow-ups)

---

### SMS Scripts (10)

**SMS-1: First Contact - Contractor**
```
Category: sms | Target: contractor | Stage: new_signup
---
Hi {first_name}, it's {sender_name} from RateRight. Saw you signed up - are you looking for workers for upcoming jobs? Happy to help you get started.
```

**SMS-2: First Contact - Worker**
```
Category: sms | Target: worker | Stage: new_signup
---
Hi {first_name}, it's {sender_name} from RateRight. Saw you signed up - are you looking for work right now? I can help you get your profile set up and start seeing jobs.
```

**SMS-3: Follow-Up Day 3**
```
Category: sms | Target: both | Stage: no_response
---
Hey {first_name}, just checking in. Still need help with RateRight? Happy to answer any questions.
```

**SMS-4: Follow-Up Day 7**
```
Category: sms | Target: both | Stage: no_response
---
Hey {first_name}, last message from me unless you want to chat. Post jobs free, find workers free - no fees for contractors, ever. Any questions, just reply.
```

**SMS-5: Hot Lead - Contractor**
```
Category: sms | Target: contractor | Stage: engaged
---
{first_name} - great chatting earlier. Ready to post your first job? Takes 2 mins and it's completely free for contractors - no fees on your end, ever. Want me to walk you through it?
```

**SMS-6: Hot Lead - Worker**
```
Category: sms | Target: worker | Stage: engaged
---
{first_name} - great chatting earlier. Ready to complete your profile? Takes 5 mins and you'll start seeing jobs in your area straight away. Want me to walk you through it?
```

**SMS-7: Re-Engagement 30 Days**
```
Category: sms | Target: both | Stage: gone_cold
---
Hey {first_name}, been a while. Just wanted to check - did you find what you needed? If not, we're here when you're ready. No pressure. Reply STOP to opt out.
```

**SMS-8: Post-Signup Activation - Contractor**
```
Category: sms | Target: contractor | Stage: just_signed_up
---
Welcome to RateRight {first_name}! Your account's ready. Next step: Post your first job (free) and start getting quotes from verified workers. Questions? Just reply.
```

**SMS-9: Post-Signup Activation - Worker**
```
Category: sms | Target: worker | Stage: just_signed_up
---
Welcome to RateRight {first_name}! Your account's ready. Next step: Complete your profile so contractors can find you. Takes 5 mins. Questions? Just reply.
```

**SMS-10: First Job Posted**
```
Category: sms | Target: contractor | Stage: first_action
---
Nice one {first_name} - your job's live! You should start seeing applications soon. I'll check in tomorrow to see how it's going.
```

---

### Call Scripts (10)

**CALL-1: Cold Call Opening - Contractor**
```
Category: call | Target: contractor | Stage: not_signed_up
---
OPENING:
"Hey {first_name}, it's {sender_name} from RateRight - the construction marketplace. You signed up recently so I wanted to check in. Are you looking for workers for upcoming jobs?"

[Pause for response]

"Got it. Quick question - what's your biggest headache right now when it comes to finding reliable workers?"
```

**CALL-2: Cold Call Opening - Worker**
```
Category: call | Target: worker | Stage: not_signed_up
---
OPENING:
"Hey {first_name}, it's {sender_name} from RateRight. You signed up recently so I wanted to check in. Are you looking for work at the moment?"

[Pause for response]

"Got it. What kind of jobs are you after, and what area do you cover?"
```

**CALL-3: Value Pitch - Contractor**
```
Category: call | Target: contractor | Stage: qualifying
---
VALUE PITCH:
"So here's how we're different from agencies - You post jobs free. You find workers free. You pay them the agreed rate - that's it. No markup, no monthly fees, nothing.

The worker pays a small platform fee, not you.

And the payment sits in escrow so they know they'll get paid, and you know it's only released when you're satisfied.

Does that sound like something that could work for your next project?"
```

**CALL-4: Value Pitch - Worker**
```
Category: call | Target: worker | Stage: qualifying
---
VALUE PITCH:
"Here's how it works - you set your own rates, pick your own jobs, no one tells you what to do.

When you complete a job, the money's already sitting in escrow waiting for you. We take 9.9% and you get the rest, usually within a day or two.

Compare that to agencies taking half your rate and telling you where to be at 6am. Sound better?"
```

**CALL-5: Discovery Questions**
```
Category: call | Target: both | Stage: qualifying
---
"Before I explain how it all works, can I ask a few quick questions?"

1. "What's your typical project size?"
2. "How do you usually find [workers/jobs] now?"
3. "What's the main problem with that?"
```

**CALL-6: Close - Soft**
```
Category: call | Target: both | Stage: ready_to_convert
---
"Alright {first_name}, sounds like this could work for you.

How about this - I'll send you a link to [post your first job / complete your profile]. Takes 2 minutes, completely free.

Once you see how it works, you can decide if it's right for you. Fair?"
```

**CALL-7: Close - Urgency**
```
Category: call | Target: contractor | Stage: ready_to_convert
---
"I've got a few workers in {location} looking for jobs right now.

If you post today, you could have quotes by tomorrow morning.

Want me to send you the link?"
```

**CALL-8: Check-In - Active User**
```
Category: call | Target: both | Stage: active_user
---
OPENING:
"Hey {first_name}, just checking in. How's everything going with RateRight? Any issues or questions I can help with?"
```

**CALL-9: Referral Ask**
```
Category: call | Target: both | Stage: happy_customer
---
"Glad it's working out {first_name}.

Quick question - know anyone else in construction who's sick of dealing with agencies?

If you refer them and they sign up, I'll make sure you both get looked after."
```

**CALL-10: Case Study Ask**
```
Category: call | Target: contractor | Stage: happy_customer
---
"{first_name}, you've had some solid results with us.

Would you be open to a quick 5-minute chat where I ask a few questions about your experience?

We're putting together some case studies and your story could really help other contractors see what's possible."
```

---

### Objection Handlers (8)

**OBJ-1: "Already Have Workers"**
```
Category: objection | Target: contractor
---
OBJECTION: "Already have workers"

RESPONSE:
"That's great - sounds like you've got reliable people. Most of our contractors use us as a backup for when their regulars are booked, or when they need a specific trade they don't usually work with.

No cost to have an account ready. When's your next big project coming up?"
```

**OBJ-2: "What's the Catch?"**
```
Category: objection | Target: both
---
OBJECTION: "What's the catch?" / "Sounds too good to be true"

RESPONSE:
"Fair question. For contractors - completely free. No posting fees, no monthly subscription, no percentage.

The worker pays 9.9% from their end when the job completes. That's how we keep the lights on.

Compare that to agencies charging YOU 30-40% markup and you can see why contractors are switching."
```

**OBJ-3: "Too Busy Right Now"**
```
Category: objection | Target: both
---
OBJECTION: "Too busy right now" / "Call me later"

RESPONSE:
"Totally get it. Construction's flat out this time of year. I won't take more of your time - but can I send you a quick link so you've got it when things settle down? No obligation."
```

**OBJ-4: "Need to Think About It"**
```
Category: objection | Target: both
---
OBJECTION: "Need to think about it"

RESPONSE:
"No worries, makes sense. What's the main thing you need to think through? Is it the pricing, how it works, or something else?

Sometimes I can clear things up on the spot."
```

**OBJ-5: "How Do I Know Workers Are Good?"**
```
Category: objection | Target: contractor
---
OBJECTION: "How do I know the workers are any good?"

RESPONSE:
"Every worker on the platform has a verified ABN and has to carry their own insurance.

Plus there's a rating system - you can see their history before you hire.

And because payment sits in escrow, you only release it when you're happy with the work."
```

**OBJ-6: "I've Been Burned Before"**
```
Category: objection | Target: contractor
---
OBJECTION: "I've been burned before"

RESPONSE:
"Yeah, I hear that a lot. That's exactly why we built the escrow system - your money doesn't go anywhere until you say the job's done right.

And if there's an issue, we help sort it out before anyone gets paid.

What happened last time, if you don't mind me asking?"
```

**OBJ-7: "The Fee is Too High" (Worker)**
```
Category: objection | Target: worker
---
OBJECTION: "9.9% is too high"

RESPONSE:
"I get it - 9.9% sounds like a chunk. But think about it this way: agencies take 30-40% and tell you where to be.

We take 9.9%, you set your own rates, pick your own jobs, and the money's in your account within days.

Most workers just build the fee into their quote."
```

**OBJ-8: "I'll Just Use Gumtree/Facebook"**
```
Category: objection | Target: both
---
OBJECTION: "I'll just use Gumtree/Facebook"

RESPONSE:
"Yeah, heaps of people do. The difference is we verify ABNs, hold payment in escrow, and both sides rate each other.

So you're not rolling the dice on strangers. Free to try - worst case you've got a backup option."
```

---

### Email Scripts (2)

**EMAIL-1: Welcome Email**
```
Category: email | Target: both | Stage: post_signup
---
Subject: Welcome to RateRight - here's what to do next

Hi {first_name},

You're in. Your RateRight account is ready to go.

Next step: [Post your first job / Complete your profile] - takes 2 minutes.

Questions? Just reply to this email or call me on {sender_phone}.

Cheers,
{sender_name}
```

**EMAIL-2: Re-Engagement 30 Days**
```
Category: email | Target: both | Stage: inactive_30d
---
Subject: Still looking for [workers/work]?

Hi {first_name},

Haven't seen you on RateRight for a while. Just wanted to check - did you find what you needed?

If not, your account's still there waiting. No fees, no lock-in.

Reply if you need a hand.

Cheers,
{sender_name}
```

---

## Build Order

### Phase 1: Foundation (Backend)
- [ ] **Step 1:** Create `brand_guidelines` table and seed data
- [ ] **Step 2:** Create `scripts` table with compliance fields
- [ ] **Step 3:** Create `compliance_queue` table
- [ ] **Step 4:** Build `/api/brand-guidelines` endpoints
- [ ] **Step 5:** Build `/api/scripts` CRUD endpoints

### Phase 2: Compliance Service
- [ ] **Step 6:** Create `src/services/compliance.js`
- [ ] **Step 7:** Implement `checkCompliance()` - rule-based checks
- [ ] **Step 8:** Implement `autoFixMessage()` - auto-corrections
- [ ] **Step 9:** Add AI tone detection (uses GPT-4o-mini)
- [ ] **Step 10:** Build `/api/compliance/*` endpoints

### Phase 3: AI Integration
- [ ] **Step 11:** Inject brand guidelines into `draftMessage()` prompt
- [ ] **Step 12:** Add post-generation compliance check
- [ ] **Step 13:** Update `getObjectionResponse()` with guidelines
- [ ] **Step 14:** Add compliance flag to AI response structure

### Phase 4: Frontend - Brand Guidelines
- [ ] **Step 15:** Create `BrandGuidelines.jsx` page
- [ ] **Step 16:** Build tone editor component
- [ ] **Step 17:** Build banned words/phrases editor
- [ ] **Step 18:** Add live preview panel

### Phase 5: Frontend - Script Library
- [ ] **Step 19:** Create `ScriptLibrary.jsx` page
- [ ] **Step 20:** Build `ScriptCard.jsx` component
- [ ] **Step 21:** Build script detail/edit modal
- [ ] **Step 22:** Add compliance status badges

### Phase 6: Frontend - Command Center
- [ ] **Step 23:** Create `ScriptsCommandCenter.jsx` main page
- [ ] **Step 24:** Build compliance score card
- [ ] **Step 25:** Build `ComplianceQueue.jsx` slide-over
- [ ] **Step 26:** Add navigation to Scripts Command Center

### Phase 7: Seed Data & Testing
- [ ] **Step 27:** Insert 30 seed scripts from plan (10 SMS, 10 Call, 8 Objection, 2 Email)
- [ ] **Step 28:** Run batch compliance check on seeds
- [ ] **Step 29:** Test AI message generation with guardrails
- [ ] **Step 30:** End-to-end test: create script → use → compliance check

---

## File Structure

```
src/
├── routes/
│   ├── scripts.js          (NEW - Script CRUD + analytics)
│   ├── compliance.js       (NEW - Compliance endpoints)
│   └── ai.js               (MODIFY - Add guardrails)
├── services/
│   ├── compliance.js       (NEW - Compliance checker)
│   └── ai.js               (MODIFY - Inject guidelines)
│
admin/src/
├── pages/
│   ├── ScriptsCommandCenter.jsx    (NEW - Main dashboard)
│   ├── ScriptLibrary.jsx           (NEW - Script grid)
│   └── BrandGuidelines.jsx         (NEW - Guidelines editor)
├── components/
│   ├── scripts/
│   │   ├── ScriptCard.jsx          (NEW)
│   │   ├── ScriptDetailModal.jsx   (NEW)
│   │   └── ComplianceStatus.jsx    (NEW)
│   └── ComplianceQueue.jsx         (NEW - Review queue)
│
supabase/
└── scripts-command-center-migration.sql  (NEW)
```

---

## API Summary

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/brand-guidelines` | Get active guidelines |
| PUT | `/api/brand-guidelines` | Update guidelines |
| GET | `/api/brand-guidelines/history` | Change history |
| GET | `/api/scripts` | List scripts |
| GET | `/api/scripts/:id` | Get script |
| POST | `/api/scripts` | Create script |
| PATCH | `/api/scripts/:id` | Update script |
| DELETE | `/api/scripts/:id` | Delete script |
| POST | `/api/scripts/:id/use` | Record usage |
| GET | `/api/scripts/analytics` | Performance stats |
| POST | `/api/compliance/check` | Check message |
| GET | `/api/compliance/queue` | Get review queue |
| POST | `/api/compliance/queue/:id/approve` | Approve |
| POST | `/api/compliance/queue/:id/reject` | Reject |
| POST | `/api/compliance/queue/:id/edit` | Edit & approve |

---

## Success Criteria

1. **Brand Guidelines Editor** - Can add/remove banned words, adjust tone description
2. **Script Library** - 10+ scripts with compliance badges visible
3. **AI Guardrails** - AI-generated messages follow brand voice
4. **Compliance Checker** - Real-time validation with highlighted issues
5. **Needs Review Queue** - Borderline messages queued for human review
6. **Zero Off-Brand Messages** - All outbound comms pass compliance check

---

## Ready for CC2

**Blockers:** None

**Notes for CC2:**
- Start with database migration (Step 1-3)
- Build compliance service before AI integration
- Use `gen_random_uuid()` not `uuid_generate_v4()` (per LESSONS.md)
- Test compliance checking before integrating with AI prompts
- 30 seed scripts (10 SMS, 10 Call, 8 Objection, 2 Email) - insert with `is_seed: true`
- Objection handlers are category `objection` (separate from `call`)
- **Correct fee messaging:** Contractors = FREE, Workers = 9.9%
- SMS opt-out ("Reply STOP to opt out") only on re-engagement messages (gone_cold, inactive_30d) - not required for active sales follow-ups
- Scripts have `target_stage` field: new_signup, no_response, engaged, gone_cold, just_signed_up, first_action, not_signed_up, qualifying, ready_to_convert, active_user, happy_customer, post_signup, inactive_30d

---

**Plan saved:** `docs/scripts-command-center-plan.md`
**Ready for CC2:** Yes
