# 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
- **Contact data enrichment** — Hidden deal detection, API integrations, probability scoring
- **Home valuation widget** — CMA builder, seller lead capture, comparable analysis
- **Private/off-market listings hub** — Buyer matching, access control, invitation workflow
- **Collaborative buyer/seller boards** — Real-time workspaces, shared deal notes, team coordination
- **Voice note transcription** — AI entity extraction, CRM auto-population, searchable archives
- **Paid ad campaign management** — Google, Meta, TikTok, LinkedIn integration + budget tracking
- **AI blog engine** — SEO optimization, content calendar, auto-publishing, social amplification
- **AI lead nurture engine** — 24/7 automated engagement, preference learning, autonomous response
- **Enhanced IDX property search** — Advanced filters, saved searches, market analytics dashboard
- **Google One Tap SSO** — High-conversion lead capture, passwordless authentication
- **Autonomous AI marketing agents** — SEO agent, Blog agent, Ads agent, Nurture agent, Social agent
- **Website template engine** — Agent and brokerage website builder with curated templates, IDX, blog, lead capture

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. Document root: `fogbreak.io/` (peer to `public_html/`). |
| **Backend** | PHP 8.x | PDO prepared statements. No ORMs. |
| **Database** | MySQL 8 | `thinkwho_fogbreak`. 25+ tables. Tenant-aware. |
| **Frontend** | Vanilla JavaScript PWA | Single HTML file (`fogbreak.html`). ~13,600 lines. 26-tab SPA. 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
│   ├── enrichment.php               # Contact data enrichment + deal probability (~1,100 lines)
│   ├── valuation.php                # Home valuation widget + CMA builder (~1,100 lines)
│   ├── private_listings.php         # Off-market listings hub + buyer matching (~1,050 lines)
│   ├── boards.php                   # Collaborative buyer/seller boards (~1,100 lines)
│   ├── voice_notes.php              # Voice transcription + CRM extraction (~823 lines)
│   ├── ads.php                      # Paid ad campaign manager (~1,247 lines)
│   ├── blog.php                     # AI blog engine + SEO optimization (~1,250 lines)
│   ├── ai_nurture.php              # AI lead nurture 24/7 auto-response (~1,200 lines)
│   ├── website_templates.php        # NEW: Website template engine + public sites (~1,400 lines)
│   ├── migrate_fogbreak.php          # 13 new tables + extensions
│   ├── migrate_lp_features.php      # Migration for all LP-inspired tables
│   └── 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/        # 35 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
    ├── 24-CONTACT-ENRICHMENT.md
    ├── 25-HOME-VALUATION-CMA.md
    ├── 26-AD-CAMPAIGN-MANAGER.md
    ├── 27-PRIVATE-LISTINGS-HUB.md
    ├── 28-GOOGLE-ONE-TAP-SSO.md
    ├── 29-VOICE-NOTES-CRM.md
    ├── 30-COLLABORATIVE-BOARDS.md
    ├── 31-AUTONOMOUS-AI-AGENTS.md
    ├── 32-BLOG-ENGINE.md
    ├── 33-AI-LEAD-NURTURE.md
    ├── 34-ENHANCED-IDX-SEARCH.md
    └── 35-WEBSITE-TEMPLATE-ENGINE.md
```

**Total codebase:** 32,900+ lines across 40+ files (Phase 1 + Phase 1.5). 35 instruction files define the full 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.
- **api/enrichment.php** — Contact enrichment, hidden deal detection, probability scoring.
- **api/blog.php** — AI blog engine, SEO, content calendar, auto-publishing.
- **api/ai_nurture.php** — Autonomous 24/7 lead engagement, preference learning.
- **api/ads.php** — Paid ad management across Google, Meta, TikTok, LinkedIn.
- **api/private_listings.php** — Off-market hub, buyer matching, access control.
- **api/website_templates.php** — Website template engine. Public site builder with templates, pages, sections, forms, analytics.
- **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_fogbreak`)

### 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)

**Enrichment:** `contact_enrichment` (enriched profiles), `enrichment_events` (tracking updates), `enrichment_sources` (API integrations), `enrichment_queue` (async processing), `deal_probability_scores` (AI predictions)

**Valuation:** `home_valuations` (estimates), `cma_reports` (comparable analyses), `cma_comps` (comparable properties), `valuation_configs` (market settings)

**Private Listings:** `private_listings` (off-market deals), `private_listing_access` (permission grants), `buyer_needs` (preference profiles), `buyer_matches` (match results), `private_listing_views` (engagement tracking), `private_listing_invites` (access workflow)

**Boards:** `boards` (workspaces), `board_members` (access), `board_items` (deal notes), `board_item_comments` (threads), `board_item_ratings` (voting), `board_activity` (audit log)

**Voice Notes:** `voice_notes` (recordings), `voice_extractions` (AI-parsed entities), `voice_note_tags` (categorization), `voice_note_actions` (auto-created tasks)

**Advertising:** `ad_campaigns` (campaign definitions), `ad_creatives` (ad variants), `ad_audiences` (target segments), `ad_performance` (metrics), `ad_platform_accounts` (connected accounts), `ad_rules` (automation rules), `ad_landing_pages` (conversion pages)

**Blog:** `blog_posts` (articles), `blog_categories` (taxonomy), `blog_tags` (topic tags), `blog_post_tags` (assignment), `blog_post_categories` (assignment), `blog_authors` (contributor metadata), `blog_comments` (reader engagement), `blog_analytics` (performance tracking), `blog_content_calendar` (scheduling), `blog_seo_audits` (optimization tracking)

