# RateRight Growth Engine - Build Guide

## Project Status

**Last Updated:** 2026-01-31 (P0 Auth Bug Fix - Railway Nixpacks auto-rebuild)

| Component | Status | Notes |
|-----------|--------|-------|
| Session 1: Scaffolding | ✅ COMPLETE | Express API deployed |
| Session 2: Twilio Inbound | ✅ COMPLETE | Webhook endpoint live |
| Session 3: Lead CRUD | ✅ COMPLETE | API endpoints live |
| Session 4: SMS Sending | ✅ COMPLETE | Outbound SMS |
| Session 5: Call Logging | ✅ COMPLETE | Log calls with transcripts |
| Session 6: Lead Scoring | ✅ COMPLETE | Scoring algorithm |
| Session 7: Call List | ✅ COMPLETE | Daily prioritized list |
| Session 8: Slack Integration | ✅ COMPLETE | Notifications |
| Sessions 9-13: Admin UI | ✅ COMPLETE | Mobile-first React app |
| Session 14: Platform Sync | ✅ COMPLETE | Poll RateRight API |
| Session 15: Cron Jobs | ✅ COMPLETE | Daily summary |
| Learning System Phase 1 | ✅ COMPLETE | Conversion patterns, feedback |
| Auto-Transcription | ✅ COMPLETE | Every call transcribed |
| Auto-Summary | ✅ COMPLETE | AI summary on call end |
| Ideas Capture | ✅ COMPLETE | Voice Assistant ideas |
| Activity Page | ✅ COMPLETE | Manager call reporting |
| Real-Time Updates | ✅ COMPLETE | Live notifications via Supabase |
| Weekly Report | ✅ COMPLETE | Monday 7am to Slack |
| Auto-Tune Call List | ✅ COMPLETE | Pattern-based lead boosting |
| Gamification Battleground | ✅ COMPLETE | XP, levels, badges, leaderboard |
| Messages Hub 0.1% | ✅ COMPLETE | Long-press, entity detection, AI writer |
| **Sales Playbook** | ✅ COMPLETE | Brand guidelines, scripts, compliance (was Scripts Command Center) |
| Desktop UI Fix | ✅ COMPLETE | NavLink, active states, More dropdown |
| Messages Mobile Fix | ✅ COMPLETE | Input visibility, VoiceAssistant hidden |
| **Messages UI Overhaul** | ✅ COMPLETE | Search, New Message, Done action, unknown numbers |
| **Call Recording Playback** | ✅ COMPLETE | Play call recordings in Lead Profile |
| **Manager Dashboard** | ✅ COMPLETE | Team overview, rep stats, coaching insights |
| **Power Dialer** | ✅ COMPLETE | Auto-advance with 2-min study timer |
| **Performance: Compression** | ✅ COMPLETE | 70% smaller transfers, 1yr asset cache |
| **Security Audit Fixes** | ✅ COMPLETE | CORS, Twilio validation, debug endpoints removed |
| **Dashboard Fixes** | ✅ COMPLETE | RepliesWaiting now uses consolidated API |
| **UI Consolidation** | ✅ COMPLETE | Removed Prompts/Scripts, unified to Sales Playbook |
| **Bug Report Button** | ✅ COMPLETE | Floating bug button restored, sends to Slack |
| **GitHub Private** | ✅ COMPLETE | Repository visibility set to private |
| **Mobile Fixes** | ✅ COMPLETE | Lead page action bar, Intel Edit button |
| **Inbound Call Transcription** | ✅ COMPLETE | Integrated with CallContext |
| **Actionable Playbook** | ✅ COMPLETE | Today's Plays + Bulk Outreach in Strategy Modal |
| **Voicemail Drop** | ✅ COMPLETE | One-click pre-recorded VM drops on calls |
| **PWA Mobile App** | ✅ COMPLETE | Install prompt, offline indicator, service worker |
| **Battleground User ID Fix** | ✅ COMPLETE | Fixed 17 routes using wrong user ID pattern |
| **AI Caching** | ✅ COMPLETE | 2-hour cache for intel-brief and script recommendations |
| **Inbound Call Logging** | ✅ COMPLETE | CallOutcomeSheet now shows after inbound calls |
| **Twilio Device Fix** | ✅ COMPLETE | Only re-register if device not destroyed |
| **Worker Referral Capture** | ✅ COMPLETE | Modal in CallOutcomeSheet for tradie referrals |
| **Business Intel Display** | ✅ COMPLETE | Cards in LeadProfile + CallPrepPage |
| **SMS Sequences v1** | ✅ COMPLETE | Basic sequence automation after no-answer |
| **SMS Sequences v2** | ✅ COMPLETE | Stage-based + randomized timing |
| **Caching Analysis** | ✅ COMPLETE | docs/caching-opportunities.md |
| **Docs Index** | ✅ COMPLETE | docs/INDEX.md navigation guide |
| **Battleground V2** | ✅ COMPLETE | XP Duels + Manager Challenges + Sound Celebrations |
| **AI Sequence Suggestions** | ✅ COMPLETE | Purple badge in Messages suggesting sequence enrollment |
| **Call List Search** | ✅ COMPLETE | Search/filter leads in Call List |
| **Quality Audit Upgrade** | ✅ COMPLETE | 10 categories, 40+ tests, unified alerting |
| **Dark Mode + Skeleton Loading** | ✅ COMPLETE | System preference detection, theme persistence |
| **Micro-Optimizations** | ✅ COMPLETE | 43 optimizations across 6 phases |
| **Messages Hub Phase 1** | ✅ COMPLETE | Add to Sequence button, tooltips, filter tabs |
| **Messages Hub Phase 2** | ✅ COMPLETE | Archive/unarchive, enhanced conversation header |
| **Messages Hub Phase 3** | ✅ COMPLETE | Sequence filter, bulk actions |
| **Clawdbot Integration** | ✅ COMPLETE | API key auth, Telegram bot access |
| **Notion Integration** | ✅ COMPLETE | Business state, metrics, knowledge base sync |
| **Mae & Vena Onboarding** | ✅ COMPLETE | Added to user allowlist |
| **Ice Breakers UI** | ✅ COMPLETE | Ice breakers section at top of active call |
| **Sales Funnel Panel** | ✅ COMPLETE | Full-screen funnel with intel during calls |
| **Send to Similar Leads** | ✅ COMPLETE | Batch personalized messaging after send |
| **Two-way Call Transcription** | ✅ COMPLETE | Twilio Media Streams for both sides |
| **Personal Intel CallPrep** | ✅ COMPLETE | Collapsible personal intel section |
| **RLS Fixes (Session 21)** | ✅ COMPLETE | supabaseAdmin for sequences, dossier, enrollments |
| **Auto-Enroll on No-Answer** | ✅ COMPLETE | Backend triggers sequence enrollment |
| **Manual Start Sequence** | ✅ COMPLETE | Button in Lead Profile to start sequences |
| **Column Name Fixes** | ✅ COMPLETE | leads.name/trade → first_name/last_name/metadata |
| **SMS Phone Normalization** | ✅ COMPLETE | Normalize lead phone before Twilio send + better errors |
| **SMS Scheduler RLS Fix** | ✅ COMPLETE | sequenceProcessor + scheduledSms use supabaseAdmin, startup processing |
| **Intelligence Alerts Enhancement** | ✅ COMPLETE | API failure, SMS delivery, performance degradation alerts |
| **Self-Improvement System** | ✅ COMPLETE | Auto-adjust thresholds, learn from successful suggestions |
| **P0 Auth Bug Fix** | ✅ COMPLETE | Railway Nixpacks was rebuilding frontend without VITE_* vars |

