# CLAUDE.md — Fogbreak Project Instructions

**Last Updated:** March 29, 2026 (v3 — project rename from BrokerBot → Fogbreak)
**Purpose:** Operational memory for all Claude sessions working on Fogbreak. Read this FIRST before doing anything else.

---

## ⚡ RENAME CONTEXT (v3)

This project was renamed from **BrokerBot** to **Fogbreak** on March 29, 2026. All code, config, documentation, and filenames have been updated. The rename is complete.

### Post-Rename: Manual Steps for Kean

| Task | Status |
|------|--------|
| Rename folder on Mac from "BrokerBot" to "Fogbreak" | Do when copying to new project |
| Update `APP_NAME` in production `config.php` on Bluehost | Do on next deploy |
| Rename GitHub repo if still named `brokerbot` | `gh repo rename fogbreak` |

---

## PRODUCT OVERVIEW

**Fogbreak** is a modular real estate operating system: CRM, transaction coordinator, showing manager, analytics/coaching platform, and AI marketing engine. Built for The Matthams Group on California's Monterey Peninsula, architecturally designed as a white-label SaaS product for resale to any brokerage — city, state, or nationwide.

**Tagline:** "The brokerage-first, AI-native operating system for real estate teams."

### What Fogbreak Replaces (6 Platforms)
1. **Follow Up Boss** — CRM, lead routing, smart lists, action plans, speed-to-lead tracking
2. **ShowingTime** — Showing scheduling, feedback collection, seller reports, SmartRoute, broker dashboards
3. **Sisu** — KPI dashboards, agent coaching, leaderboards, gamification, GCI forecasting, ROI analytics
4. **Paperless Pipeline** — TC workflow engine, task dependencies, compliance tracking, closing calendars
5. **DocuSign** — eSignature with entity signers, signing groups, anchor tagging, audit trails
6. **RealScout** — AI property matching, preference learning, collaborative search, curated collections

### What Fogbreak Adds (No Existing Platform Does This)
- **Self-hosted AI** — Ollama (Llama 3.3 70B + Mistral 7B) for inference at zero API cost
- **AI auto-marketing** — listing descriptions, social posts, virtual staging, video/reel generation, photo enhancement
- **Native mobile apps** — iOS + Android via React Native/Expo
- **Next.js web frontend** — SSR property pages, Socket.io real-time, white-label theming
- **Database-driven market templates** — zero geographic hardcoding, scales city → state → nationwide

One integrated platform. One source of truth.

---

## WHO BUILT THIS AND WHY

- **Kean Matthams** — Founder, primary user, Monterey Coast Realty agent. Architect of the experience.
- **Sharon Matthams** — Strategic partner, Carmel Realty Company agent. End-user feedback.
- **Tracy Travaille** — Transaction coordinator. Power user, compliance expert.

**Why Fogbreak exists:** The Matthams Group needed an integrated system that understood the unique compliance requirements of the Monterey Peninsula (9 different jurisdictions, each with wildly different requirements), automated transaction workflows, and could be white-labeled for other brokerages. Existing tools didn't integrate well and felt generic.

**How it's built:** Intentionally low-cost, high-value. PHP 8.x on shared hosting. No AWS, no microservices complexity. The code is the product.

---

## TECH STACK

### Current Stack (Phase 1 — Live)

| Layer | Technology | Notes |
|-------|-----------|-------|
| **Hosting** | Bluehost shared hosting | Dedicated IP. cPanel with SSH access. |
| **Backend** | PHP 8.x | PDO prepared statements. No ORMs. |
| **Database** | MySQL 8 | `thinkwho_portal`. 25+ tables. Tenant-aware. |
| **Frontend** | Vanilla JavaScript PWA | Single HTML file (`fogbreak.html`). ~2,600 lines. Responsive CSS. |
| **Email** | cPanel SMTP + Gmail | mail.fogbreak.io:465 SSL. Gmail as IMAP inbox. |
| **Scheduling** | Bluehost cron | Runs every 15 minutes. Single unified runner (cron.php). |
| **Integration** | Google Apps Script | Gmail/Sheets sync. Custom functions. |
| **Version Control** | GitHub (fogbreak repo) | gh CLI API for pushes. No Chrome browser pushes. |
| **Deployment** | Manual upload to Bluehost | Future: CI/CD via GitHub Actions. |

