# CleanOS Architecture Plan

## What Is CleanOS?

A **booking management SaaS for cleaning companies** with AI built in. Cleaning companies sign up, connect their phone number, and get:

- AI receptionist (voice + text) that quotes and books
- Online booking widget for their website
- Customer management with full conversation history
- Automated follow-ups (quotes, reminders, reviews)
- Scheduling and dispatch
- Invoicing and payments

Think: **Launch27 + Jobber + Leah**, all in one platform.

---

## The Vision (Phases)

### Phase 1: NMC's Internal System (Now → Q2 2026)
Build for No More Chores. Solve your own problems first.
- Leah AI agent (SMS + voice) ✅ done
- Live pricing from Launch27 ✅ done
- Full conversation logging in GHL ✅ done
- Quote follow-up engine (code-based, not GHL workflows)
- Chatwoot for conversations (replaces GHL for messaging)
- PostgreSQL as the data foundation

### Phase 2: Standalone Platform (Q2 → Q4 2026)
Extract what works into a product.
- Multi-tenant architecture (each cleaning company = a tenant)
- Self-service onboarding (connect Twilio number, upload services/pricing)
- Booking widget (embed on any website)
- Replace Launch27 with built-in booking engine
- Admin dashboard for business owners

### Phase 3: SaaS Launch (2027)
Ship it.
- Public launch
- Pricing tiers
- Marketing site
- Stripe billing
- Onboarding flow
- Support docs

---

## Tech Stack

### Core Application
| Component | Technology | Why |
|-----------|-----------|-----|
| **Backend** | Node.js (Express or Fastify) | Same language as Twilio functions, huge ecosystem, fast |
| **Frontend** | Next.js (React) | Modern, SSR for SEO, great DX, massive community |
| **Database** | PostgreSQL + pgvector | The foundation. Structured data + AI vector search. One database for everything |
| **ORM** | Prisma | Type-safe, great migrations, multi-tenant friendly |
| **Auth** | NextAuth.js or Logto (open source) | Multi-tenant auth with org/workspace support |
| **Queue/Jobs** | BullMQ (Redis) | Scheduled follow-ups, email sends, async processing |

### Communications Layer
| Component | Technology | Why |
|-----------|-----------|-----|
| **SMS/Voice** | Twilio | Already using it, battle-tested, per-tenant phone numbers |
| **Email sending** | Amazon SES or Resend | Cheap, reliable, API-first. ~$0.10 per 1000 emails |
| **Conversations UI** | Chatwoot (embedded or forked) | Open source, native Twilio integration, agent bot API |
| **Voice AI** | Vapi | Already configured, handles voice agent complexity |

### AI Layer
| Component | Technology | Why |
|-----------|-----------|-----|
| **Text AI** | Claude (Anthropic API) | Best conversational quality, tool use for pricing |
| **Voice AI** | GPT-4o-mini (via Vapi) | Fastest latency for voice |
| **Embeddings** | OpenAI text-embedding-3-small | For pgvector semantic search on conversations |
| **Agent framework** | Custom (not LangChain) | Keep it simple, you own the logic |

### Infrastructure (Phase 1)
| Component | Where | Cost |
|-----------|-------|------|
| **App server** | MacBook Air (dev) → VPS (prod) | $0 → $10-20/mo |
| **Database** | Local PostgreSQL → Supabase or self-hosted | $0 → $0-25/mo |
| **Redis** | Local → managed | $0 → $0-10/mo |
| **Chatwoot** | Docker on same server | $0 |
| **Domain/SSL** | Cloudflare | Free |

---

## Database Schema (Simplified)

