# Unified Architecture V1 — RateRight Operations Platform
*Created: 2026-03-03 | Owner: Rivet | Status: DRAFT — iterating until approved*

## Vision

One system. Three layers. Eight agents working 24/7 with persistent memory, automated marketing execution, and a visual dashboard Michael can check from his phone.

This IS OpsMan — the product we're selling to contractors. We build it for ourselves first.

---

## Layer 1: Mission Control (Dashboard)

### What It Is
Next.js web dashboard hosted at `rivet.rateright.com.au/ops` (behind auth). Michael's single pane of glass for the entire operation.

### Screens

| Screen | Purpose | Data Source | Priority |
|--------|---------|-------------|----------|
| **Task Board** | Kanban — see what every agent is working on, assign tasks | SQLite `tasks` table + agent status.json | P0 |
| **Metrics** | Live numbers — workers, contractors, hires, emails sent, ad performance | SQLite `metrics` table + Stripe API + Supabase | P0 |
| **Team** | Fleet status — which agents are active, idle, stalled + roles | fleet-cli.js data + status.json files | P1 |
| **Memory Browser** | Browse agent memories by day, search across all agents | Memory folders + MEM0 API | P1 |
| **Calendar** | Cron jobs, scheduled tasks, upcoming deadlines | Clawdbot cron API per gateway | P2 |
| **Docs** | Every document agents have created, searchable | Workspace files, categorised | P2 |
| **Campaign Tracker** | Email open rates, ad performance, outreach pipeline | Instantly API + Facebook Ads API + SQLite | P1 |
| **Approvals** | Pending decisions with tap yes/no | SQLite `approvals` table + Telegram webhook | P0 |

### Tech Stack
- **Framework:** Next.js (already deployed at rivet.rateright.com.au)
- **Auth:** Existing Supabase auth (already working)
- **Data:** SQLite for ops data + Supabase for user data + API calls to agent gateways
- **Hosting:** Same VPS, same systemd service (rateright-app, port 3000)

### Build Approach
- Start from open-source openclaw-mission-control repo as reference (MIT licensed)
- Builder implements as new routes under existing app: `/ops`, `/ops/tasks`, `/ops/metrics`, etc.
- Mobile-first design — Michael checks from phone on break

---

## Layer 2: Memory Architecture

### Current State
- ✅ Method 1 (Structured Folders): `memory/YYYY-MM-DD.md`, `MEMORY.md`, `SOUL.md` per agent
- ❌ Method 2 (Memory Search): Not enabled — need to configure OpenAI embedding key
- ❌ Method 3 (MEM0): Not installed
- ❌ Method 4 (SQLite): Not used for structured data

### Target State

| Method | What | Config | Timeline | Owner |
|--------|------|--------|----------|-------|
| **Folders** (keep) | Daily notes, long-term memory, soul files | Already working | ✅ Done | All agents |
| **Memory Search** | Native OpenClaw semantic search across memories | Enable per gateway + set OpenAI embedding key | Week 1 | Sentinel |
| **MEM0** | Auto-extract important info from every conversation | Install `@mem0/openclaw-mem0` plugin per gateway | Week 2 | Builder |
| **SQLite** | Structured ops data — leads, workers, metrics, campaigns | Create shared DB at `/home/ccuser/shared/ops.db` | Week 1 | Builder |

### SQLite Schema (V1)

```sql
-- Leads & Contacts
CREATE TABLE leads (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  company TEXT,
  email TEXT,
  phone TEXT,
  city TEXT,
  type TEXT CHECK(type IN ('contractor', 'worker', 'hostel', 'partner')),
  source TEXT, -- 'linkedin', 'cold_email', 'hostel', 'referral', 'website'
  status TEXT CHECK(status IN ('new', 'contacted', 'qualified', 'converted', 'lost')),
  notes TEXT,
  assigned_agent TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Campaign Tracking
CREATE TABLE campaigns (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  type TEXT CHECK(type IN ('email', 'facebook_ad', 'linkedin', 'hostel_flyer', 'phone_call')),
  city TEXT,
  status TEXT CHECK(status IN ('draft', 'active', 'paused', 'completed')),
  sent INTEGER DEFAULT 0,
  opens INTEGER DEFAULT 0,
  clicks INTEGER DEFAULT 0,
  replies INTEGER DEFAULT 0,
  conversions INTEGER DEFAULT 0,
  spend REAL DEFAULT 0,
  owner TEXT, -- agent name
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Worker Supply Tracking (per city)
CREATE TABLE worker_supply (
  id INTEGER PRIMARY KEY,
  city TEXT NOT NULL,
  worker_count INTEGER DEFAULT 0,
  threshold INTEGER DEFAULT 15,
  outreach_activated BOOLEAN DEFAULT FALSE,
  last_checked DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Agent Tasks (feeds Mission Control task board)
CREATE TABLE tasks (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  description TEXT,
  assigned_to TEXT NOT NULL, -- agent name
  status TEXT CHECK(status IN ('backlog', 'in_progress', 'review', 'done')) DEFAULT 'backlog',
  priority TEXT CHECK(priority IN ('p0', 'p1', 'p2', 'p3')) DEFAULT 'p2',
  due_date DATETIME,
  created_by TEXT DEFAULT 'rivet',
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  completed_at DATETIME
);

-- Approvals (feeds Mission Control approvals screen)
CREATE TABLE approvals (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  description TEXT,
  requested_by TEXT NOT NULL, -- agent name
  options TEXT, -- JSON: ["approve", "reject"] or ["option_a", "option_b"]
  recommendation TEXT,
  decision TEXT,
  decided_by TEXT, -- 'michael' or 'rivet'
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME
);

-- Metrics (daily snapshots)
CREATE TABLE daily_metrics (
  id INTEGER PRIMARY KEY,
  date DATE NOT NULL,
  workers_total INTEGER DEFAULT 0,
  workers_new INTEGER DEFAULT 0,
  contractors_total INTEGER DEFAULT 0,
  contractors_new INTEGER DEFAULT 0,
  hires_total INTEGER DEFAULT 0,
  hires_new INTEGER DEFAULT 0,
  revenue REAL DEFAULT 0,
  emails_sent INTEGER DEFAULT 0,
  email_opens INTEGER DEFAULT 0,
  email_replies INTEGER DEFAULT 0,
  ad_spend REAL DEFAULT 0,
  ad_impressions INTEGER DEFAULT 0,
  ad_clicks INTEGER DEFAULT 0,
  website_visits INTEGER DEFAULT 0,
  signups INTEGER DEFAULT 0
);
```