### Target Stack (Phase 2+ — Building)

| Layer | Technology | Notes |
|-------|-----------|-------|
| **AI Inference** | Ollama (local) → vLLM (production) | Llama 3.3 70B (reasoning) + Mistral 7B (chatbot/routine). Zero API cost. |
| **AI Proxy** | Python FastAPI sidecar | Routes requests to correct model. OpenAI-compatible API. |
| **AI Frameworks** | LangGraph + CrewAI | Stateful workflows + team-based content generation. |
| **Database** | PostgreSQL with RLS | Row-level security for tenant isolation. Migrating from MySQL. |
| **Web Frontend** | Next.js 16 | SSR property pages, Socket.io real-time, white-label CSS variables. |
| **Mobile** | React Native / Expo | iOS + Android. Push notifications, offline-first, GPS routes. |
| **Virtual Staging** | Collov AI API | $0.23/image. Room detection, style selection. |
| **Video** | Runway API + ElevenLabs | $0.78/10s video. AI voiceover. Auto-generation on new listing. |
| **Photo** | Autoenhance.ai API | Sky replacement, HDR, color correction, perspective fix. |
| **Social** | Meta, TikTok, LinkedIn APIs | Auto-post on listing events. Content calendar. |
| **SMS** | Twilio | Two-way SMS, drip campaigns, showing confirmations. |
| **MLS** | RETS / RESO Web API | Real-time listing sync, event detection, market analytics. |

---

## FILE STRUCTURE (Actual on Disk — March 29, 2026)