---

## Deployed Infrastructure

| Service | URL | Status |
|---------|-----|--------|
| Railway API | https://rateright-growth-production.up.railway.app | ✅ Live |
| Supabase | https://memscjotxrzqnhrvnnkc.supabase.co | ✅ Live |
| GitHub | https://github.com/mcloughlinmichaelr-debug/rateright-growth | ✅ Live |
| Admin UI | Deploy to Vercel/Netlify (see admin/ folder) | 📦 Ready |

---

## Environment Variables (Railway)
```
SUPABASE_URL=https://memscjotxrzqnhrvnnkc.supabase.co
SUPABASE_ANON_KEY=<set>
NODE_ENV=production
TWILIO_ACCOUNT_SID=<set>
TWILIO_AUTH_TOKEN=<set>
TWILIO_PHONE_NUMBER=+61468087171
SLACK_WEBHOOK_URL=<set>
RATERIGHT_API_URL=https://rateright.com.au/api
RATERIGHT_ADMIN_API_KEY=jBpFaG5Z6LJE4b
```

---

## File Structure

```
rateright-growth-deploy/
├── src/
│   ├── config/
│   │   └── database.js         # Supabase client + supabaseAdmin
│   ├── middleware/
│   │   ├── auth.js             # JWT authentication middleware
│   │   └── requestLogger.js    # Request timing middleware
│   ├── routes/
│   │   ├── health.js           # GET /health
│   │   ├── webhooks.js         # POST /api/webhooks/twilio/*
│   │   ├── leads.js            # CRUD /api/leads
│   │   ├── sms.js              # POST /api/sms/*
│   │   ├── calls.js            # POST /api/calls/log
│   │   ├── callList.js         # GET /api/call-list
│   │   ├── jobs.js             # POST /api/jobs/:name
│   │   ├── ai.js               # AI endpoints
│   │   ├── voice.js            # Twilio Voice SDK (in-app calling)
│   │   └── voicemail.js        # Voicemail drop feature
│   ├── services/
│   │   ├── twilio.js           # SMS sending
│   │   ├── slack.js            # Slack notifications
│   │   ├── templates.js        # SMS template rendering
│   │   ├── scoring.js          # Lead scoring algorithm
│   │   ├── ai.js               # OpenAI integration
│   │   └── deepgram.js         # Live transcription
│   ├── jobs/
│   │   ├── index.js            # Job scheduler
│   │   ├── platformSync.js     # RateRight API sync
│   │   └── dailySummary.js     # Daily metrics
│   ├── utils/
│   │   ├── phone.js            # AU phone normalization
│   │   ├── validation.js       # Input validation + sanitization
│   │   ├── logger.js           # Structured logging
│   │   └── intent.js           # SMS intent classification
│   └── index.js                # Express app
├── admin/                      # Mobile-first React UI
│   ├── src/
│   │   ├── api/client.js       # API client (includes AI methods)
│   │   ├── components/
│   │   │   ├── BottomNav.jsx   # Mobile navigation
│   │   │   ├── LeadCard.jsx    # Lead display card
│   │   │   ├── CallOutcomeModal.jsx
│   │   │   ├── IntelBriefModal.jsx    # AI pre-call brief
│   │   │   ├── PostCallSummarySheet.jsx  # AI call analysis
│   │   │   ├── AIMessageWriter.jsx    # AI SMS drafting
│   │   │   ├── LiveCopilot.jsx        # Real-time call AI
│   │   │   ├── AIInsightsWidget.jsx   # Dashboard AI widget
│   │   │   ├── PredictiveScoreBadge.jsx # AI probability
│   │   │   ├── VoiceAssistant.jsx     # Voice commands
│   │   │   ├── VoiceNoteButton.jsx    # Voice notes
│   │   │   ├── TwilioCall.jsx         # In-app calling UI
│   │   │   └── ErrorBoundary.jsx      # React error handling
│   │   ├── pages/
│   │   │   ├── Dashboard.jsx   # Stats + AI insights
│   │   │   ├── CallList.jsx    # Prioritized call list
│   │   │   ├── Leads.jsx       # Lead list + filters
│   │   │   ├── LeadProfile.jsx # Lead detail + AI tools
│   │   │   ├── Messages.jsx    # Smart messaging hub
│   │   │   └── Battleground.jsx # Sales competition
│   │   ├── context/
│   │   │   ├── AuthContext.jsx # Supabase auth
│   │   │   └── CallContext.jsx # Global in-app calling state
│   │   ├── App.jsx             # Router + Voice Assistant
│   │   └── index.css           # Tailwind styles
│   └── package.json
├── supabase/
│   ├── schema.sql              # Database schema
│   └── ai-schema.sql           # AI tables schema
├── BUILD-GUIDE.md
└── package.json
```

---

## API Reference

### Health
```
GET /health
```

### Leads
```
GET    /api/leads                    # List (filters: status, score_min, score_max, search)
GET    /api/leads/:id                # Get with communications, notes, callbacks
POST   /api/leads                    # Create
PATCH  /api/leads/:id                # Update
DELETE /api/leads/:id                # Soft delete
```

### SMS
```
GET  /api/sms/templates              # List templates
POST /api/sms/send                   # Send single SMS
POST /api/sms/batch                  # Send to multiple leads
POST /api/sms/preview                # Preview template
```

### Calls
```
GET  /api/calls/outcomes             # List valid outcomes
POST /api/calls/log                  # Log call outcome
```

### Call List
```
GET /api/call-list                   # Prioritized daily list
GET /api/call-list/stats             # Lead statistics
```

### Jobs (Admin)
```
GET  /api/jobs                       # List available jobs
POST /api/jobs/platformSync          # Trigger platform sync
POST /api/jobs/dailySummary          # Trigger daily summary
POST /api/jobs/recalculateScores     # Recalculate all scores
```

### Webhooks
```
POST /api/webhooks/twilio/inbound    # Receive SMS
POST /api/webhooks/twilio/status     # SMS delivery status
```

---

## Admin UI (Mobile-First)

### Features
- **Bottom navigation** for mobile (hidden on desktop)
- **44px minimum tap targets** for touch
- **Click-to-call** phone numbers (`tel:` links)
- **Single column layouts** on mobile
- **Desktop sidebar** on larger screens
- **Pull to refresh** support
- **Optimized for one-thumb operation**

### Pages
1. **Dashboard** - Stats overview, quick actions, AI wisdom
2. **Call List** - Focus mode for sequential calling
3. **Leads** - Searchable, filterable list
4. **Lead Profile** - Full details, SMS, call logging
5. **Messages** - Smart messaging hub with AI features
6. **Battleground** - Team competition & leaderboards

### Run Locally
```bash
cd admin
npm install
npm run dev
```

### Deploy to Vercel
```bash
cd admin
npm run build
# Deploy dist/ folder to Vercel or Netlify
```

### Environment
Create `admin/.env`:
```
VITE_API_URL=https://rateright-growth-production.up.railway.app
```

---

## Lead Scoring

| Activity | Score Change |
|----------|-------------|
| SMS reply (positive) | +40 |
| SMS reply (question) | +20 |
| SMS reply (negative) | -100 |
| Call connected | +10 |
| Call interested | +30 |
| Call not interested | -50 |
| Platform job posted | +50 |
| Platform worker hired | +30 |
| Platform login (7d) | +20 |
| No response 14 days | -20 |
| Days since contact (>7) | -2/day |