```
tenants
  id, name, subdomain, settings_json, created_at

users (business owners, staff)
  id, tenant_id, email, name, role, auth_provider_id

contacts (customers)
  id, tenant_id, first_name, last_name, email, phone, address,
  city, postal_code, tags[], custom_fields_json, created_at

services
  id, tenant_id, name, category, base_price, pricing_type,
  duration_minutes, description, active

service_pricing_params
  id, service_id, name, price_per_unit, min, max

service_extras
  id, tenant_id, name, price, description

frequencies
  id, tenant_id, name, discount_percent, interval_days

quotes
  id, tenant_id, contact_id, service_id, frequency_id,
  details_json (bedrooms, bathrooms, sqft, building_type, extras),
  subtotal, tax, total, status (draft/sent/accepted/declined/expired),
  sent_at, responded_at, expires_at, created_at

bookings
  id, tenant_id, contact_id, quote_id, service_id,
  scheduled_date, scheduled_time, duration_minutes,
  assigned_team[], status (scheduled/in_progress/completed/cancelled),
  total, paid, notes

conversations
  id, tenant_id, contact_id, channel (sms/email/webchat/voice),
  status (active/resolved/pending), assigned_to, ai_handled,
  created_at, updated_at

messages
  id, conversation_id, direction (inbound/outbound), sender_type (customer/ai/agent),
  content, metadata_json, created_at

message_embeddings (pgvector)
  id, message_id, embedding vector(1536)

follow_ups
  id, tenant_id, contact_id, quote_id, type (sms/email),
  scheduled_at, sent_at, status (pending/sent/cancelled),
  template_or_ai (template/ai), content

contractors
  id, tenant_id, name, phone, email, active, rating,
  service_areas[], skills[]

schedules
  id, tenant_id, contractor_id, booking_id, date, time_start, time_end
```

---

## How It Replaces Current Tools

| Current Tool | What It Does | CleanOS Replacement |
|-------------|-------------|-------------------|
| **Launch27** | Booking engine, pricing, services | Built-in booking engine + pricing calculator |
| **GHL** | CRM, conversations, email marketing, pipeline | Contacts + Conversations + Follow-up engine |
| **Aircall** | Phone system | Twilio (already done) |
| **Vapi** | Voice AI agent | Keep as-is (voice AI layer) |
| **Twilio** | SMS/Voice infrastructure | Keep as-is (comms backbone) |
| **Slack** | Team notifications | Keep or add built-in notifications |

---

## Chatwoot's Role

Chatwoot is NOT the whole platform. It's **one module**: the conversations layer.

What Chatwoot gives you out of the box:
- Unified inbox (SMS, email, webchat, FB, IG, WhatsApp)
- Twilio native integration (SMS + voice)
- Agent bot API (hook Leah/Claude into any inbox)
- Contact management (basic)
- Team assignment and routing
- Canned responses
- CSAT surveys
- Self-hosted, PostgreSQL backend

What you build on top:
- Booking engine
- Pricing calculator
- Quote management
- Follow-up automation
- Scheduling/dispatch
- Invoicing
- Multi-tenant wrapper
- AI agent configuration per tenant

### Integration approach:
- Chatwoot runs as a Docker service alongside your app
- Share the same PostgreSQL instance (separate schemas or databases)
- Your app calls Chatwoot API for conversation operations
- Chatwoot webhooks notify your app of new messages (triggers AI)
- Customers interact through Chatwoot channels, AI responds via Chatwoot API
- Business owners see conversations in Chatwoot UI (or your custom UI later)

---

## The Follow-Up Engine (Code, Not Workflows)

Instead of GHL's drag-and-drop workflows, follow-ups are scheduled jobs:

```
1. Quote created → schedule follow-ups:
   - +2 hours: AI-personalized SMS check-in
   - +1 day: Email with quote summary + booking link
   - +3 days: SMS with gentle nudge
   - +7 days: Final email with limited-time offer

2. Each job runs via BullMQ:
   - Pulls conversation history
   - Claude generates personalized message (not a template)
   - Sends via Chatwoot API (SMS or email)
   - Logs in conversation history

3. If customer responds at ANY point:
   - Cancel remaining follow-ups
   - Leah picks up the conversation naturally
   - Update quote status
```

