# AI Sales Brain - Master Plan

**Status:** Planning
**Created:** Jan 17, 2026
**Goal:** Unify Content Hub + Call System + Learning into one intelligent system that knows what works and gets smarter every day

---

## The Vision

**Current State:** Tools sitting next to each other
**Target State:** One AI brain that:
- Knows what works for each lead type
- Recommends the right script/message at the right time
- Learns from every interaction
- Surfaces patterns to the user
- Gets smarter every day

---

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                      AI SALES BRAIN                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │   CONTENT    │  │    CALL      │  │   LEARNING   │          │
│  │     HUB      │◄─┼─►  SYSTEM    │◄─┼─►  ENGINE    │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│         │                 │                 │                   │
│         └────────────────┼─────────────────┘                   │
│                          │                                      │
│                          ▼                                      │
│              ┌──────────────────────┐                          │
│              │   INTELLIGENCE API   │                          │
│              │                      │                          │
│              │  • What works now?   │                          │
│              │  • Best for this lead│                          │
│              │  • Market intel      │                          │
│              │  • Pattern detection │                          │
│              └──────────────────────┘                          │
│                          │                                      │
│         ┌────────────────┼────────────────┐                    │
│         │                │                │                    │
│         ▼                ▼                ▼                    │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │  PERPLEXITY │  │   GPT-4o    │  │  PATTERNS   │            │
│  │  Market Intel│  │  Reasoning  │  │  Database   │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## The Intelligence API

One endpoint that powers everything: `POST /api/ai/intelligence`

```javascript
// Request
{
  "context": "pre_call" | "during_call" | "sms_compose" | "dashboard",
  "lead_id": "uuid",
  "request": "recommend_script" | "what_to_say" | "market_intel" | "whats_working"
}

// Response
{
  "recommendation": {
    "script_id": "uuid",
    "script_name": "Reactivation Check-in",
    "confidence": 0.87,
    "reason": "43% success with similar leads (plumber, 3 weeks quiet)"
  },
  "market_intel": {
    "demand_trend": "+23%",
    "jobs_in_area": 8,
    "competitor_news": "HiPages raised fees"
  },
  "patterns": {
    "best_time": "Tuesday 10am",
    "best_approach": "Mention jobs in area",
    "avoid": "Don't lead with pricing"
  },
  "similar_wins": [
    {
      "lead": "Mike's Plumbing",
      "approach": "Reactivation script + jobs angle",
      "days_to_convert": 3
    }
  ]
}
```

---

## Data Model: What We Track

### 1. Script/Template Performance
```sql
CREATE TABLE content_performance (
  id UUID PRIMARY KEY,
  content_type VARCHAR(20), -- 'script', 'sms_template', 'objection_response'
  content_id UUID,

  -- Usage
  times_used INTEGER DEFAULT 0,

  -- Outcomes
  success_count INTEGER DEFAULT 0,
  callback_count INTEGER DEFAULT 0,
  conversion_count INTEGER DEFAULT 0,

  -- Segmented performance
  performance_by_trade JSONB, -- {"plumber": {"used": 50, "success": 23}, ...}
  performance_by_day JSONB,   -- {"monday": {"used": 30, "success": 15}, ...}
  performance_by_hour JSONB,  -- {"10": {"used": 20, "success": 12}, ...}
  performance_by_lead_temp JSONB, -- {"hot": {...}, "warm": {...}, ...}

  -- Trends
  last_7_days_success_rate DECIMAL,
  last_30_days_success_rate DECIMAL,
  trend VARCHAR(10), -- 'up', 'down', 'stable'

  updated_at TIMESTAMP
);
```