```
app/                                 # Main application directory (GitHub repo root)
├── api/                             # Backend API modules
│   ├── config.php.example           # DB config template (NEVER commit config.php)
│   ├── config.php                   # [GITIGNORED] Local credentials
│   ├── auth.php                     # Login, sessions, magic links
│   ├── admin.php                    # Core CRUD, phase tracking (~1,674 lines)
│   ├── client.php                   # Client portal API
│   ├── email.php                    # Email hub: inbox, compose, SMTP, Fair Housing (~1,175 lines)
│   ├── drips.php                    # Drip campaigns: steps, enrollments, execution (~1,542 lines)
│   ├── properties.php               # Listings, saved searches, alert engine (~1,528 lines)
│   ├── transactions.php             # Deal management, 9 jurisdiction checklists (~1,071 lines)
│   ├── deadlines.php                # Relative due dates, dependencies, critical path (~1,200 lines)
│   ├── commissions.php              # Splits, tiers, forecasting (~1,373 lines)
│   ├── documents.php                # Upload, versioning, review, sharing (~1,604 lines)
│   ├── calendar.php                 # Events, Google Calendar sync
│   ├── tenants.php                  # Multi-tenant white-label
│   ├── cron.php                     # Unified task runner, 8 jobs
│   ├── esign.php                    # eSignature engine (~2,793 lines) [Phase 2, 70% complete]
│   ├── sheets.php                   # Google Sheets proxy with cache
│   ├── migrate_fogbreak.php          # 13 new tables + extensions
│   └── migrate_tenants.php          # Tenant table + tenant_id columns
│
├── fogbreak.html                    # Main 8-tab SPA dashboard
│   # Tabs: Dashboard, Clients, Deals, Email, Properties, Transactions, Documents, Calendar
│
├── admin.html                       # Legacy admin dashboard
├── portal.html                      # Client portal
├── index.html                       # Client portal login
├── sign.html                        # eSignature signing interface [Phase 2]
│
├── js/                              # Frontend modules
│   ├── daily-action-feed.js         # Priority ranking (0-100)
│   ├── lead-scoring.js              # Scoring algorithm
│   ├── outreach-drafts.js           # Draft generation + Fair Housing
│   └── pipeline-analytics.js        # KPIs, funnel, trends
│
├── responsive.css                   # 5-breakpoint grid system (mobile-first)
├── sw.js                            # Service worker (offline cache)
├── manifest.json                    # PWA manifest
│
├── ARCHITECTURE.html                # Full system architecture spec (5,000+ words)
│
├── google-apps-script/              # Google Apps Script integration
│   ├── Code.gs                      # Gmail/Calendar/Sheets functions
│   └── SETUP.md                     # Deployment to Google
│
└── claude-code-instructions/        # 24 build instruction files
    ├── 00-MASTER-PLAN.md            # Run order, architecture, key decisions
    ├── 01-GEOGRAPHIC-EXTRACTION.md  # Remove 232 hardcoded refs, build market templates
    ├── 02-DATABASE-REDESIGN.md      # PostgreSQL migration with RLS
    ├── 03-SELF-HOSTED-AI.md         # Ollama setup, FastAPI proxy, 10 agent types
    ├── 04-FOLLOW-UP-BOSS-REPLACEMENT.md
    ├── 05-SHOWINGTIME-REPLACEMENT.md
    ├── 06-SISU-REPLACEMENT.md
    ├── 07-PAPERLESS-PIPELINE-REPLACEMENT.md
    ├── 08-DOCUSIGN-REPLACEMENT.md   # 5 security fixes FIRST, then features
    ├── 09-REALSCOUT-REPLACEMENT.md
    ├── 10-AI-COPY-ENGINE.md
    ├── 11-SOCIAL-MEDIA-AUTOMATION.md
    ├── 12-VIRTUAL-STAGING.md
    ├── 13-VIDEO-REEL-GENERATION.md
    ├── 14-PHOTO-ENHANCEMENT.md
    ├── 15-NEXTJS-WEB-APP.md
    ├── 16-REACT-NATIVE-MOBILE.md
    ├── 17-CLIENT-PORTAL.md
    ├── 18-MLS-INTEGRATION.md
    ├── 19-SMS-TWILIO.md
    ├── 20-ADVANCED-ANALYTICS.md
    ├── 21-SELF-HOST-MIGRATION.md
    ├── 22-VENDOR-MARKETPLACE.md
    └── 23-DATA-MIGRATION.md
```

**Total codebase:** 23,000+ lines across 30+ files (Phase 1). 24 instruction files define the full Phase 2+ build plan.

### Key Files to Know
- **fogbreak.html** — THE main interface. Start here for any feature work.
- **api/admin.php** — Core API. All CRUD operations flow through this.
- **api/esign.php** — Largest module (2,793 lines). eSignature engine. Phase 2 priority. Has 5 critical security fixes pending.
- **api/email.php** — Email hub. Inbox, compose, Fair Housing audit, SMTP.
- **api/transactions.php** — Transaction management + jurisdiction compliance checklists.
- **api/drips.php** — Automated campaign engine. Runs via cron.
- **ARCHITECTURE.html** — Read this before major refactors. Documents every system interaction.
- **claude-code-instructions/00-MASTER-PLAN.md** — Read this before starting any new feature work.

---

## DATABASE SCHEMA