### Score Tiers
- **Hot**: 70-100
- **Warm**: 50-69
- **Cool**: 20-49
- **Cold**: 0-19
- **Dead**: Below 0

---

## Scheduled Jobs

| Job | Schedule | Description |
|-----|----------|-------------|
| Platform Sync | Every 15 min | Syncs activity from RateRight |
| Score Recalculation | Every hour | Updates all lead scores |
| Daily Summary | 7am AEST | Slack summary + metrics |

---

## Twilio Configuration

**Phone:** +61 468 087 171

**Webhook URL:**
```
https://rateright-growth-production.up.railway.app/api/webhooks/twilio/inbound
```

**Method:** POST

---

## Team

| Name | Role | Primary Use |
|------|------|-------------|
| Tony McCabe | Sales Director | Call List, Call Logging |
| Angelica | GM Remote Operations | Inbox, Lead Profiles |
| Michael | Founder | Dashboard |
| Markus | Developer | Code review |

---

## Changelog

### 2026-01-28 - Objections Management API

**COMPLETE**

Added CRUD API for managing sales objections and rebuttal scripts.

**Files Created:**
- `src/routes/objections.js` - GET/POST/PUT/DELETE endpoints
- `supabase/sales-rebuttals-migration.sql` - Table creation

**Files Modified:**
- `src/index.js` - Route registration with X-API-Key + writeLimiter
- `supabase/PENDING_MIGRATIONS.md` - Added ⬜ pending migration

**API Endpoints:**
- `GET /api/objections` - List all (filter by category, search, tag)
- `POST /api/objections` - Create new
- `PUT /api/objections/:id` - Update
- `DELETE /api/objections/:id` - Delete

**Notes:**
- Uses `gen_random_uuid()` (not uuid_generate_v4) per LESSONS.md
- Uses `supabaseAdmin || supabase` pattern for RLS tables
- Supports both X-API-Key and JWT auth

---

### 2026-01-21 (Session 23 - Intelligence Dashboard Enhancements)

**COMPLETE**

Enhanced the 0.1% Intelligence System with additional critical alerts and self-improvement capabilities.

**New Critical Alerts (3 types added to criticalAlerts.js):**
- **API Failure Detection** - Detects Twilio/OpenAI outages (5+ failures in 5min)
- **SMS Delivery Monitoring** - Alerts on >20% delivery failure rate (hourly check)
- **Performance Degradation** - Detects slow APIs >5s response (3+ in 5min)

**Self-Improvement System (new selfImprovement.js):**
- Auto-adjust thresholds based on 30-day performance data
- Learn from successful suggestions to improve future recommendations
- Track threshold changes in `intelligence_adjustments` table
- Integrated with Monthly Deep Dive job

**Files Changed:**
- `src/services/criticalAlerts.js` - Added 3 new alert functions + thresholds
- `src/services/selfImprovement.js` - NEW - Auto-adjustment logic
- `src/jobs/monthlyDeepDive.js` - Integrated self-improvement report

**Database Migration:**
- `supabase/self-improvement-schema.sql` - system_settings, intelligence_adjustments tables

**Verification:**
- All pages already have tracking hook instrumented (CallPrep, Messages, LeadProfile, CallList)
- Friction detection system fully operational
- Weekly Excellence Report fully built

---

### 2026-01-20 (Session 22 - Quality Audit Upgrade)

**COMPLETE**

Upgraded the 0.1% Quality Audit system from basic DB checks to comprehensive monitoring.

**New Test Categories (10 total):**
- 📊 **Business Metrics** - SMS delivery rate, call outcome logging, speed-to-lead, conversion tracking
- 🧪 **Synthetic Journeys** - Lead CRUD flow, SMS template validation, call list generation performance
- 📱 **Frontend Quality** - LCP, INP, CLS, FCP, TTFB from web-vitals

**Frequent Monitoring:**
- 15-minute critical checks (DB, API health)
- Hourly external service checks (Twilio, OpenAI, Deepgram)
- Daily full audit at 6am AEST (all categories)

**Unified Alerting:**
- Failed tests create alerts in `intelligence_alerts` table
- Severity mapping: critical → critical, api/external → high, business → medium, frontend → low
- 30-minute cooldown prevents duplicate alerts
- Auto-resolution when tests pass again

**Frontend Tracking:**
- Web Vitals collection via `web-vitals` package
- Error tracking captures uncaught errors, React boundary errors, unhandled rejections
- Data stored in new `web_vitals` and `frontend_errors` tables

**New API Endpoints:**
- `GET /api/jobs/audit-history?days=7` - Audit trend analysis
- `GET /api/jobs/audit-latest` - Most recent audit result
- `POST /api/analytics/vitals` - Store web vital metrics
- `POST /api/analytics/error` - Store frontend errors
- `GET /api/analytics/vitals/summary` - Vitals summary stats

**Files Created:**
- `src/jobs/frequentAudit.js` - 15-min and hourly audit scheduler
- `admin/src/utils/webVitals.js` - Web vitals collection
- `admin/src/utils/errorTracking.js` - Frontend error tracking
- `supabase/quality-audit-upgrade-schema.sql` - New tables

**Files Modified:**
- `src/services/qualityAudit.js` - Added 3 new test categories
- `src/jobs/index.js` - Added frequent audit intervals
- `src/routes/jobs.js` - Added audit history endpoints
- `src/routes/analytics.js` - Added vitals and error endpoints
- `admin/src/main.jsx` - Initialize web vitals and error tracking
- `admin/src/components/ErrorBoundary.jsx` - Report errors to backend
- `admin/package.json` - Added web-vitals dependency

**Migration Required:**
- Run SQL from `supabase/quality-audit-upgrade-schema.sql` in Supabase

---

### 2026-01-19 (Undocumented Features - Discovered in Audit)

**Previously undocumented features found in git history:**

- **AI Sequence Suggestions** (a472dec)
  - Backend analyzes conversations and suggests sequence enrollment
  - Criteria: Early stage leads, no active sequence, 2+ days since last message
  - UI: Purple badge shows 'SUGGEST SEQUENCE: [reason]'
  - Actions: Start Sequence button enrolls in stage-appropriate sequence

- **Call List Search** (2418695)
  - Search/filter functionality added to Call List page
  - Filter leads by name, phone, or company

---

### 2026-01-19 (Session 19 - Bug Audit + New Features)

**COMPLETE**

Comprehensive codebase audit and two new features.

**New Features:**
- **Worker Referral Capture UI** - Modal in CallOutcomeSheet for capturing tradies referrals during calls
  - Phone validation with Australian format normalization
  - Promise.allSettled for partial success on batch creates
  - Auto-links referrals to referring lead
- **Business Intel Display** - Cards showing pain points, competitors, hiring needs
  - Added to LeadProfile as BusinessIntelCard
  - Added expandable section to CallPrepPage
  - Business intel included in live-intel API response

**Bug Fixes Applied:**
- Phone validation with error messages in WorkerReferralCapture
- Promise.allSettled for batch operations (partial success supported)
- Rate limiting on /draft-message endpoint
- Database error handling on communications insert
- Array key fixes (content-based keys instead of index)
- Null safety improvements across components

**Files Created:**
- `admin/src/components/WorkerReferralCapture.jsx`
- `admin/src/components/BusinessIntelCard.jsx`