### 2. User Performance Patterns
```sql
CREATE TABLE user_patterns (
  id UUID PRIMARY KEY,
  user_id UUID,

  -- Time patterns
  best_call_day VARCHAR(10),
  best_call_hour INTEGER,
  best_sms_day VARCHAR(10),
  best_sms_hour INTEGER,

  -- Approach patterns
  best_opening_style VARCHAR(50), -- 'direct', 'rapport', 'value_lead'
  best_trade_vertical VARCHAR(50),
  avg_calls_to_convert DECIMAL,
  avg_touchpoints_to_convert DECIMAL,

  -- Strengths/weaknesses
  objection_handle_rate JSONB, -- {"too_expensive": 0.78, "too_busy": 0.45}

  updated_at TIMESTAMP
);
```

### 3. Market Intelligence Cache
```sql
CREATE TABLE market_intel (
  id UUID PRIMARY KEY,
  region VARCHAR(50), -- 'sydney', 'melbourne', etc.
  trade VARCHAR(50),  -- 'plumber', 'electrician', etc.

  -- Demand signals
  demand_index INTEGER, -- 0-100
  demand_trend VARCHAR(10), -- 'up', 'down', 'stable'
  demand_change_percent DECIMAL,

  -- Job data
  active_jobs_count INTEGER,
  avg_job_value DECIMAL,

  -- Competition
  competitor_activity JSONB,

  -- Perplexity research
  industry_news TEXT[],
  hiring_trends TEXT[],

  searched_at TIMESTAMP,
  expires_at TIMESTAMP
);
```

### 4. Pattern Library
```sql
CREATE TABLE discovered_patterns (
  id UUID PRIMARY KEY,
  pattern_type VARCHAR(50), -- 'conversion', 'timing', 'approach', 'objection'

  -- The pattern
  description TEXT, -- "Plumbers who go quiet for 3 weeks convert 43% with reactivation script"

  -- Conditions
  conditions JSONB, -- {"trade": "plumber", "days_quiet": [14, 28], "script": "reactivation"}

  -- Evidence
  sample_size INTEGER,
  confidence DECIMAL,
  success_rate DECIMAL,

  -- Status
  is_active BOOLEAN DEFAULT true,
  discovered_at TIMESTAMP,
  last_validated_at TIMESTAMP
);
```

---

## Phase 1: Foundation (Week 1)

### 1.1 Create Intelligence API
**File:** `src/routes/intelligence.js`

```javascript
// Core endpoint that powers everything
router.post('/intelligence', async (req, res) => {
  const { context, lead_id, request } = req.body;

  // Gather all context in parallel
  const [
    leadData,
    contentPerformance,
    userPatterns,
    marketIntel,
    similarWins,
    discoveredPatterns
  ] = await Promise.all([
    getLeadWithHistory(lead_id),
    getContentPerformance(context),
    getUserPatterns(req.user.id),
    getMarketIntel(leadData?.trade, leadData?.region),
    getSimilarWins(leadData),
    getRelevantPatterns(leadData)
  ]);

  // AI reasoning layer
  const recommendation = await generateRecommendation({
    context,
    request,
    leadData,
    contentPerformance,
    userPatterns,
    marketIntel,
    similarWins,
    discoveredPatterns
  });

  return res.json(recommendation);
});
```

### 1.2 Create Performance Tracking
**File:** `src/services/performanceTracker.js`

Track every interaction:
- Script used → outcome
- SMS sent → reply/conversion
- Objection response → worked/didn't
- Call time → outcome

### 1.3 Create Pattern Discovery Job
**File:** `src/jobs/patternDiscovery.js`

Daily job that:
- Analyzes last 30 days of data
- Finds statistically significant patterns
- Stores in `discovered_patterns` table
- Alerts when new patterns found

---

## Phase 2: Content Hub Integration (Week 2)