**AI Nurture:** `ai_nurture_conversations` (chat sessions), `ai_nurture_messages` (turn history), `ai_nurture_preferences` (learned buyer/seller preferences), `ai_nurture_handoffs` (human escalation log), `ai_nurture_configs` (tenant personality), `ai_nurture_metrics` (engagement KPIs)

**Website Templates:** `website_templates` (template library), `website_sites` (published sites), `website_pages` (site pages), `website_sections` (page sections), `website_media` (uploads), `website_navigation` (nav menus), `website_forms` (lead capture forms), `website_form_submissions` (submitted leads), `website_analytics` (traffic data), `website_domains` (custom domains), `website_testimonials` (client reviews), `website_team_members` (team profiles)

**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-io/fogbreak` (private)
- **Branch:** `main`
- **Push via:** gh CLI only. Never Chrome browser.
- **Domain:** `fogbreak.io` — own document root on Bluehost (peer to `public_html/`, NOT inside it)
- **Deploy:** Manual upload to Bluehost via cPanel. Future: GitHub Actions.
- **Config:** `config.php` is .gitignored. Never committed. Copy from `config.php.example`.
- **Live URL:** `https://fogbreak.io/pwa/app/fogbreak.html`

---

## CRON JOBS

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

**16 Active Jobs (Phase 1 + 1.5):**
- 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)
- enrichment_process (nightly contact enrichment queue)
- deal_probability_calc (update probability scores)
- ai_nurture_touchpoints (every 5 min autonomous messaging)
- ai_nurture_temperature (hourly preference refinement)
- blog_publish_scheduled (auto-publish queued posts)
- ad_metrics_sync (hourly sync from ad platforms)
- ad_rule_engine (execute automation rules)
- voice_transcribe (async transcription queue)

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

---

## BRANDING SYSTEM

Each tenant configures a single brand identity stored in the `tenants` table. Fogbreak applies this brand automatically across all outputs — websites, emails, CMA presentations, blog posts, ad creatives, social content, client portals, and mobile apps.

### Per-Tenant Brand Config (stored in tenants table)
- `brand_name` — Display name (e.g. "The Matthams Group")
- `primary_color` — Primary brand color (hex)
- `accent_color` — Accent color (hex)
- `bg_color` — Background color (hex)
- `text_color` — Text color (hex)
- `font_heading` — Heading font family
- `font_body` — Body font family
- `logo_url` — Logo image path
- `brand_voice` — Text description of brand voice for AI content generation

### How Branding Works
- CSS variables (`--primary`, `--accent`, `--bg`, `--text`) are injected from tenant config on every page load
- AI-generated content (blog posts, ad copy, nurture messages, social posts) uses `brand_voice` instructions
- Email templates, CMA presentations, and documents pull brand colors and logo automatically
- Individual agents within a tenant can have their own headshot, bio, and contact info — but inherit the tenant's brand identity

### Legacy Note
The original codebase has a `brand` VARCHAR field in some tables (deals, properties, drip_campaigns) with values like 'TMG', 'MCR', 'CRC'. This was a Tenant #1 (Matthams Group) artifact for routing content between two brokerages. For the SaaS platform, branding is handled entirely by tenant_id — each tenant IS a brand. The legacy brand field will be deprecated during the geographic extraction phase (instruction 01).

---

## 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)

---

## WHAT'S BEING BUILT (Phase 1.5 — LP Feature Parity, In Progress)

🔨 Contact data enrichment (API integrations, deal probability, hidden deal detection)
🔨 Home valuation widget (Zillow/Redfin APIs, CMA builder, seller lead capture)
🔨 Private/off-market listings hub (buyer matching, access control, invitation workflow)
🔨 Collaborative buyer/seller boards (real-time workspaces, shared notes, team coordination)
🔨 Voice note transcription (Whisper API, CRM auto-population, entity extraction)
🔨 Paid ad campaign manager (Google, Meta, TikTok, LinkedIn, budget tracking, automation rules)
🔨 AI blog engine (SEO optimization, content calendar, auto-publish, social amplification)
🔨 AI lead nurture engine (24/7 autonomous messaging, preference learning, handoff workflow)
🔨 Enhanced IDX property search (advanced filters, market analytics, saved searches)
🔨 Google One Tap SSO (passwordless lead capture, high conversion)
🔨 Autonomous AI marketing agents (SEO agent, Blog agent, Ads agent, Nurture agent, Social agent)
🔨 8 new cron jobs for LP feature automation

---

## BUILD PLAN — 35 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)

**Phase 1.5 — Luxury Presence Feature Parity (parallel after foundation):** 24 (Enrichment), 25 (Valuation/CMA), 26 (Ads), 27 (Private Listings), 28 (One Tap SSO), 29 (Voice Notes), 30 (Boards), 31 (Autonomous Agents), 32 (Blog), 33 (AI Nurture), 34 (Enhanced IDX), 35 (Website Template Engine)

### 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. **Branding is tenant-level.** All outputs (emails, presentations, AI content) automatically use the tenant's configured brand identity.
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 (v4) | Renamed from BrokerBot → Fogbreak | Full scope: 6-platform replacement + AI marketing + self-hosted AI + native apps + LP feature parity | 35 instruction files | Phase 1.5: Contact Enrichment, Valuation/CMA, Ads, Private Listings, Voice Notes, Boards, Blog, AI Nurture, Enhanced IDX, Autonomous Agents, One Tap SSO | Next: execute instruction 01 (Geographic Extraction)