This is infinitely more flexible than GHL workflows. Claude can adjust tone, reference specific details from the conversation, and even decide NOT to send if it doesn't make sense.

---

## Multi-Tenant Architecture

Each cleaning company (tenant) gets:
- Their own subdomain: `acme.cleanos.com`
- Their own Twilio phone number(s)
- Their own AI agent (with their business knowledge, pricing, voice)
- Their own booking widget to embed on their website
- Isolated data (PostgreSQL row-level security or schema-per-tenant)

### Tenant onboarding flow:
1. Sign up → create account
2. Connect Twilio number (or we provision one)
3. Add services and pricing
4. Configure AI agent (upload business docs, set personality)
5. Embed booking widget on their website
6. Done. AI answers calls/texts, books appointments, follows up.

---

## Phase 1 Implementation Order

This is what we build NOW for NMC:

### Week 1-2: Foundation
- [ ] Set up PostgreSQL locally with pgvector
- [ ] Create initial schema (contacts, services, quotes, conversations, messages)
- [ ] Import NMC services/pricing from Launch27 into local DB
- [ ] Install Chatwoot via Docker, connect Twilio number

### Week 3-4: Wire Leah to Chatwoot
- [ ] Create Leah as an Agent Bot in Chatwoot
- [ ] Inbound SMS flows through Chatwoot → webhook to our AI handler → reply via Chatwoot API
- [ ] Full conversation history visible in Chatwoot UI
- [ ] Remove GHL from the SMS flow

### Week 5-6: Quote + Follow-Up Engine
- [ ] Leah creates quotes in the database when customer is interested
- [ ] Build follow-up job scheduler (BullMQ + Redis)
- [ ] Claude-powered personalized follow-ups
- [ ] Quote status tracking (sent → viewed → accepted/declined)

### Week 7-8: Booking + Admin
- [ ] Basic admin dashboard (Next.js)
- [ ] View contacts, conversations, quotes, bookings
- [ ] Booking creation from accepted quotes
- [ ] Basic scheduling view

### Ongoing: Migrate off GHL
- [ ] Move email sending to SES/Resend
- [ ] Move contact data from GHL to PostgreSQL
- [ ] Move pipeline/opportunities to built-in quote tracking
- [ ] Eventually: cancel GHL subscription

---

## Current Monthly Costs

| Service | Current Cost | CleanOS Cost |
|---------|-------------|-------------|
| GHL | ~$97/mo | $0 (replaced) |
| Aircall | cancelled | $0 |
| Launch27 | ~$59/mo | $0 (replaced eventually) |
| Twilio | ~$20-50/mo (usage) | Same |
| Vapi | ~$10-30/mo (usage) | Same |
| Anthropic API | ~$5-10/mo | Same |
| VPS (when needed) | $0 | $10-20/mo |
| **Total** | ~$240-340/mo | ~$45-110/mo |

Savings: **$150-250/month** once fully migrated.

---

## What You'd Sell (Phase 3)

**CleanOS** - The AI-powered booking platform for cleaning companies.

| Tier | Price | Features |
|------|-------|----------|
| **Starter** | $49/mo | 1 phone number, AI text agent, booking widget, 500 SMS, 1000 emails |
| **Growth** | $99/mo | Everything + voice AI agent, 2000 SMS, unlimited emails, follow-up engine |
| **Pro** | $199/mo | Everything + multi-location, team scheduling, custom AI training, priority support |

Market: ~100,000+ cleaning companies in North America alone. If you capture 0.1%, that's 100 customers × $99 = ~$10K/month recurring.

---

## Summary

The key insight: **you're not replacing one SaaS with another**. You're building the platform that other cleaning companies will pay for. Every problem you solve for NMC becomes a feature in CleanOS.

Start with Phase 1. Build for yourself. Ship what works. Then sell it.