### Memory Flow

```
Agent conversation happens
        │
        ├──→ Method 1: Agent writes to memory/YYYY-MM-DD.md (manual, transparent)
        ├──→ Method 2: Memory Search indexes for semantic recall (automatic)
        ├──→ Method 3: MEM0 extracts key facts, stores as vectors (automatic)
        └──→ Method 4: Structured data goes to SQLite (agent writes via SQL)
                │
        On next session:
        ├──→ Agent reads memory files (Method 1)
        ├──→ Agent searches memories semantically (Method 2)
        ├──→ MEM0 injects relevant context (Method 3)
        └──→ Agent queries SQLite for specific data (Method 4)
```

---

## Layer 3: GTM Execution Stack

### Tools & Costs

| Tool | Purpose | Cost | Agent Owner | Priority |
|------|---------|------|-------------|----------|
| **Instantly** | Cold email at scale (warm-up, sequences, tracking) | $30/mo | Susan | P0 |
| **Apollo** | Lead enrichment (email, phone, company data) | Free tier (10K credits/mo) | Susan | P0 |
| **Facebook Ads API** | Bulk ad creation, publish, performance tracking | Free (ad spend separate) | Herald | P1 |
| **Perplexity API** | Pain point research, competitor scraping | Already have key | Radar | ✅ Done |
| **Phantom Buster** | LinkedIn profile scraping, engagement extraction | $69/mo | Susan | P2 |
| **Million Verifier** | Email verification before sending | $37/500K emails | Susan | P1 |
| **Hey Gen** | UGC video ad generation from scripts | $29/mo | Herald | P3 |

**Total monthly cost: ~$165/mo** (within $1K budget, leaves $835 for ad spend)

### Automation Pipelines

**Pipeline 1: Worker Acquisition (Priority)**
```
Radar scrapes Reddit/Facebook for construction worker communities
    → Herald creates targeted social content
    → Herald generates bulk ad variations (React components)
    → Herald publishes to Facebook via API
    → Dashboard tracks performance
    → Herald kills losers, promotes winners
    → Workers land on rivet.rateright.com.au/work
    → Signup tracked in SQLite + Supabase
```

**Pipeline 2: Contractor Outreach**
```
Susan identifies contractors (Growth Engine + Apollo enrichment)
    → Million Verifier validates emails
    → Susan sends cold email sequences via Instantly
    → Replies auto-tracked in SQLite
    → Susan preps call scripts for Michael
    → Michael makes calls on break
    → Outcomes logged in SQLite
    → Dashboard shows pipeline metrics
```

**Pipeline 3: Content & Social**
```
Radar identifies trending construction topics
    → Herald writes content (LinkedIn, Facebook, Instagram)
    → Herald posts to platforms (API or manual approval)
    → Engagement tracked in SQLite
    → LinkedIn engagers scraped → enriched → emailed
    → Success stories captured and recycled
```

**Pipeline 4: Competitor Intelligence**
```
Radar monitors Yakka Labour, hipages, Airtasker
    → Price changes, feature launches, job volume
    → Findings stored in SQLite competitor table
    → Weekly competitor brief to Michael
    → Strategic adjustments pushed to fleet
```

---

## Agent Responsibilities (Updated)