**Files Modified:**
- `admin/src/components/CallOutcomeSheet.jsx` - Added referral capture
- `admin/src/pages/LeadProfile.jsx` - Added BusinessIntelCard
- `admin/src/pages/CallPrepPage.jsx` - Added business intel section, fixed keys
- `src/routes/ai.js` - Added business_intel to live-intel, rate limiting, error handling

---

### 2026-01-19 (Session 20 - SMS Sequences)

**COMPLETE**

Automated SMS follow-up sequences after no-answer calls.

**Features:**
- **Sequence Processor Job** - Runs every 60s, processes due enrollments, respects AEST business hours
- **Enrollment API** - List sequences, enroll/unenroll leads, pause/resume/skip/send-now
- **Auto-Pause on Reply** - Sequences automatically pause when lead responds to SMS
- **Seed Sequences** - Created "New Worker Outreach" and "New Contractor Outreach" (4 steps, 7 days each)
- **CallOutcomeSheet Toggle** - When outcome is "No Answer", shows toggle to start follow-up sequence
- **SequenceQueue Component** - View active enrollments on SalesPlaybook page, filter by due today
- **Lead Profile Status** - Shows active/paused sequence with pause/resume buttons

**Migrations Applied:**
- `20260119113451_sequence_automation.sql` - Schema enhancements (next_step_at, pause_reason, channel, indexes)
- `20260119113909_seed_sequences.sql` - Seed sequences + steps

**Files Created:**
- `src/jobs/sequenceProcessor.js`
- `src/routes/sequences.js`
- `admin/src/components/playbook/SequenceQueue.jsx`

**Files Modified:**
- `src/index.js` - Register sequences routes
- `src/jobs/index.js` - Add sequence processor to scheduler
- `src/routes/webhooks.js` - Auto-pause on inbound SMS
- `admin/src/api/client.js` - Add sequencesApi
- `admin/src/components/CallOutcomeSheet.jsx` - Add enroll toggle
- `admin/src/pages/SalesPlaybook.jsx` - Add SequenceQueue component
- `admin/src/pages/LeadProfile.jsx` - Add SequenceStatusCard

---

### 2026-01-18 (Undocumented Features - Discovered in Audit)

**Previously undocumented features found in git history:**

- **Ice Breakers UI** (3f43c8a)
  - Ice breakers section at top of active call UI
  - Shows conversation starters from personal intel
  - Preloaded intel for instant display on call start

- **Sales Funnel Panel** (bd9e845)
  - Full-screen Sales Funnel with intel & talking points
  - Shows lead stage, next actions, objection history
  - Added to call window for easy reference during calls

- **Send to Similar Leads** (d4ae649)
  - Batch personalized messaging after sending to one lead
  - Find leads in same stage/trade and send personalized variants
  - SimilarLeadsPrompt component on LeadProfile

- **User Access** (various commits)
  - Added Cathy Reily (cathyrei@gmail.com)
  - Added Stephen (stephen@rftn.com.au)
  - Added Cormick Cronin

---

### 2026-01-18 (Session 11 - Bug Fixes Continued)

**COMPLETE**

Bug fixes for SalesPlaybook crash and call state management.

**Bug Fixes:**
- **SalesPlaybook crash** - "Something went wrong" error when clicking "Re-engage with Script"
  - Division by zero when calculating reply rate percentage
  - Scripts with `times_used = 0` caused `NaN` from division
  - Fixed: Added `script.times_used > 0` guard before calculating percentage
- **Incoming calls to voicemail** - Calls received while on notes screen went to voicemail
  - Fixed: Reset call state immediately on new incoming call
  - Reduced post-call reset delay from 2s to 500ms
  - Added auto re-register on device unregistration
- **VoiceAssistant missing** - Floating mic button was removed
  - Restored from git history (commit 10245ea)
  - Re-added to App.jsx

**Performance:**
- Added `compression` middleware - 70% smaller transfers
- Static assets cached 1 year (immutable, content-hashed)

**Data Cleanup:**
- Fixed 4 orphan/null-date callbacks causing "491295 hrs overdue" display
- Soft-deleted test accounts

**Files Modified:**
- `admin/src/pages/SalesPlaybook.jsx` - Division by zero fix
- `admin/src/components/IncomingCallHandler.jsx` - Call state management
- `admin/src/components/VoiceAssistant.jsx` - Restored
- `admin/src/App.jsx` - Restored VoiceAssistant
- `src/index.js` - Compression, caching headers
- `src/routes/dashboard.js` - Callback date guards

---

### 2026-01-18 (Session 10 - Mobile Fixes & Intel Edit)

**COMPLETE**

Mobile UI fixes and Intel Edit modal bug fix.

**Bug Fixes:**
- **Lead page mobile** - Action bar (Call/SMS buttons) was hidden behind BottomNav
  - Fixed: Changed `bottom-0` to `bottom-16 md:bottom-0`
- **Intel Edit button** - "Save" was failing with database error
  - Missing columns: `user_notes`, `manually_updated`, `updated_by`, `notes_updated_at`
  - Applied migration `20260117235816_intel_edit_support.sql` via CLI
- **Inbound call transcription** - Wasn't working when receiving calls
  - Added `acceptInboundCall()` to CallContext
  - Integrated IncomingCallHandler with CallContext for transcription

**New Features:**
- **Intel Edit button** - Added to IntelSummaryCard header
  - Opens IntelEditModal for editing company/person intel
  - Voice note support for hands-free editing

**Files Modified:**
- `admin/src/components/LeadActionBar.jsx` - Fixed mobile positioning
- `admin/src/components/IntelSummaryCard.jsx` - Added Edit button
- `admin/src/context/CallContext.jsx` - Added inbound call support
- `admin/src/components/TwilioCall.jsx` - Added `attachToInboundCall()`
- `admin/src/components/IncomingCallHandler.jsx` - Integrated with CallContext

**Migration Applied:**
- `supabase/migrations/20260117235816_intel_edit_support.sql`

---

### 2026-01-18 (Session 9 - Performance & Fixes)

**COMPLETE**

Performance optimizations and bug fixes.

**Performance:**
- Added `compression` middleware - 70% smaller transfers
- vendor-twilio: 180KB → 47KB gzipped
- vendor-supabase: 170KB → 44KB gzipped
- index.js: 387KB → 121KB gzipped
- Static assets cached 1 year (immutable, content-hashed)
- Load times: 48s → ~3s

**Bug Fixes:**
- Slipping Away "Re-engage with Script" now opens Scripts Command Center (was /prompts)
- Fixed "491295 hrs overdue" callback bug (null dates = epoch)
- Fixed `leads.notes` column not found error
- Added error handling to ScriptsCommandCenter for missing tables

**Data Cleanup:**
- Soft-deleted "Debug Test" test account
- Cleaned up 4 orphan/null-date callbacks

**Security:**
- GitHub repository set to private

**Files Modified:**
- `src/index.js` - Added compression, caching headers
- `src/routes/dashboard.js` - Fixed callback date guards, removed notes column
- `admin/src/pages/ScriptsCommandCenter.jsx` - Added error handling
- `admin/src/components/dashboard/SlippingLeads.jsx` - Fixed navigation

---

### 2026-01-18 (Power Dialer)

**COMPLETE**

Auto-advance call system with configurable study time before each call.