### 2.1 "What's Working" Dashboard
Top of Content Hub shows:
```
┌─────────────────────────────────────────────────────────────┐
│ 🧠 AI INSIGHTS - Updated 10 min ago                         │
│                                                             │
│ 🔥 HOT RIGHT NOW                                            │
│ "Reactivation Check-in" script is crushing it - 47% success │
│ this week (up from 31% last week)                          │
│                                                             │
│ 📈 PATTERN DETECTED                                         │
│ Your Tuesday 10am calls convert 2.3x better than average.  │
│ You have 5 callbacks scheduled for Friday - move them?     │
│ [Yes, Reschedule] [No Thanks]                              │
│                                                             │
│ 💡 TRY THIS                                                 │
│ Plumbers are responding well to "jobs in area" angle.      │
│ You have 3 plumber leads today - use this approach?        │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 2.2 Smart Script Recommendations
When viewing scripts:
```
┌─────────────────────────────────────────────────────────────┐
│ 📞 Reactivation Check-in                                    │
│                                                             │
│ ⭐ AI RECOMMENDED for your next 3 calls:                    │
│ • Mike's Plumbing (plumber, 3 weeks quiet) - 87% match     │
│ • Sparky Solutions (electrician, callback) - 72% match     │
│ • BuildRight Co (builder, re-engage) - 68% match           │
│                                                             │
│ 📊 PERFORMANCE                                              │
│ Overall: 34% success                                        │
│ For plumbers: 47% success ← your best trade                │
│ On Tuesdays: 52% success ← your best day                   │
│ At 10am: 61% success ← sweet spot!                         │
│                                                             │
│ 🏆 SIMILAR WINS                                             │
│ "Used this with Mike's Plumbing last week - converted in   │
│  2 calls after mentioning the 8 jobs in his area"          │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 2.3 AI Compose with Context
When composing SMS:
```
┌─────────────────────────────────────────────────────────────┐
│ ✨ AI COMPOSE                                               │
│                                                             │
│ Writing for: Mike's Plumbing (plumber, went quiet)         │
│                                                             │
│ 🧠 AI KNOWS:                                                │
│ • Plumbers respond to "jobs in area" (67% reply rate)      │
│ • Mike opened last SMS but didn't reply                    │
│ • 8 plumbing jobs posted in his area this week             │
│ • Best time to send: Tuesday 10am (your pattern)           │
│                                                             │
│ [Generate Smart Message]                                    │
│                                                             │
│ RESULT:                                                     │
│ "Hey Mike, saw 8 plumbing jobs come through in your area   │
│  this week - keen to send them your way? No stress if      │
│  you're sorted 👍"                                          │
│                                                             │
│ Predicted reply rate: 34% (above your average of 18%)      │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

---

## Phase 3: Call System Integration (Week 3)

### 3.1 Smart Intel Brief
Replace current brief with AI-powered version:
```
┌─────────────────────────────────────────────────────────────┐
│ 🧠 INTEL BRIEF - Mike's Plumbing                            │
│                                                             │
│ ═══ AI RECOMMENDATION ═══                                   │
│                                                             │
│ USE: "Reactivation Check-in" script                        │
│ CONFIDENCE: 87%                                             │
│                                                             │
│ WHY: Similar leads (plumber, 3 weeks quiet) convert at 43% │
│ with this script. Mike downloaded pricing guide but never   │
│ called - mention that.                                      │
│                                                             │
│ ═══ MARKET INTEL (Live) ═══                                 │
│                                                             │
│ 📈 Plumbing demand UP 23% in Sydney this week              │
│ 💼 8 plumbing jobs posted in Mike's area                   │
│ 📰 News: Plumber shortage hitting Sydney's west            │
│                                                             │
│ USE THIS: "Heaps of work coming through - just this week   │
│ we've got 8 plumbing jobs in your area"                    │
│                                                             │
│ ═══ YOUR PATTERNS ═══                                       │
│                                                             │
│ ✅ Tuesday 10am = your best time (52% success)             │
│ ✅ "Jobs in area" angle works for you (67% reply)          │
│ ⚠️ Avoid leading with pricing (drops success 30%)          │
│                                                             │
│ ═══ SIMILAR WIN ═══                                         │
│                                                             │
│ 🏆 Last week: "Converted Pete's Plumbing with same         │
│    approach - mentioned jobs in area, he signed up same    │
│    day. 3 calls total."                                    │
│                                                             │
│ ═══ PREDICTED OBJECTIONS ═══                                │
│                                                             │
│ 🛡️ "Too busy" (72% likely)                                 │
│    → Your response success rate: 78%                       │
│    → "Totally get it - that's actually why tradies love   │
│       us. Post when you need workers, we handle the rest." │
│                                                             │
│                    [Ready to Call]                          │
└─────────────────────────────────────────────────────────────┘
```

### 3.2 Live Call Intelligence
During call, AI assistant shows:
```
┌─────────────────────────────────────────────────────────────┐
│ 🎯 LIVE ASSIST                                              │
│                                                             │
│ CURRENT STAGE: Discovery                                    │
│ ████████░░░░░░░░ 45%                                        │
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 💡 AI DETECTED: He mentioned "too many calls"           │ │
│ │                                                         │ │
│ │ THIS WORKS (73% success):                               │ │
│ │ "I hear you - that's actually why we built RateRight    │ │
│ │  different. You post when YOU need workers, no cold     │ │
│ │  calls from us."                                        │ │
│ │                                                         │ │
│ │ [Copy] [Used It 👍] [Didn't Work 👎]                    │ │
│ └─────────────────────────────────────────────────────────┘ │
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 🔥 BUYING SIGNAL: "How many workers do you have?"       │ │
│ │                                                         │ │
│ │ HE'S INTERESTED! Close with:                            │ │
│ │ "Great question - we've got 200+ verified tradies in    │ │
│ │  your area. Want me to show you who's available for     │ │
│ │  your next job?"                                        │ │
│ │                                                         │ │
│ │ [Copy] [Closing Now...]                                 │ │
│ └─────────────────────────────────────────────────────────┘ │
│                                                             │
│ 📊 LIVE STATS                                               │
│ Call duration: 4:32                                         │
│ Sentiment: Positive (warming up)                            │
│ Conversion probability: 67% ↑                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 3.3 Post-Call Learning
After every call:
```
┌─────────────────────────────────────────────────────────────┐
│ 📊 CALL COMPLETE - Learning from this call                  │
│                                                             │
│ Duration: 8:34                                              │
│ Outcome: Callback scheduled                                 │
│                                                             │
│ 🧠 AI LEARNED:                                              │
│                                                             │
│ ✅ "Jobs in area" angle → led to callback                  │
│    (Adding to your success patterns)                       │
│                                                             │
│ ✅ "Reactivation Check-in" script → worked                 │
│    (Success rate now 48% for plumbers)                     │
│                                                             │
│ ✅ Objection "too busy" → handled successfully             │
│    (Your handle rate now 79%)                              │
│                                                             │
│ 📈 Pattern Strengthened:                                    │
│ "Plumbers who go quiet 2-4 weeks respond well to           │
│  jobs-in-area angle" (now 47 data points)                  │
│                                                             │
│                     [Done]                                  │
└─────────────────────────────────────────────────────────────┘
```

---

## Phase 4: Market Intelligence (Week 4)

### 4.1 Scheduled Perplexity Jobs
Daily job that researches:
- Trade demand by region
- Industry news
- Competitor activity
- Hiring trends

**File:** `src/jobs/marketIntelligence.js`

```javascript
// Run daily at 6am
async function refreshMarketIntel() {
  const trades = ['plumber', 'electrician', 'carpenter', 'builder', 'concreter'];
  const regions = ['sydney', 'melbourne', 'brisbane', 'perth'];

  for (const trade of trades) {
    for (const region of regions) {
      const intel = await perplexity.research(`
        ${trade} demand ${region} Australia 2026
        - Job posting trends
        - Hiring activity
        - Industry news
        - Average rates
      `);

      await storeMarketIntel(trade, region, intel);
    }
  }
}
```

### 4.2 Real-Time Intel Injection
During calls, surface relevant market intel:
```javascript
// When lead is a plumber in Sydney
const marketIntel = await getMarketIntel('plumber', 'sydney');

// Inject into call assist
"📈 Market Intel: Plumbing demand up 23% in Sydney.
 8 jobs posted in his area this week.
 Use: 'Heaps of work coming through right now'"
```

---

## Phase 5: Pattern Discovery (Week 5)

### 5.1 Automated Pattern Detection
Daily job that finds patterns:

```javascript
async function discoverPatterns() {
  // Find timing patterns
  const timingPatterns = await analyzeTimingPatterns();
  // "Tuesday 10am has 2.3x conversion rate"

  // Find approach patterns
  const approachPatterns = await analyzeApproachPatterns();
  // "Jobs in area angle has 67% reply rate for plumbers"

  // Find trade patterns
  const tradePatterns = await analyzeTradePatterns();
  // "Plumbers who go quiet 2-4 weeks convert at 43%"

  // Find objection patterns
  const objectionPatterns = await analyzeObjectionPatterns();
  // "Too busy objection handled 78% successfully with X response"

  // Store significant patterns
  for (const pattern of [...timingPatterns, ...approachPatterns, ...tradePatterns, ...objectionPatterns]) {
    if (pattern.confidence > 0.7 && pattern.sampleSize > 20) {
      await storePattern(pattern);
      await notifyUser(pattern); // Slack/in-app notification
    }
  }
}
```

### 5.2 Pattern Surfacing
Show patterns to users:
```
┌─────────────────────────────────────────────────────────────┐
│ 🧠 AI DISCOVERED - New Pattern                              │
│                                                             │
│ "Electricians who downloaded the pricing guide but didn't  │
│  sign up convert at 52% when you mention 'no lock-in       │
│  contracts' within the first 2 minutes."                   │
│                                                             │
│ Based on: 34 similar leads                                  │
│ Confidence: 87%                                             │
│                                                             │
│ You have 3 electricians matching this pattern in your      │
│ call list today.                                           │
│                                                             │
│ [Apply to These Leads] [Show Me the Data] [Dismiss]        │
└─────────────────────────────────────────────────────────────┘
```

---

## Phase 6: A/B Testing Engine (Week 6)

### 6.1 Automatic Variation Testing
AI creates and tests variations:

```javascript
// AI notices a high-performing script
// Generates 2 variations to test

const variations = await generateVariations(topScript, {
  keepCore: true,
  varyElements: ['opener', 'value_prop', 'close']
});

// Randomly assign to 20% of matching calls
// Track performance over 50 uses each
// Promote winner, retire losers
```

### 6.2 Testing Dashboard
```
┌─────────────────────────────────────────────────────────────┐
│ 🧪 A/B TESTS RUNNING                                        │
│                                                             │
│ TEST: Reactivation Script - Opener Variation                │
│ Status: Running (34/50 calls)                               │
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ A (Control): "Hey {name}, just checking in..."          │ │
│ │ Success rate: 43% (18/42 calls)                         │ │
│ │ ████████████████████░░░░░                               │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ B (Variant): "Hey {name}, quick question..."            │ │
│ │ Success rate: 51% (16/34 calls) ← LEADING               │ │
│ │ █████████████████████████░░░░                           │ │
│ └─────────────────────────────────────────────────────────┘ │
│                                                             │
│ Estimated completion: 3 days                                │
│ Statistical significance: 72% (need 95%)                    │
│                                                             │
│ [Pause Test] [End Early] [View Details]                     │
└─────────────────────────────────────────────────────────────┘
```

---

## Implementation Order

### Week 1: Foundation
- [ ] Create `content_performance` table
- [ ] Create `user_patterns` table
- [ ] Create `market_intel` table
- [ ] Create `discovered_patterns` table
- [ ] Build Intelligence API endpoint
- [ ] Build performance tracking service

### Week 2: Content Hub Integration
- [ ] Build ContentHub.jsx with tabs
- [ ] Add "What's Working" dashboard section
- [ ] Add AI recommendations to script cards
- [ ] Integrate smart compose for SMS

### Week 3: Call System Integration
- [ ] Upgrade IntelBriefModal with AI recommendations
- [ ] Add confidence scores and reasoning
- [ ] Integrate market intel into pre-call brief
- [ ] Add pattern display to call assist
- [ ] Build post-call learning feedback

### Week 4: Market Intelligence
- [ ] Build Perplexity scheduled jobs
- [ ] Create market intel caching system
- [ ] Integrate live market intel into calls
- [ ] Build trade-specific talk tracks

### Week 5: Pattern Discovery
- [ ] Build pattern discovery job
- [ ] Create pattern notification system
- [ ] Add pattern surfacing to UI
- [ ] Build pattern management (activate/retire)

### Week 6: A/B Testing
- [ ] Build variation generator
- [ ] Create test assignment system
- [ ] Build testing dashboard
- [ ] Create auto-promotion logic

### Week 7: Personal Intel (from personal-intel-plan.md)
- [ ] Extend `searchPerson()` to include personal profile (family, hobbies, interests)
- [ ] Add `searchPersonalNews()` for hobby/interest-related news
- [ ] Extend `lead_intel` table with personal columns
- [ ] Build PersonalProfileCard component
- [ ] Add conversation starters to Intel Brief
- [ ] Add rapport tracking to learning engine

**Personal Intel Vision:**
```
👨‍👩‍👧‍👦 Married, 2 kids  🎣 Fishing  ⛳ Golf  🏉 Rugby

💬 OPEN WITH:
"Hey John - how'd the fishing trip go last weekend?
 Saw you posted about Lake Eucumbene."

📰 NEWS HE'D CARE ABOUT:
• NRL finals start next week
• Lake Eucumbene stocking report just released
```

---

## Success Metrics

| Metric | Current | Target |
|--------|---------|--------|
| Script recommendation accuracy | N/A | 70%+ |
| Call conversion rate | ~25% | 40%+ |
| SMS reply rate | ~12% | 25%+ |
| Time to find right script | Manual | < 5 sec |
| Pattern discovery | Manual | Automated daily |
| A/B tests running | 0 | 3+ always |

---

## Files to Create

### Backend
- `src/routes/intelligence.js` - Main AI endpoint
- `src/services/intelligenceEngine.js` - Core logic
- `src/services/performanceTracker.js` - Track everything
- `src/services/patternDiscovery.js` - Find patterns
- `src/services/abTesting.js` - Variation testing
- `src/jobs/marketIntelligence.js` - Daily market research
- `src/jobs/patternDiscovery.js` - Daily pattern analysis

### Frontend
- `admin/src/pages/ContentHub.jsx` - Unified content page
- `admin/src/components/content/CallsTab.jsx`
- `admin/src/components/content/SMSTab.jsx`
- `admin/src/components/content/ObjectionsTab.jsx`
- `admin/src/components/content/SettingsTab.jsx`
- `admin/src/components/ai/WhatsWorking.jsx` - Dashboard widget
- `admin/src/components/ai/AIRecommendation.jsx` - Recommendation card
- `admin/src/components/ai/PatternAlert.jsx` - Pattern notification
- `admin/src/components/ai/ABTestDashboard.jsx` - Testing UI

### Database
- `supabase/migrations/ai_sales_brain.sql`

---

## The 0.1% Difference

**Before (Current):**
> "Here's an intel brief. Here are some scripts. Good luck."

**After (AI Sales Brain):**
> "Call Mike now with the Reactivation script. Similar plumbers convert at 47% with this approach. Mention the 8 jobs in his area - that angle works 67% of the time for you. It's Tuesday 10am - your best window. Last week you converted Pete's Plumbing the same way."

---

**Ready to build?**