| Agent | Layer 1 (Dashboard) | Layer 2 (Memory) | Layer 3 (GTM) |
|-------|--------------------|--------------------|---------------|
| **Builder** | Builds all dashboard screens | Creates SQLite DB, installs MEM0 | Builds ad generator, API integrations |
| **Susan** | Reads task board for assignments | Uses SQLite for lead data | Runs Instantly campaigns, Apollo enrichment |
| **Harper** | Financial metrics dashboard | Queries SQLite for cost analysis | Tracks ROI per channel |
| **Sentinel** | Infrastructure monitoring panel | Configures memory search fleet-wide | Monitors all API integrations |
| **Radar** | Feeds competitor data to dashboard | Stores intel in SQLite | Scrapes Reddit/LinkedIn/competitors |
| **Herald** | Content calendar view | Uses MEM0 for content memory | Runs ad campaigns, social posting |
| **Cog** | Support queue dashboard | Manages memory maintenance | Customer support automation |
| **Rivet** | Reviews all screens, assigns tasks | Synthesises memory across fleet | Coordinates all pipelines |
| **Michael** | Checks dashboard on phone, approves | Browses memory when needed | Makes phone calls, strategic decisions |

---

## Implementation Roadmap

### Phase 1: Foundation (This Week, Mar 3-9)
- [ ] Enable memory search across all 8 agent gateways (Sentinel)
- [ ] Create SQLite ops database with V1 schema (Builder)
- [ ] Sign up Instantly free trial, connect API (Susan)
- [ ] Sign up Apollo free tier, get API key (Susan)
- [ ] Build `/ops` dashboard route with task board + metrics (Builder)
- [ ] Migrate lead data from CSVs/Growth Engine to SQLite (Cog)

### Phase 2: Automation (Week 2, Mar 10-16)
- [ ] Install MEM0 plugin on all gateways (Builder + Sentinel)
- [ ] Build bulk ad generator (React components) (Builder)
- [ ] Connect Facebook Ads API (Builder)
- [ ] Build campaign tracker dashboard screen (Builder)
- [ ] First automated email sequence live via Instantly (Susan)
- [ ] First bulk ad campaign live via Facebook API (Herald)

### Phase 3: Intelligence (Week 3, Mar 17-23)
- [ ] Add approval workflow to dashboard (Builder)
- [ ] Build memory browser screen (Builder)
- [ ] Connect LinkedIn scraping pipeline (Susan + Phantom Buster)
- [ ] Add email verification via Million Verifier (Susan)
- [ ] Build competitor tracking SQLite table + dashboard (Radar)
- [ ] Automate daily metrics snapshots to SQLite (Cog)

### Phase 4: Optimisation (Week 4, Mar 24-30)
- [ ] Auto-optimise Facebook ads (kill losers, promote winners) (Herald)
- [ ] Calendar screen showing all cron jobs (Builder)
- [ ] Team screen with live agent status (Builder)
- [ ] Full pipeline: scrape → enrich → verify → email → track → optimise (Susan)
- [ ] UGC video ads via Hey Gen API (Herald)
- [ ] Performance review — what's working, what to cut (Rivet + Michael)

---

## Success Metrics (4 Weeks Out)

| Metric | Target | How Measured |
|--------|--------|-------------|
| Workers signed up | 200+ | Supabase + SQLite |
| Contractors contacted | 500+ | Instantly + SQLite |
| Email open rate | 30%+ | Instantly dashboard |
| First hire completed | ✅ Yes | Stripe + Supabase |
| Ad campaigns running | 5+ active | Facebook Ads API |
| Dashboard screens live | 5+ | rivet.rateright.com.au/ops |
| Agent memory retention | Cross-session recall working | MEM0 + memory search |
| Michael's daily check-in time | <5 minutes | Dashboard usability |

---

## Budget

| Category | Monthly | Notes |
|----------|---------|-------|
| Instantly | $30 | Cold email |
| Apollo | $0 | Free tier |
| Million Verifier | $37 | As needed |
| Phantom Buster | $69 | Month 2 |
| Hey Gen | $29 | Month 2 |
| Facebook ad spend | $500-835 | Remaining budget |
| **Total** | **$665-1,000** | Within $1K/mo allocation |

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| OpenAI flag on agents (like Herald) | Agent goes down | Fallback models configured, auto-switch |
| Instantly account flagged for spam | Email channel dead | Warm-up properly, verify emails first, low volume start |
| Facebook ad account banned | Ad channel dead | Follow policies, start conservative, separate ad account |
| SQLite corruption | Data loss | Daily backups, WAL mode, version control |
| MEM0 stores sensitive data externally | Privacy risk | Review MEM0 privacy policy, self-host if available |
| Too many tools, not enough execution | Complexity paralysis | Phase rollout, don't add tool until previous one working |

---

## Design Principles

1. **Build for Michael's phone** — Every screen must work on mobile. If he can't check it on break, it's useless.
2. **Automate the middle** — Agents do the grunt work. Michael makes decisions. Rivet coordinates.
3. **Data in SQLite, context in memory** — Structured data goes to DB. Conversational context goes to memory. Don't mix them.
4. **Start ugly, iterate fast** — V1 doesn't need to be pretty. It needs to work. Polish in Week 3-4.
5. **One new tool per week** — Don't overwhelm. Add Instantly Week 1. Apollo Week 1. Facebook Ads Week 2. Phantom Buster Week 3.
6. **This IS the product** — Everything we build for ourselves becomes the OpsMan demo. Build it like we're selling it.

---

*V1 Draft — Rivet, 2026-03-03. Iterating until Michael approves.*