**Features:**
- Power Dial button in Call List header
- Configuration modal with study time options (30s, 1m, 2m, 3m, 5m)
- Default 2-minute study timer on Call Prep page
- Auto-dial when timer reaches 0
- Pause/Resume timer controls
- "Call Now" to skip timer
- Session stats tracking (calls made, conversions, talk time)
- Progress indicator showing remaining leads
- Auto-advance to next lead after logging outcome

**Flow:**
1. Start Power Dial → Select study time
2. Navigate to first lead's Call Prep page
3. 2-minute countdown timer
4. Auto-dial when timer ends
5. Call → Log outcome → Auto-advance to next lead
6. Repeat until queue empty

**Files Created:**
- `admin/src/context/PowerDialerContext.jsx` - Timer, queue, session management

**Files Modified:**
- `admin/src/App.jsx` - Added PowerDialerProvider
- `admin/src/pages/CallList.jsx` - Power Dial button + modal
- `admin/src/pages/CallPrepPage.jsx` - Timer UI, auto-dial logic
- `admin/src/components/CallOutcomeSheet.jsx` - Pass outcome/duration

**Bug Fix:**
- Fixed race condition where auto-dial fired immediately on lead change
- Added `timerWasRunningRef` to ensure timer actually counted down before auto-dial

---

### 2026-01-18 (Manager Dashboard)

**COMPLETE**

Dark-themed manager dashboard for team oversight and coaching.