**Database name:** Configured per tenant (Tenant #1 uses `thinkwho_portal`)

### Core Tables

**CRM:** `clients` (lifecycle: lead → active → closed → repeat), `interactions` (calls, meetings, emails per client), `tasks` (phase-dependent auto-generation)

**Email:** `email_messages` (all inbox via IMAP + SMTP), `email_log` (outbound record)

**Automation:** `drip_campaigns` (4 defaults: buyer nurture, seller nurture, re-engage, past-client), `drip_steps` (individual campaign emails/SMS), `drip_enrollments` (client progress tracking)

**Properties:** `properties` (listings — MLS + custom), `saved_searches` (per client/agent), `property_alerts` (sent alerts)

**Transactions:** `transactions` (deals with 9 jurisdiction templates), `compliance_items` (jurisdiction checklists per deal), `deadline_templates` (relative due dates per jurisdiction), `documents` (uploads), `doc_activity` (version history), `doc_shares` (secure sharing)

**Financial:** `commissions` (per deal), `commission_splits` (co-list, team), `commission_tiers` (tiered rates)

**Calendar:** `calendar_events` (synced with Google Calendar)

**System:** `admins` (user accounts), `admin_sessions` (24-hour tokens), `tenants` (multi-tenant configs), `cron_log` (execution history)

### Schema Pattern
Every table has: `id` (PK auto-increment), `tenant_id` (NULL = Matthams Group), `created_at`, `updated_at`. All foreign keys use `tenant_id + local_id` to prevent cross-tenant data leaks.

---

## API ARCHITECTURE

### Request/Response Pattern

Every API module follows: auto-migration (create tables if missing) → auth check (session token or API key) → route by `$_GET['action']` via switch statement → JSON response.

### Authentication

1. **Session Token** (human users): POST `/api/auth.php?action=login` → 24-hour token in `admin_sessions`
2. **API Key** (automation/cron): `MTH_PORTAL_2026` via `Authorization: Bearer` header. No expiry.

### Standards
- ALL queries use PDO prepared statements. No string interpolation. Zero SQL injection tolerance.
- All responses: `{"success": true/false, "data": {...}, "message": "..."}` or `{"error": "...", "code": 400}`
- Helper functions in config.php: `getDB()`, `jsonResponse()`, `getBody()`, `generateToken()`, `tableExists()`, `validateAPIKey()`, `logCronExecution()`

---

## DEPLOYMENT

### Source of Truth: GitHub

- **Repo:** `fogbreak` (private, Kean's account)
- **Branch:** `main`
- **Push via:** gh CLI only. Never Chrome browser.
- **Deploy:** Manual upload to Bluehost via cPanel. Future: GitHub Actions.
- **Config:** `config.php` is .gitignored. Never committed. Copy from `config.php.example`.

---

## CRON JOBS

**Runner:** `api/cron.php` | **Schedule:** Every 15 minutes via Bluehost | **Auth:** API key

**8 Active Jobs:** drip_execute (send campaign emails), property_alerts (match new listings to saved searches), deadline_notify (alert on upcoming/overdue tasks), commission_forecast (aggregate open deals), document_review_remind (nudge after 5 days pending), calendar_sync (Google Calendar bidirectional), email_sync (pull Gmail inbox), morning_brief (8 AM weekday summary to Kean + Sharon)

All jobs are idempotent with execution logging to `cron_log`.

---

## THREE-BRAND SYSTEM

Never mix brands. Each has unique visual identity and voice.

| Attribute | Matthams Group | MCR | CRC |
|-----------|---|---|---|
| **Primary** | #1A3347 (deep ocean) | #004434 (dark teal) | #532B19 (rich brown) |
| **Accent** | #A8875B (weathered brass) | #148FF8 (blue) | #D4AF37 (gold) |
| **Background** | #F4F1EC (driftwood) | #F2F2F3 (light gray) | #FAF9F5 (cream) |
| **Text** | #1C1C1C (near-black) | #133234 (teal-dark) | #543B22 (brown-dark) |
| **Use Case** | Umbrella, group marketing | Kean's listings, Peninsula | Sharon's listings, Carmel/PB |
| **Typography** | Playfair Display + Inter | "BS" sans-serif | Minion Pro serif |

Implementation: CSS variables (`--primary`, `--accent`, `--bg`, `--text`), drip campaign `brand` field, brand-specific alert templates and outreach drafts.

---

## JURISDICTION COMPLIANCE (Monterey Peninsula — Tenant #1 Seed Data)

9 jurisdictions, each with unique inspection/certification/timeline requirements. Post-geographic extraction (instruction 01), these move to database `compliance_templates` and `market_configs` tables.

**Key jurisdictions:** Carmel-by-the-Sea (volume not sqft, CFO permit, ~30 days, ~$2K), Pacific Grove (RZRR 10 biz days, $502), Monterey (sewer lateral CAWD only, 21 days), Marina (online inspection, 5 days, $180), Pebble Beach (80% entity signers, 35 days, ~$3K), plus Seaside, Del Rey Oaks, Sand City, Monterey County unincorporated.

**Critical gotchas:** Carmel uses VOLUME not sqft. CAWD sewer lateral is Carmel/PG/Monterey only — NOT countywide. Water Efficiency vs Water Conservation certificates are different. PG RZRR is the longest single requirement. Pebble Beach entity signers dominate.

---

## WHAT'S BEEN BUILT (Phase 1 — Complete)

✅ CRM with lifecycle management, lead scoring, task management, interaction logging
✅ Full email system (IMAP inbox, SMTP compose, threading, Fair Housing audit)
✅ Drip campaign engine (4 campaigns, auto-enrollment, scheduler, cron execution)
✅ Property alerts (saved searches, branded templates, bulk import)
✅ Transaction management (9 jurisdictions, compliance checklists, relative deadlines, critical path)
✅ Commission tracking (splits, tiers, agent reporting, pipeline forecast)
✅ Document management (upload, versioning, review workflow, secure sharing)
✅ Calendar (Google Calendar sync, auto-task generation)
✅ Multi-tenant architecture (tenant isolation, configurable branding, per-tenant admin)
✅ 8 automated cron jobs
✅ 8-tab PWA dashboard (responsive, offline-capable)

---

## BUILD PLAN — 24 Claude Code Instructions

Full plan in `claude-code-instructions/`. Run in order per `00-MASTER-PLAN.md`.

**Foundation (sequential, these first):**
1. `01-GEOGRAPHIC-EXTRACTION` — Remove 232 hardcoded Monterey references. Build database-driven market templates. Gate for nationwide scaling.
2. `02-DATABASE-REDESIGN` — MySQL → PostgreSQL with RLS. 20+ new tables.
3. `03-SELF-HOSTED-AI` — Ollama + FastAPI proxy. 10 AI agent types. RAG pipeline. Unlocks 8 downstream features.

**Platform Replacements (parallel after foundation):** 04 (FUB), 05 (ShowingTime), 06 (Sisu), 07 (Paperless Pipeline), 08 (DocuSign — 5 security fixes first), 09 (RealScout)

**AI Marketing Suite (after AI layer):** 10 (Copy), 11 (Social), 12 (Virtual Staging), 13 (Video), 14 (Photo)

**Client Apps (after platform replacements):** 15 (Next.js), 16 (React Native), 17 (Client Portal)

**Integration & Scale:** 18 (MLS), 19 (SMS/Twilio), 20 (Analytics), 21 (Self-host migration), 22 (Vendor Marketplace), 23 (Data Migration)

### eSignature Module — 70% Complete, 5 Critical Fixes Required

**Built:** 27 API endpoints, sequential/parallel signing, SHA-256 audit trail, email automation, signing UI, template infrastructure, ESIGN Act compliance, cron automation.

**Critical fixes before production (~45 min):**
⚠️ SQL injection on line 758 (handleRemoveRecipient)
⚠️ Hardcoded tenant_id=1 in 8 locations
⚠️ Missing tenant_id filters on envelope queries (cross-tenant data leak)
⚠️ PIN generated but never validated
⚠️ No deal ownership check (privilege escalation)

### Geographic Extraction — The Gate

232 hardcoded Monterey Peninsula references across 20 files. Until instruction 01 is complete, Fogbreak cannot scale beyond Monterey. This is the first thing to build.

---

## OPERATIONAL RULES

1. **Tenant isolation is sacred.** All queries filtered by `tenant_id`. One mistake = cross-brokerage data leak.
2. **Fair Housing audit on ALL outbound content.** Drip emails, alerts, AI copy, social posts, outreach drafts. Non-negotiable. Includes AI output.
3. **Zero geographic hardcoding.** All geographic data from database market templates. #1 scaling constraint.
4. **Never commit credentials.** `config.php` is .gitignored.
5. **All queries: PDO prepared statements.** No string interpolation. Zero SQL injection tolerance.
6. **Push to GitHub via gh CLI.** Never Chrome.
7. **Execution, not delegation.** Build it. Don't hand off terminal commands.
8. **Test locally where possible.** LAMP stack before production push.
9. **Read ARCHITECTURE.html before major refactors.**
10. **Idempotent cron jobs.** Never send the same email twice.
11. **Never mix brands.** Each output uses ONE brand voice only.
12. **AI output is never auto-published.** All AI content goes through approval workflow. Human in the loop.
13. **All 6 replaced platforms referenced in context.** No partial framing.
14. **Read `00-MASTER-PLAN.md` before starting new feature work.**

---

## PROJECT SEPARATION

| | Fogbreak (this project) | The Matthams Group |
|---|---|---|
| **Purpose** | The product (code + architecture) | The customer (Tenant #1) |
| **Contains** | Application code, API modules, build instructions | Client data, transactions, marketing, contacts |
| **Code changes** | Made here | Never |
| **Client data** | Never stored here | Lives there |

Work on Fogbreak features here. Work on Matthams transactions/marketing/clients in The Matthams Group project.

---

## COMMUNICATION STYLE

Per Kean's preferences:
- He is the **Architect of the experience**, not a seeker of approval.
- Replace hedging ("I think," "maybe") with direct, clear statements.
- Factor in recovery context (post-op right arm, chronic left knee) — be mindful of task duration.
- Prioritize natural warmth and craft-focused depth over tactical posturing.
- Use architectural metaphors where they land naturally.
- Luxury market context: Carmel, Marina, Pebble Beach — family legacy.

---

## SESSION STARTUP CHECKLIST

1. **Read this CLAUDE.md first.** All the way through.
2. **Read `claude-code-instructions/00-MASTER-PLAN.md`** for full build plan and status.
3. **Check for new files:** `ls -la app/api/ app/js/` — any new modules since last session?
4. **Read ARCHITECTURE.html** if planning major changes.
5. **Identify which instruction file to execute next.** Check master plan for dependencies.
6. **Brief Kean on status:** What's done, what's blocked, what's next (and why).
7. **Ask clarifying questions** if requirements are vague. Get clarity before coding.

---

## GLOSSARY

**Fogbreak** — This system. CRM + TC + showings + analytics + AI marketing. | **Deal** — Active transaction. | **Phase** — Deal lifecycle stage (0-9). | **Drip** — Automated email campaign. | **Enrollment** — Client added to a drip. | **Saved Search** — Client property search criteria triggering alerts. | **Compliance Item** — Jurisdiction-specific requirement. | **Deadline Template** — Relative due date rule. | **Commission Split** — Revenue distribution. | **Tenant** — White-label instance (NULL = Matthams Group). | **Fair Housing** — US housing law; all outreach audited. | **CFO** — Carmel Forest Officer. | **CAWD** — Carmel Area Water District (sewer laterals, Carmel/PG/Monterey only). | **MCWD** — Marina Coast Water District. | **eSign** — Built-in DocuSign replacement (70% complete). | **Ollama** — Local AI inference server. | **vLLM** — Production AI inference target. | **RAG** — Retrieval-Augmented Generation for property matching. | **Market Template** — DB-driven geographic config. | **SmartRoute** — GPS showing optimizer. | **GCI** — Gross Commission Income. | **Virtual Staging** — AI room furnishing ($0.23/image via Collov). | **Anchor Tagging** — Auto-place signature fields on documents.

---

**End of CLAUDE.md**

Last sync: March 29, 2026 (v3) | Renamed from BrokerBot → Fogbreak | Full scope: 6-platform replacement + AI marketing + self-hosted AI + native apps | 24 instruction files | Next: execute instruction 01 (Geographic Extraction)