**Features:**
- Team stats overview (calls, conversions, talk time)
- Period comparison (vs yesterday/last week)
- Rep breakdown with individual performance
- Coaching insights (who needs help, who's crushing it)
- Filter by period (today, week, month)

**API Endpoints:**
- `GET /api/manager/dashboard` - Team overview stats
- `GET /api/manager/rep/:userId` - Individual rep details

**Files Created:**
- `src/routes/manager.js` - Backend API
- `admin/src/pages/ManagerDashboard.jsx` - Full-page dashboard

**Files Modified:**
- `src/index.js` - Registered manager routes
- `admin/src/App.jsx` - Added /manager route (no AppLayout wrapper)

---

### 2026-01-18 (Call Recording Playback)

**COMPLETE**

Play call recordings directly in Lead Profile activity history.

**Problem:**
- Twilio recordings were being captured but URL wasn't stored
- Only transcript was saved, not recording URL

**Solution:**
- Store `recording_url` in communications metadata when recording completes
- Proxy endpoint to fetch recordings with Twilio Basic Auth
- Play/Pause button on call history items

**API Endpoints:**
- `GET /api/calls/recording/:communicationId` - Proxy to Twilio recording

**Files Modified:**
- `src/routes/voice.js` - Store recording_url in metadata
- `src/routes/calls.js` - Added recording proxy endpoint
- `admin/src/pages/LeadProfile.jsx` - Play button on call items

---

### 2026-01-17 (Messages Mobile Fix - CRITICAL)

**COMPLETE**

Fixed message input being completely hidden on mobile by BottomNav and floating buttons.

**Problem:**
- Message input field was blocked by 80px BottomNav
- VoiceAssistant floating button (z-40) overlapped input
- Users could not see/tap input, Send button, or template picker

**Solution:**
- Add `pb-28 md:pb-4` to input container (112px padding clears nav + buffer)
- Change `100vh` to `100dvh` for better mobile browser chrome handling
- Hide VoiceAssistant on /inbox (Messages already has voice features)

**Files Modified:**
- `admin/src/pages/Messages.jsx` - Input padding + viewport height
- `admin/src/App.jsx` - Conditional VoiceAssistant rendering

---

### 2026-01-17 (Desktop UI Fix)

**COMPLETE**

Fixed desktop sidebar navigation to match mobile quality.

**Problems Fixed:**
- `<a href>` tags caused full page refreshes (SPA anti-pattern)
- No active state indicator for current page
- 8 cluttered nav items vs mobile's clean 5 + More pattern
- Battleground link missing from desktop
- 96px empty space at bottom on desktop (pb-24)

**Changes:**
- Replace all `<a>` tags with `<NavLink>` for instant SPA navigation
- Add active states (blue bg + text) for current page
- Restructure sidebar: 5 primary items + More dropdown
- Add Battleground link to desktop nav
- Create DesktopMoreMenu.jsx component
- Fix bottom padding: `pb-24 md:pb-6` on 17 pages

**Desktop Nav Structure (After):**
```
├── 🏠 Dashboard (active state when on /)
├── 📞 Call List
├── 💬 Messages
├── 👥 Leads
├── ⚔️ Battleground
└── ⚙️ More ▼
    ├── 🚀 Activation
    ├── 📋 Scripts
    ├── 🎛️ Command Center
    ├── ✉️ Prompts
    ├── 📊 My Stats
    ├── 📈 Weekly Insights
    └── ⚙️ Settings
```

**Files Created:**
- `admin/src/components/DesktopMoreMenu.jsx`

**Files Modified:**
- `admin/src/App.jsx` - NavLink import, navLinkClass helper, sidebar restructure
- 17 pages - Responsive bottom padding (`pb-24 md:pb-6`)

---

### 2026-01-17 (Scripts Command Center - Priority #9)

**COMPLETE**

Brand guidelines enforcement, unified scripts library, AI guardrails, and compliance checking.

**Features:**
- Brand Guidelines editor (tone, keywords, banned words/phrases)
- 30 seed scripts (10 SMS, 10 Call, 8 Objection, 2 Email)
- Compliance checker with scoring (pass >= 70)
- Auto-fix for minor compliance issues
- AI guardrails (draftMessage injects brand voice rules)
- Category filters (SMS, Call, Email, Objection)
- Script copy-to-clipboard functionality
- Compliance tester modal

**Business Rules:**
- Contractors = FREE ("zero cost to you", "no cost")
- Workers = 9.9% platform fee (always mentioned)
- SMS opt-out ONLY on re-engagement (gone_cold, inactive_30d)
- Max 1 exclamation mark per message
- Banned words: guaranteed, promise, best, cheapest, urgent, free, etc.

**API Endpoints:**
- `GET /api/scripts/guidelines` - Get active brand guidelines
- `PUT /api/scripts/guidelines` - Update guidelines
- `GET /api/scripts/guidelines/history` - Guidelines change history
- `POST /api/scripts/compliance/check` - Check message compliance
- `POST /api/scripts/compliance/auto-fix` - Auto-fix message
- `POST /api/scripts/compliance/validate/:id` - Validate script
- `GET /api/scripts/compliance/stats` - Compliance statistics
- `GET /api/scripts/compliance/queue` - Review queue

**Files Created:**
- `src/services/compliance.js` - Core compliance service
- `admin/src/pages/ScriptsCommandCenter.jsx` - Main command center page
- `supabase/migrations/20260117043817_scripts_command_center.sql`
- `supabase/migrations/20260117050000_seed_scripts.sql`

**Files Modified:**
- `src/routes/scripts.js` - Added guidelines + compliance endpoints
- `src/services/ai.js` - Injected brand voice into draftMessage
- `admin/src/api/client.js` - Added scriptsApi compliance methods
- `admin/src/App.jsx` - Added /scripts/command-center route

**Migration:** `supabase/PENDING_MIGRATIONS.md` - ✅ Applied

---

### 2026-01-17 (Gamification Battleground - Priority #7)

**COMPLETE**

Full competitive sales team battleground with live leaderboards, challenges, and records.

**Features:**
- Live leaderboard (today/week/month/all-time periods)
- Hall of Fame (permanent records: most calls/day, biggest deal, longest streak, etc.)
- Daily challenges (individual + team missions with XP rewards)
- Team Pulse feed (real-time activity stream with conversions, overtakes, records)
- Streak Wars (flame tiers: bronze 3d, silver 7d, gold 14d, diamond 30d)
- Weekly badges (Closer, Dialer, Sniper, Consistent, Early Bird, Night Owl)
- User stats modal (tap leaderboard row to see full stats)

**Automated Triggers:**
- Call logged → Challenge progress + record check + pulse event (if conversion)
- Friday 3pm AEST → Weekly badge awards + Slack announcement
- Every hour → Leaderboard snapshot (for position tracking)

**API Endpoints:**
- `GET /api/battleground/leaderboard?period=today` - Live leaderboard
- `GET /api/battleground/hall-of-fame` - Permanent records
- `GET /api/battleground/challenges` - Today's individual + team challenges
- `GET /api/battleground/pulse` - Team activity feed
- `GET /api/battleground/badges/:userId` - User's weekly badges
- `POST /api/battleground/challenges/progress` - Update challenge progress

**Files Created:**
- `src/services/leaderboardService.js` - Rankings, records, pulse events
- `src/services/challengesService.js` - Daily challenges logic
- `src/services/badgesService.js` - Weekly badge awards
- `src/routes/battleground.js` - All API routes
- `admin/src/pages/Battleground.jsx` - Main page
- `admin/src/components/gamification/LiveLeaderboard.jsx`
- `admin/src/components/gamification/HallOfFame.jsx`
- `admin/src/components/gamification/DailyChallenges.jsx`
- `admin/src/components/gamification/TeamPulseFeed.jsx`
- `admin/src/components/gamification/StreakWars.jsx`
- `admin/src/components/gamification/UserStatsModal.jsx`
- `supabase/gamification-battleground-migration.sql`

**Files Modified:**
- `src/index.js` - Registered battleground routes
- `src/jobs/index.js` - Added weekly badges cron + leaderboard snapshot
- `src/routes/calls.js` - Added battleground triggers on call log
- `admin/src/api/client.js` - Added battlegroundApi
- `admin/src/App.jsx` - Added /battleground route
- `admin/src/components/BottomNav.jsx` - Replaced Prompts with Battle nav

**Migration:** `supabase/PENDING_MIGRATIONS.md` - ✅ Applied

---

### 2026-01-17 (Messages Hub 0.1% - Priority #8)

**COMPLETE**

Full messages hub upgrade with smart interactions and AI-powered message analysis.

**Features:**
- Renamed Inbox → Messages throughout app
- 6 Smart filters: Hot, Waiting on Me, Waiting on Them, Buying Signals, Needs Rescue, All
- Lead Card Preview at top of conversation thread
- Long-press context menu on messages (AI Explain, Copy, Extract Phone, Flag)
- SmartMessageContent with entity detection (phone, email, date auto-linking)
- AIExplainModal for AI-powered message analysis
- MiniLeadPopup on contact long-press (quick actions)
- Response time tracking (response_time_seconds column)
- Speed Demon badge integration for fastest responders
- AI Message Writer with tone selector (Professional/Friendly/Urgent)
- 3 AI suggestions on modal open with one-tap Send

**API Endpoints:**
- `POST /api/ai/explain-message` - AI analysis of message content

**Files Created:**
- `admin/src/pages/Messages.jsx` - Renamed from Inbox
- `admin/src/hooks/useLongPress.js` - Touch gesture hook
- `admin/src/components/inbox/LeadCardPreview.jsx`
- `admin/src/components/inbox/MessageContextMenu.jsx`
- `admin/src/components/inbox/AIExplainModal.jsx`
- `admin/src/components/inbox/SmartMessageContent.jsx`
- `admin/src/components/inbox/MiniLeadPopup.jsx`
- `supabase/messages-hub-migration.sql`

**Files Modified:**
- `src/routes/ai.js` - Added explain-message endpoint
- `src/routes/sms.js` - Response time calculation
- `src/services/badgesService.js` - Speed Demon badge
- `admin/src/api/client.js` - Added aiApi.explainMessage()
- `admin/src/App.jsx` - Messages route
- `admin/src/components/BottomNav.jsx` - "Messages" label
- `admin/src/components/inbox/InboxFilterTabs.jsx` - 6 smart filters
- `admin/src/components/AIMessageWriter.jsx` - Tone selector, 3 suggestions

**Migration:** `supabase/PENDING_MIGRATIONS.md` - ✅ Applied

---

### 2026-01-16 (AI Strategy Modal)

**COMPLETE**

Tap "Today's Mission" card to open AI-powered strategy modal with prioritized action plan.

**Features:**
- AI analyzes current state (SMS waiting, callbacks, hot leads, calls to target)
- Generates prioritized action plan with time estimates
- Each step has action button that navigates directly to task
- Strategic target recommendation at end ("big game" call)
- Fallback strategy when AI unavailable

**API Endpoints:**
- `GET /api/dashboard/strategy` - Get AI strategy with prioritized steps

**Files Created:**
- `admin/src/components/StrategyModal.jsx` - Modal UI component
- `docs/strategy-modal-plan.md` - Feature documentation

**Files Modified:**
- `src/routes/dashboard.js` - Added /strategy endpoint
- `admin/src/components/TodaysMission.jsx` - Made clickable with "Get AI Plan" hint
- `admin/src/components/TimeAwareSection.jsx` - Pass onMissionClick prop
- `admin/src/pages/Dashboard.jsx` - Modal state + navigation handlers
- `admin/src/api/client.js` - Added getStrategy() method

---

### 2026-01-16 (Contextual AI Wisdom System)

**COMPLETE**

AI-powered contextual coaching that sees your numbers and calls you out.

**Features:**
- 14 context triggers (post_win, streak_broken, overdue_callbacks, etc.)
- OpenAI generates situation-specific wisdom
- Tap to expand for deeper explanation
- Thumbs up/down rating system
- 28 curated fallbacks (2 per trigger) when AI unavailable
- 2-hour cache with context-change invalidation

**Context Triggers:**
- `post_win` - Just converted someone
- `streak_broken` - No calls in 3+ days
- `overdue_callbacks` - 2+ callbacks overdue
- `sms_waiting` - 2+ SMS replies waiting
- `zero_calls` - 0 calls after 12pm
- `friday_push` - Friday after 3pm
- `monday_start` - Monday before 11am
- `behind_target` - <50% target after 2pm
- `afternoon_slump` - 2pm-4pm energy dip
- `streak_strong` - 5+ day streak
- `crushing_it` - Beat target + win today
- `winning_streak` - 2+ wins this week
- `end_of_day` - After 5pm
- `general` - Default fallback

**API Endpoints:**
- `GET /api/dashboard/wisdom` - Get contextual wisdom
- `POST /api/dashboard/wisdom/rate` - Rate wisdom (up/down)

**Files Created:**
- `supabase/wisdom-migration.sql` - Tables + curated fallbacks
- `src/services/wisdom.js` - Context analysis + OpenAI generation
- `admin/src/components/WisdomDisplay.jsx` - UI component

**Files Modified:**
- `src/routes/dashboard.js` - Added wisdom endpoints
- `admin/src/components/TimeAwareSection.jsx` - Replaced time indicator with wisdom
- `admin/src/pages/Dashboard.jsx` - Added wisdom fetching + rating
- `admin/src/api/client.js` - Added wisdom API methods

---

### 2026-01-16 (Notification System)

**COMPLETE**

- Created `NotificationDropdown.jsx` - grouped notification dropdown
- Created `useClickOutside.js` hook for dropdown dismissal
- Updated `DashboardHeader.jsx` to show dropdown on bell click
- Updated `Dashboard.jsx` to pass notification data
- Fixed count mismatch (SMS replies now show all, not just >4hrs)

**Files Created:**
- `admin/src/components/NotificationDropdown.jsx`
- `admin/src/hooks/useClickOutside.js`

**Files Modified:**
- `admin/src/components/DashboardHeader.jsx`
- `admin/src/pages/Dashboard.jsx`
- `src/routes/dashboard.js` (added notifications object)

---

### 2026-01-16 (0.1% Dashboard Build)

**COMPLETE - All 12 steps finished**

**Step 2: Backend API Endpoint**
- Created `src/routes/dashboard.js` with comprehensive dashboard stats endpoint
- `GET /api/dashboard/stats` returns all dashboard data in one call

**Steps 3-9: Frontend Components**
- `DashboardHeader.jsx` - Greeting, streak badge, notifications
- `TodaysMission.jsx` - Calls to target, callbacks, hot leads
- `LiveStats.jsx` - Progress rings, calls/convos/wins
- `UrgentActions.jsx` - Red alerts for overdue items
- `RecentWins.jsx` - Last 3 conversions (motivation!)
- `MarketplaceHealth.jsx` - Workers vs Contractors (Phase 2 stub)
- `QuickActions.jsx` - Big START CALLING button

**Step 10: TimeAwareSection**
- Morning mode (before 10am): Mission-focused
- Work mode (10am-5pm): Live progress + urgent actions
- Evening mode (after 5pm): Day recap + tomorrow preview

**Steps 11-12: Integration**
- Refactored `Dashboard.jsx` to use new components
- Added `dashboardApi` to API client
- Realtime updates wired (sms_inbound, call_logged, lead_converted)

**Files Created:**
- `src/routes/dashboard.js` - Backend API
- `admin/src/components/DashboardHeader.jsx`
- `admin/src/components/TodaysMission.jsx`
- `admin/src/components/LiveStats.jsx`
- `admin/src/components/UrgentActions.jsx`
- `admin/src/components/RecentWins.jsx`
- `admin/src/components/MarketplaceHealth.jsx`
- `admin/src/components/QuickActions.jsx`
- `admin/src/components/TimeAwareSection.jsx`

**Files Modified:**
- `src/index.js` - Added dashboard route
- `admin/src/pages/Dashboard.jsx` - Complete refactor
- `admin/src/api/client.js` - Added dashboardApi

---

### 2026-01-16 (Security & Code Audit Fixes)

**MEDIUM PRIORITY FIXES (Batch 2):**
- Structured logger utility (`src/utils/logger.js`) - replaces raw console.log
- Request timing middleware (`src/middleware/requestLogger.js`) - logs response times
- React ErrorBoundary component - catches React errors with graceful fallback UI
- Input sanitization for text fields - XSS prevention, email validation
- Cleaned up TODO comments throughout codebase

**MEDIUM PRIORITY FIXES (Batch 1):**
- Added validation utilities (`src/utils/validation.js`)
- UUID validation on lead ID parameters (leads.js, sms.js)
- SMS message length validation (max 1600 chars)
- Phone number format validation for AU numbers
- Request body size limit (1MB) to prevent DoS
- Standardized error responses using `errorResponse()` helper

**CRITICAL FIXES:**
- Added auth middleware - all API routes now require Supabase JWT
- Fixed Deepgram API key exposure - no longer returned to frontend
- Fixed SQL injection risk in webhooks.js status callback
- Fixed duplicate winning_patterns table definition
- Fixed dynamic Tailwind classes in PredictiveScoreBadge
- Fixed undefined loadBrief function in IntelBriefModal
- Fixed hardcoded email in ContractorFoundModal (uses auth context)
- Added description column to sms_templates schema

**HIGH PRIORITY FIXES:**
- Added error handling to database operations (ai.js, calls.js, webhooks.js)
- Fixed race condition in callback creation (calls.js)
- Added supabaseAdmin client for server-side auth validation
- Documented all environment variables in .env.example
- Removed hardcoded streak value in CallList.jsx

**Files Modified:**
- `src/middleware/auth.js` (new) - JWT authentication middleware
- `src/middleware/requestLogger.js` (new) - Request timing middleware
- `src/utils/logger.js` (new) - Structured logging utility
- `src/utils/validation.js` - Added sanitizeEmail, sanitizeTextFields
- `src/config/database.js` - Added supabaseAdmin client
- `src/routes/ai.js` - Error handling, Deepgram fix
- `src/routes/calls.js` - Error handling, race condition fix
- `src/routes/webhooks.js` - Error handling, SQL injection fix
- `src/routes/leads.js` - Input sanitization for text fields
- `src/routes/voice.js` - Cleaned up TODO comment
- `src/services/deepgram.js` - Removed API key exposure
- `src/index.js` - Applied auth middleware, request logger
- `admin/src/api/client.js` - Added auth token to requests
- `admin/src/components/ErrorBoundary.jsx` (new) - React error boundary
- `admin/src/components/PredictiveScoreBadge.jsx` - Static Tailwind classes
- `admin/src/components/IntelBriefModal.jsx` - Fixed function name
- `admin/src/components/ContractorFoundModal.jsx` - Uses auth context
- `admin/src/pages/CallList.jsx` - Conditional streak display, cleaned TODO
- `admin/src/App.jsx` - Added ErrorBoundary wrapper
- `.env.example` - Full documentation
- `supabase/critical-fixes-migration.sql` (new)

### 2026-01-15 (Session 2 - Real-Time & Auto-Tune)
- **REAL-TIME UPDATES**
  - RealtimeContext.jsx: Supabase realtime subscriptions
  - Listens to communications INSERT (new SMS) and leads UPDATE (conversions)
  - Dashboard/Inbox auto-refresh when events occur
  - Visual indicators: green wifi icon, pulsing badge, "NEW MESSAGE" banner
  - Audio notification on inbound SMS and conversions
  - Event system for components to subscribe to specific events

- **WEEKLY "WHAT'S WORKING" REPORT**
  - weeklyReport.js: analyzes last 30 days of conversion_patterns
  - Identifies: best trades, best contact times, winning channels, touchpoints
  - Sends formatted report to Slack every Monday 7am AEST
  - Stores in ai_insights table for app display

- **AUTO-TUNE CALL LIST**
  - winning_patterns table stores AI-detected patterns
  - Call list fetches active patterns and boosts matching leads
  - Pattern-boosted leads get priority 1.5 (after inbound replies, before hot leads)
  - Response includes activePatterns array for UI display
  - Leads show patternBoost with description and conversion rate

### 2026-01-15 (Late Night Session)
- **AUTO-TRANSCRIPTION FOR ALL CALLS**
  - CallContext now auto-starts transcription when any call connects
  - Uses Deepgram (primary) or Web Speech API (fallback)
  - Visual "Recording & Transcribing" indicator on call screen
  - Transcripts stored in communications metadata

- **AUTO-SUMMARY GENERATION**
  - AI summary generated automatically when call ends
  - CallOutcomeSheet pre-populated with AI summary
  - Notes auto-filled, outcome auto-suggested
  - Score adjustment applied from AI recommendation
  - User just confirms and saves

- **LEARNING SYSTEM WIRED INTO AI**
  - getEffectiveResponses() now called in objection handler
  - Proven responses with effectiveness scores injected into AI prompts
  - getSimilarWins() already wired into Intel Brief
  - AI now says "PROVEN RESPONSES (these have worked before)"

- **LEARNING SYSTEM PHASE 1**
  - conversion_patterns table: captures full journey of converted leads
  - objection_responses table: tracks response effectiveness
  - suggestion_feedback table: thumbs up/down tracking
  - Auto-capture on lead conversion
  - Effectiveness score formula: (helpful/total * 0.6) + (conversions/10 * 0.4)

- **IDEAS/STRATEGY CAPTURE**
  - Voice Assistant now captures ideas, strategies, experiments, reminders
  - Stored in ideas table with categories
  - Example: "Idea: offer referral bonus" or "Strategy: focus on formwork"

- **ACTIVITY PAGE**
  - New /activity page shows all calls made today
  - Manager can see who was called, outcomes, duration, notes
  - Summary cards: total calls, connected, SMS sent
  - Outcome breakdown badges

- **DASHBOARD FIXES**
  - Stats now real (from communications table, not fake calculations)
  - StatCards clickable - navigate to relevant pages
  - AI Insights auto-refresh if >1 hour old
  - Readable styling (white background, dark text)

- **BUG FIXES**
  - Bell notification icon now navigates to /inbox
  - Streak calculated from real data (not hardcoded 12)

### 2026-01-15 (Evening Session)
- **TWILIO IN-APP CALLING**
  - Calls now happen inside the app via Twilio Voice SDK (not native phone dialer)
  - Created global CallProvider context for call state management
  - All call buttons across app use in-app calling
  - Sydney edge for Australian dial tones

- **NOTES & TRANSCRIPTS SECTION**
  - Added Notes & Transcripts section to Lead Profile page
  - Shows call notes (green) and AI Copilot transcripts (violet)
  - Collapsible section, expanded by default

- **VOICE NOTE TRANSCRIPTION FIX**
  - Voice notes now actually transcribed via OpenAI Whisper
  - Previously just saved "Voice note recorded" placeholder
  - Transcription shows with spinner, then displays actual text
  - Auto-fills notes field with transcript

- **AI COPILOT TRANSCRIPT SAVING**
  - Live Copilot transcripts now saved to lead_notes table
  - Transcripts appear in Notes section after call ends
  - Includes call duration in transcript header

- **BUG FIXES**
  - Fixed white screen after call ends (stale callback bug in CallContext)
  - Fixed double-calling of onCallEnd with callEndedRef flag
  - Fixed frontend Supabase auth crash (mock client when not configured)
  - Fixed build process to use pre-built public folder with credentials

### 2026-01-15 (Morning)
- Session 3: Lead CRUD API
- Session 2: Twilio inbound webhook
- Session 1: Project scaffolding

---

## AI Sales System

### Overview
A comprehensive AI-powered sales assistant system that provides:
- **Pre-Call Intel Briefs** - 30-second AI-generated preparation for calls
- **Post-Call Auto-Summary** - AI analysis of call notes/transcripts
- **AI Message Writer** - Context-aware SMS drafting
- **Live Call Copilot** - Real-time transcription and objection handling
- **Pattern Learning Engine** - Weekly insights and trends
- **Predictive Lead Scoring** - AI-calculated conversion probability
- **Voice Assistant** - Natural language commands
- **Voice Notes** - Speech-to-text note taking

### Required Environment Variables
```
OPENAI_API_KEY=sk-...           # Required for AI features
DEEPGRAM_API_KEY=...            # Optional: for live transcription (fallback to Web Speech API)
```

### AI API Endpoints

#### Pre-Call Intelligence
```
GET /api/ai/intel-brief/:leadId
```
Returns a 30-second brief with:
- Executive summary
- Savings/value pitch
- Opening line
- Talking points
- Predicted objections with counters
- Similar wins analysis
- Recommended approach

#### Post-Call Summary
```
POST /api/ai/post-call-summary
Body: { leadId, transcript/notes, callDuration }
```
Returns:
- Call summary
- Key points
- Sentiment analysis
- Score adjustment recommendation
- Next step suggestion
- Follow-up date
- Coaching tip

#### AI Message Drafting
```
POST /api/ai/draft-message
Body: { leadId, prompt }
```
Generates context-aware SMS messages based on:
- Lead history
- Recent communications
- User's prompt/intent

#### Audio Transcription
```
POST /api/ai/transcribe
Body: FormData with audio file
```
Uses OpenAI Whisper for accurate speech-to-text.

#### Voice Commands
```
POST /api/ai/voice-command
Body: { transcript, userEmail }
```
Supported intents:
- `update_lead` / `mark_status` - Change lead status
- `schedule_callback` - Schedule follow-up
- `add_note` - Add note to lead
- `get_recommendation` - Get next lead to call

#### Real-Time Objection Handling
```
POST /api/ai/objection-response
Body: { objection, leadId }
```
Returns instant response suggestions for detected objections.

#### Conversion Probability
```
GET /api/ai/conversion-probability/:leadId
```
AI-calculated probability with:
- Contributing factors
- Reasoning
- Recommended action
- Optimal timing

#### Weekly Insights
```
POST /api/ai/weekly-insights
```
Generates pattern analysis:
- Top insight
- Best performing times/approaches
- Recommendations
- Concerns to address

#### Note Cleanup
```
POST /api/ai/cleanup-notes
Body: { notes, leadId }
```
Structures rough notes into:
- Clean formatted notes
- Key points
- Action items
- Sentiment
- Follow-up suggestions

#### Live Transcription Credentials
```
GET /api/ai/deepgram-credentials
```
Returns WebSocket URL and credentials for live transcription.

### AI Database Schema
Run `supabase/ai-schema.sql` to create:
- `call_recordings` - Stored transcripts and AI analysis
- `ai_insights` - Weekly pattern insights
- `conversion_factors` - Statistical conversion factors
- `ai_message_drafts` - Draft history
- `voice_commands` - Command log
- `copilot_sessions` - Live session data

### AI Models Used
| Task | Model | Notes |
|------|-------|-------|
| Complex reasoning | gpt-4o | Intel briefs, post-call analysis, patterns |
| Simple tasks | gpt-4o-mini | Message drafting, note cleanup, commands |
| Transcription | whisper-1 | Audio-to-text |
| Live streaming | Deepgram Nova-2 | Real-time transcription (optional) |

### Frontend AI Components
| Component | Purpose |
|-----------|---------|
| `IntelBriefModal` | Pre-call preparation modal |
| `PostCallSummarySheet` | Post-call AI analysis |
| `AIMessageWriter` | SMS drafting assistant |
| `LiveCopilot` | Real-time call assistance |
| `AIInsightsWidget` | Dashboard pattern insights |
| `PredictiveScoreBadge` | AI conversion probability |
| `VoiceAssistant` | Floating voice command button |
| `VoiceNoteButton` | Inline voice-to-text |

---

## Quick Start

### Test API
```bash
# Health check
curl https://rateright-growth-production.up.railway.app/health

# List leads
curl https://rateright-growth-production.up.railway.app/api/leads

# Get call list
curl https://rateright-growth-production.up.railway.app/api/call-list

# Get AI Intel Brief
curl https://rateright-growth-production.up.railway.app/api/ai/intel-brief/<lead-id>
```

### Run Admin UI
```bash
cd admin
npm install
npm run dev
# Open http://localhost:5173
```

### Deploy Backend
```bash
railway up
```
