Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

Initial commit: Harvey — autonomous AI sales agent

Ethanb5e4017cba22
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..5e53c2c
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,12 @@
+# Instantly API
+INSTANTLY_API_KEY=your_instantly_api_key_here
+
+# LinkedIn (for browser automation)
+LINKEDIN_EMAIL=your_linkedin_email
+LINKEDIN_PASSWORD=your_linkedin_password
+
+# Hunter.io (optional, free tier = 50 lookups/mo)
+HUNTER_API_KEY=your_hunter_api_key_here
+
+# Calendar (later)
+# CALENDLY_API_KEY=your_calendly_api_key_here
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..cc5dab4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,33 @@
+# Environment
+.env
+*.env
+
+# Data
+data/
+*.db
+
+# Python
+__pycache__/
+*.pyc
+*.pyo
+*.egg-info/
+dist/
+build/
+.venv/
+venv/
+
+# LinkedIn cookies
+linkedin_cookies.json
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Claude
+.claude/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..79d6072
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,29 @@
+FROM python:3.12-slim
+
+# Install system dependencies
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ curl \
+ && rm -rf /var/lib/apt/lists/*
+
+# Install Claude Code CLI
+RUN curl -fsSL https://claude.ai/install.sh | sh || true
+
+# Install Playwright system deps
+RUN pip install playwright && playwright install --with-deps chromium
+
+WORKDIR /app
+
+# Install Python dependencies
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# Copy project
+COPY harvey/ harvey/
+COPY prompts/ prompts/
+COPY harvey.yaml .
+
+# Create data directory
+RUN mkdir -p /app/data
+
+# Run Harvey
+CMD ["python", "-m", "harvey.main"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..43cc4d8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,386 @@
+# Harvey
+
+**The autonomous AI sales agent that never stops closing.**
+
+Harvey is an open-source, fully autonomous sales agent that finds prospects, writes personalized cold email campaigns, sends them, monitors replies, handles objections, and books meetings — all without human intervention. Named after Harvey Specter from *Suits*, because the best closer in New York never sleeps.
+
+Harvey runs on your existing Claude Max subscription (zero extra LLM cost), deploys to any VPS with Docker, and replaces expensive prospecting tools by finding leads on its own.
+
+```
+$ python -m harvey
+
+============================================================
+Harvey is online. Always Be Closing.
+============================================================
+Database initialized.
+Thinking about what to do next...
+Decision: prospect
+Scout: Starting prospecting cycle...
+Scout: Searching LinkedIn...
+Scout: Added prospect Sarah Chen — VP Marketing at Acme SaaS
+Scout: Added prospect James Rivera — Head of Growth at GrowthCo
+...
+```
+
+---
+
+## What Harvey Does
+
+Harvey runs a continuous heartbeat loop — wake up, decide what needs doing, do it, log the results, sleep, repeat. Every 15 minutes (configurable), Harvey checks the state of your sales pipeline and takes the highest-priority action.
+
+### The Loop
+
+```
+Wake Up → Check Budget → Decide → Act → Log → Sleep → Repeat
+ ↑ |
+ └────────────────────────────────────────────────────┘
+```
+
+### Sub-Agents
+
+Harvey feels like one agent, but under the hood it coordinates five specialized sub-agents:
+
+| Agent | What It Does |
+|-------|-------------|
+| **Scout** | Finds prospects matching your ICP — via LinkedIn search, Google dorking, company website scraping, and email pattern discovery. No Apollo or ZoomInfo needed. |
+| **Writer** | Crafts personalized 3-email sequences using proven frameworks (AIDA, PAS, BAB). Every email is tailored to the prospect's role, company, and industry. |
+| **Sender** | Deploys campaigns to Instantly (or Woodpecker) via API. Adds leads, sets sequences, activates campaigns, and tracks delivery. |
+| **Handler** | Monitors all replies. Classifies intent (interested, objection, not interested, OOO, wrong person) and auto-responds with context-aware messages that move toward a meeting. |
+| **Analyst** | *(Coming soon)* Tracks what's working — which subject lines, frameworks, ICP segments, and send times produce the best results — and adjusts Harvey's approach automatically. |
+
+### Skills System
+
+Each sub-agent is loaded with foundational sales knowledge from Harvey's skills library:
+
+| Skill | What It Teaches |
+|-------|----------------|
+| **Email Frameworks** | AIDA, PAS, BAB, QVC, 3Ps — when to use each, with templates and selection rules |
+| **Objection Handling** | LAARC framework, responses for Budget/Authority/Need/Timing objections, advanced techniques |
+| **Lead Qualification** | BANT screening, ICP scoring (1-10 scale), MEDDIC for complex deals |
+| **LinkedIn Outreach** | Connection sequences, warm-up strategies, messaging templates, rate limits |
+| **Prospecting Tactics** | Google dorking, company scraping, email discovery, trigger events, referral mining |
+| **Sales Methodology** | Multi-channel orchestration, COSTAR tone calibration, decision priorities, ethical guidelines |
+
+Skills are plain markdown files in the `skills/` directory. Edit them to change how Harvey sells — no code changes needed.
+
+---
+
+## How It Works
+
+### Architecture
+
+```
+┌─────────────────────────────────────────────────┐
+│ HARVEY (VPS) │
+│ │
+│ ┌───────────┐ Heartbeat Loop │
+│ │ Scheduler │──► Wake → Decide → Act → Log │
+│ └───────────┘ │
+│ │
+│ ┌─────────────────────────────────────────┐ │
+│ │ Brain (Claude Code CLI) │ │
+│ │ claude -p (your Max subscription) │ │
+│ └─────────┬───────────────────────────────┘ │
+│ │ │
+│ ┌─────────▼───────────────────────────────┐ │
+│ │ Sub-Agents │ │
+│ │ Scout → Writer → Sender → Handler │ │
+│ └─────────────────────────────────────────┘ │
+│ │
+│ ┌─────────────────────────────────────────┐ │
+│ │ Integrations │ │
+│ │ Instantly API │ Playwright │ SMTP │ │
+│ └─────────────────────────────────────────┘ │
+│ │
+│ ┌─────────────────────────────────────────┐ │
+│ │ State (SQLite) │ │
+│ │ Prospects │ Campaigns │ Conversations │ │
+│ └─────────────────────────────────────────┘ │
+└─────────────────────────────────────────────────┘
+```
+
+### The Brain
+
+Harvey's brain is Claude, accessed through Claude Code's headless mode (`claude -p`). This means Harvey runs on your existing Claude Max subscription — no API keys, no per-token charges, no surprise bills. An always-running autonomous agent would cost hundreds per month on API pricing. With Max, it's included.
+
+The brain handles all reasoning: deciding what to do next, writing emails, classifying reply intent, generating objection responses, and finding personalization angles.
+
+### DIY Prospecting
+
+Most sales tools charge $200+/month for lead databases. Harvey finds prospects for free:
+
+1. **LinkedIn Search** — Playwright browser automation searches for people matching your ICP (title, industry, location). Logs into your LinkedIn account and extracts profiles with human-like behavior patterns.
+
+2. **Google Dorking** — Targeted search queries like `site:linkedin.com/in "VP Marketing" "SaaS"` find profiles indexed by Google.
+
+3. **Company Website Scraping** — Checks /team, /about, /people pages to find decision-makers and their roles.
+
+4. **Email Pattern Discovery** — Given a name and company domain, Harvey tries common email patterns (first.last@, first@, flast@) and verifies them via MX record lookup and SMTP checks. No paid verification service needed.
+
+### Usage Control
+
+Harvey tracks its own Claude usage and lets you set a daily limit. Set `max_daily_claude_percent: 80` in your config and Harvey will stop working when it hits 80% of its daily budget — then pick back up the next morning.
+
+Quiet hours are also configurable. Harvey won't run between 10pm and 7am (or whatever you set).
+
+---
+
+## Quick Start
+
+### Prerequisites
+
+- Python 3.11+
+- [Claude Code CLI](https://claude.ai/download) installed and authenticated (with a Max subscription)
+- An [Instantly](https://instantly.ai) account with API access (for cold email)
+- A LinkedIn account (for prospecting)
+
+### 1. Clone and Install
+
+```bash
+git clone https://github.com/yourusername/harvey.git
+cd harvey
+pip install -r requirements.txt
+playwright install chromium
+```
+
+### 2. Configure
+
+Copy the example environment file and add your credentials:
+
+```bash
+cp .env.example .env
+```
+
+Edit `.env`:
+```
+INSTANTLY_API_KEY=your_key_here
+LINKEDIN_EMAIL=your_linkedin_email
+LINKEDIN_PASSWORD=your_linkedin_password
+```
+
+Edit `harvey.yaml` with your product, persona, and ICP:
+
+```yaml
+persona:
+ name: "Harvey"
+ company: "Acme Corp"
+ role: "Business Development"
+ linkedin: "linkedin.com/in/harvey-acme"
+ tone: "professional, consultative, confident"
+
+product:
+ name: "AcmeWidget"
+ description: "AI-powered widget optimization for e-commerce teams"
+ pricing: "Starting at $99/mo"
+ key_benefits:
+ - "Increases conversion rates by 30%"
+ - "Reduces manual work by 10 hours/week"
+ - "Integrates with Shopify, WooCommerce, BigCommerce"
+ objection_responses:
+ "too expensive": "Most clients see ROI within 30 days..."
+ "already have a solution": "What's the one thing you wish it did better?"
+
+icp:
+ industries: ["E-commerce", "DTC Brands"]
+ company_size: "10-200 employees"
+ titles: ["VP Marketing", "Head of Growth", "E-commerce Director"]
+ geography: ["United States"]
+
+channels:
+ email:
+ enabled: true
+ provider: "instantly"
+ max_daily_sends: 50
+ linkedin:
+ enabled: true
+ max_daily_connections: 20
+ max_daily_messages: 10
+
+usage:
+ max_daily_claude_percent: 80
+ heartbeat_interval_minutes: 15
+ quiet_hours:
+ start: "22:00"
+ end: "07:00"
+ timezone: "America/New_York"
+```
+
+### 3. Run
+
+```bash
+python -m harvey
+```
+
+Harvey will:
+1. Initialize the database
+2. Start the heartbeat loop
+3. Begin prospecting, writing campaigns, and handling outreach automatically
+
+### 4. Deploy (VPS)
+
+For always-on operation, deploy with Docker:
+
+```bash
+# Make sure Claude CLI is authenticated first
+claude login
+
+# Start Harvey
+docker compose up -d
+
+# Watch the logs
+docker compose logs -f harvey
+```
+
+---
+
+## Project Structure
+
+```
+harvey/
+├── harvey.yaml # Your config — persona, product, ICP, settings
+├── .env # API keys (never committed)
+├── docker-compose.yml # One-command VPS deployment
+├── Dockerfile
+├── requirements.txt
+│
+├── harvey/
+│ ├── main.py # Heartbeat loop — the core engine
+│ ├── brain.py # Claude Code headless wrapper + skills loader
+│ ├── state.py # SQLite state manager
+│ ├── config.py # Configuration loader + validation
+│ │
+│ ├── agents/
+│ │ ├── scout.py # DIY prospecting
+│ │ ├── writer.py # Email sequence generation
+│ │ ├── sender.py # Campaign deployment via Instantly
+│ │ ├── handler.py # Reply processing + auto-response
+│ │ └── analyst.py # (Coming soon) Learning from outcomes
+│ │
+│ ├── integrations/
+│ │ ├── instantly.py # Instantly API v2 client
+│ │ ├── linkedin.py # Playwright browser automation
+│ │ ├── email_finder.py # Email pattern discovery + SMTP verification
+│ │ └── calendar.py # (Coming soon) Meeting booking
+│ │
+│ └── models/
+│ ├── prospect.py # Prospect data model
+│ ├── campaign.py # Campaign + email sequence models
+│ └── conversation.py # Conversation thread model
+│
+├── prompts/ # Prompt templates (editable)
+│ ├── system.md # Harvey's core persona
+│ ├── scout.md # Prospecting instructions
+│ ├── writer.md # Email writing guidelines
+│ ├── handler.md # Reply handling rules
+│ └── qualifier.md # Lead qualification criteria
+│
+├── skills/ # Foundational sales knowledge (editable)
+│ ├── email_frameworks.md
+│ ├── objection_handling.md
+│ ├── lead_qualification.md
+│ ├── linkedin_outreach.md
+│ ├── prospecting_tactics.md
+│ └── sales_methodology.md
+│
+└── data/ # Runtime data (auto-created)
+ └── harvey.db # SQLite database
+```
+
+---
+
+## Customization
+
+### Change How Harvey Writes
+
+Edit `prompts/writer.md` to adjust email style, length, tone, or CTA approach. Edit `skills/email_frameworks.md` to change which copywriting frameworks Harvey uses.
+
+### Change How Harvey Handles Objections
+
+Edit `skills/objection_handling.md` to add industry-specific objection responses. Or add them directly in `harvey.yaml` under `product.objection_responses`.
+
+### Change How Harvey Prospects
+
+Edit `skills/prospecting_tactics.md` to adjust search strategies. Edit `skills/lead_qualification.md` to change scoring criteria.
+
+### Add a New Channel
+
+Create a new integration in `harvey/integrations/` and a corresponding agent in `harvey/agents/`. Wire it into the heartbeat loop in `main.py`.
+
+---
+
+## How Harvey Decides What To Do
+
+Every heartbeat cycle, Harvey checks the pipeline state and picks the highest-priority action:
+
+| Priority | Action | Trigger |
+|----------|--------|---------|
+| 1 | **Handle replies** | Open conversations with new messages |
+| 2 | **Send campaigns** | Draft campaigns ready to deploy |
+| 3 | **Write campaigns** | New prospects without campaigns |
+| 4 | **Prospect** | Fewer than 20 prospects with status "new" |
+| 5 | **Idle** | Everything is running, nothing needs attention |
+
+Hot leads cool fast — that's why reply handling is always #1.
+
+---
+
+## Database
+
+Harvey stores everything in SQLite (`data/harvey.db`):
+
+| Table | What It Stores |
+|-------|---------------|
+| `prospects` | Everyone Harvey has found — name, email, company, title, status, score, personalization notes |
+| `campaigns` | Email sequences — the emails, which prospects are in each campaign, deployment status |
+| `conversations` | Full conversation threads — every message sent and received, classified intent |
+| `actions` | Audit log — everything Harvey has done, when, and the result |
+| `usage_log` | Daily Claude usage tracking for budget control |
+
+---
+
+## Roadmap
+
+- [x] Core heartbeat loop
+- [x] DIY prospecting (LinkedIn + Google + email discovery)
+- [x] Email sequence generation with copywriting frameworks
+- [x] Instantly integration for campaign deployment
+- [x] Reply handling with intent classification
+- [x] Skills system for foundational sales knowledge
+- [x] Usage tracking and daily limits
+- [x] Docker deployment
+- [ ] LinkedIn DM outreach
+- [ ] Calendar integration (Cal.com / Calendly) for auto-booking
+- [ ] AI voice cold calling (Bland.ai / Vapi)
+- [ ] SMS/text outreach
+- [ ] Analyst agent — learn from outcomes, A/B test messaging
+- [ ] Web dashboard — see pipeline, review Harvey's work, override decisions
+- [ ] Multi-product support — run Harvey for multiple products simultaneously
+- [ ] Team mode — multiple Harveys coordinating across territories
+- [ ] Webhook receiver for real-time reply processing
+
+---
+
+## Philosophy
+
+Harvey is built on a few core beliefs:
+
+**1. Autonomous doesn't mean reckless.** Harvey has quiet hours, usage limits, rate limiting, and ethical guidelines baked in. It respects opt-outs immediately, never spams, and stops when told to.
+
+**2. Expensive tools are optional.** Most sales teams pay $500+/month for prospecting tools, email platforms, and enrichment services. Harvey does prospecting for free, uses your existing email tool, and runs on your existing Claude subscription.
+
+**3. Quality beats quantity.** Harvey doesn't blast 10,000 emails. It finds the right people, writes genuinely personalized outreach, and focuses on starting real conversations.
+
+**4. The best sales agent sounds like a person, not a bot.** Harvey's writing is consultative, direct, and human. No jargon, no "I hope this finds you well," no walls of text.
+
+**5. Everything is editable.** Prompts, skills, config — it's all plain text files. You don't need to be a developer to change how Harvey sells.
+
+---
+
+## License
+
+MIT
+
+---
+
+*"Put that coffee down. Coffee is for closers."* — Blake, Glengarry Glen Ross
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..9840099
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,18 @@
+services:
+ harvey:
+ build: .
+ env_file: .env
+ volumes:
+ # Persist database across restarts
+ - ./data:/app/data
+ # Mount config for easy editing without rebuild
+ - ./harvey.yaml:/app/harvey.yaml:ro
+ - ./prompts:/app/prompts:ro
+ # Mount Claude auth (required for Max plan usage)
+ - ~/.claude:/root/.claude:ro
+ restart: unless-stopped
+ logging:
+ driver: "json-file"
+ options:
+ max-size: "10m"
+ max-file: "3"
diff --git a/harvey.yaml b/harvey.yaml
new file mode 100644
index 0000000..dc49838
--- /dev/null
+++ b/harvey.yaml
@@ -0,0 +1,51 @@
+persona:
+ name: "Harvey"
+ company: "Your Company"
+ role: "Business Development"
+ linkedin: "linkedin.com/in/harvey-yourcompany"
+ tone: "professional, consultative, confident"
+
+product:
+ name: "Your Product"
+ description: "Describe what your product does and who it's for"
+ pricing: "Starting at $X/mo"
+ key_benefits:
+ - "Benefit 1"
+ - "Benefit 2"
+ - "Benefit 3"
+ objection_responses:
+ "too expensive": "I understand budget is important. Most of our clients see ROI within 30 days..."
+ "already have a solution": "That makes sense. Curious — what's the one thing you wish it did better?"
+ "not interested": "No worries at all. Mind if I ask what your current approach looks like?"
+
+icp:
+ industries:
+ - "SaaS"
+ - "Marketing Agency"
+ company_size: "10-200 employees"
+ titles:
+ - "VP Marketing"
+ - "Head of Growth"
+ - "CMO"
+ - "Director of Marketing"
+ geography:
+ - "United States"
+
+channels:
+ email:
+ enabled: true
+ provider: "instantly"
+ max_daily_sends: 50
+ linkedin:
+ enabled: true
+ max_daily_connections: 20
+ max_daily_messages: 10
+
+usage:
+ max_daily_claude_percent: 80
+ heartbeat_interval_minutes: 15
+ quiet_hours:
+ start: "22:00"
+ end: "07:00"
+ timezone: "America/New_York"
diff --git a/harvey/__init__.py b/harvey/__init__.py
new file mode 100644
index 0000000..fa191e9
--- /dev/null
+++ b/harvey/__init__.py
@@ -0,0 +1 @@
+"""Harvey — Autonomous Sales Agent. Always Be Closing."""
diff --git a/harvey/__main__.py b/harvey/__main__.py
new file mode 100644
index 0000000..8019895
--- /dev/null
+++ b/harvey/__main__.py
@@ -0,0 +1,5 @@
+"""Allow running Harvey with `python -m harvey`."""
+
+from harvey.main import main
+
+main()
diff --git a/harvey/agents/__init__.py b/harvey/agents/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/harvey/agents/analyst.py b/harvey/agents/analyst.py
new file mode 100644
index 0000000..ae0f6d2
--- /dev/null
+++ b/harvey/agents/analyst.py
@@ -0,0 +1,20 @@
+"""Analyst — learns from outcomes. Placeholder for future implementation."""
+
+import logging
+
+logger = logging.getLogger("harvey.analyst")
+
+
+class Analyst:
+ """Placeholder for the learning/analytics sub-agent.
+
+ Future capabilities:
+ - Track outreach → reply → meeting → close rates
+ - A/B test subject lines and email bodies
+ - Identify which ICP segments convert best
+ - Adjust messaging and targeting based on data
+ - Report on campaign performance
+ """
+
+ async def run(self):
+ logger.info("Analyst: Not yet implemented. Coming soon.")
diff --git a/harvey/agents/handler.py b/harvey/agents/handler.py
new file mode 100644
index 0000000..5f948ae
--- /dev/null
+++ b/harvey/agents/handler.py
@@ -0,0 +1,274 @@
+"""Handler — monitors replies and manages conversations."""
+
+import logging
+from datetime import datetime
+
+from harvey.brain import Brain
+from harvey.config import HarveyConfig, EnvConfig
+from harvey.integrations.instantly import InstantlyClient
+from harvey.models.conversation import Conversation, Message
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.handler")
+
+INTENT_LABELS = {
+ "interested",
+ "objection",
+ "not_interested",
+ "ooo",
+ "wrong_person",
+ "question",
+}
+
+
+class Handler:
+ def __init__(
+ self,
+ brain: Brain,
+ state: StateManager,
+ config: HarveyConfig,
+ env: EnvConfig,
+ ):
+ self.brain = brain
+ self.state = state
+ self.config = config
+ self.instantly = InstantlyClient(env.instantly_api_key)
+
+ async def run(self):
+ """Check for new replies and handle them."""
+ logger.info("Handler: Checking for replies...")
+
+ # Load foundational skills for this agent
+ self.skills = self.brain.load_skills_for_agent("handler")
+
+ if not self.config.channels.email.enabled:
+ return
+
+ # 1. Fetch active campaigns
+ active_campaigns = await self.state.get_campaigns_by_status("active")
+ if not active_campaigns:
+ logger.info("Handler: No active campaigns to monitor.")
+ return
+
+ total_handled = 0
+
+ for campaign in active_campaigns:
+ if not campaign.instantly_campaign_id:
+ continue
+
+ # 2. Get replies from Instantly
+ replies = await self.instantly.get_replies(campaign.instantly_campaign_id)
+ if not replies:
+ continue
+
+ for reply in replies:
+ try:
+ await self._handle_reply(reply, campaign)
+ total_handled += 1
+ except Exception as e:
+ logger.error(f"Handler: Error processing reply: {e}")
+
+ # Also check open conversations that need follow-up
+ open_convos = await self.state.get_conversations_by_status("open")
+ for convo in open_convos:
+ if convo.intent == "interested":
+ # Check if we need to follow up
+ pass # TODO: follow-up logic
+
+ if total_handled:
+ logger.info(f"Handler: Processed {total_handled} replies.")
+ else:
+ logger.info("Handler: No new replies.")
+
+ async def _handle_reply(self, reply: dict, campaign):
+ """Process a single reply."""
+ lead_email = reply.get("lead_email", reply.get("from_email", ""))
+ reply_text = reply.get("body", reply.get("text", ""))
+ reply_uuid = reply.get("uuid", reply.get("id", ""))
+
+ if not lead_email or not reply_text:
+ return
+
+ logger.info(f"Handler: Reply from {lead_email}")
+
+ # Find the prospect
+ # (Lookup by email in our DB)
+ prospects = await self.state.get_prospects_by_status("contacted")
+ prospect = next((p for p in prospects if p.email == lead_email), None)
+
+ if not prospect:
+ # Also check "replied" status
+ prospects = await self.state.get_prospects_by_status("replied")
+ prospect = next((p for p in prospects if p.email == lead_email), None)
+
+ if not prospect:
+ logger.warning(f"Handler: No prospect found for {lead_email}")
+ return
+
+ # Update prospect status
+ await self.state.update_prospect_status(prospect.id, "replied")
+
+ # 1. Classify intent
+ intent = await self._classify_intent(reply_text, prospect)
+ logger.info(f"Handler: Intent for {lead_email}: {intent}")
+
+ # 2. Get or create conversation
+ existing_convos = await self.state.get_conversations_by_status("open")
+ convo = next(
+ (c for c in existing_convos if c.prospect_id == prospect.id), None
+ )
+
+ if not convo:
+ convo = Conversation(
+ id="",
+ prospect_id=prospect.id,
+ campaign_id=campaign.id,
+ channel="email",
+ thread=[
+ Message(sender="prospect", content=reply_text),
+ ],
+ intent=intent,
+ status="open",
+ )
+ await self.state.add_conversation(convo)
+ else:
+ convo.thread.append(Message(sender="prospect", content=reply_text))
+ convo.intent = intent
+ await self.state.update_conversation(
+ convo.id,
+ thread_json=convo.thread_json(),
+ intent=intent,
+ )
+
+ # 3. Generate and send response based on intent
+ if intent == "not_interested":
+ # Graceful exit — no response needed, mark as closed
+ await self.state.update_conversation(convo.id, status="closed")
+ await self.state.update_prospect_status(prospect.id, "lost")
+ logger.info(f"Handler: {lead_email} not interested. Closing.")
+ return
+
+ if intent == "ooo":
+ # Don't respond, let the sequence continue later
+ logger.info(f"Handler: {lead_email} is OOO. Will follow up later.")
+ return
+
+ # For interested, objection, question, wrong_person — generate a reply
+ response = await self._generate_response(intent, reply_text, prospect, convo)
+ if not response:
+ logger.warning(f"Handler: Could not generate response for {lead_email}")
+ return
+
+ # Send via Instantly
+ if reply_uuid:
+ result = await self.instantly.send_reply(reply_uuid, response)
+ if result is not None:
+ # Add our response to conversation
+ convo.thread.append(Message(sender="harvey", content=response))
+ await self.state.update_conversation(
+ convo.id,
+ thread_json=convo.thread_json(),
+ )
+ logger.info(f"Handler: Replied to {lead_email}")
+
+ await self.state.log_action(
+ action_type="reply",
+ agent="handler",
+ details={
+ "prospect_email": lead_email,
+ "intent": intent,
+ "response_preview": response[:100],
+ },
+ )
+
+ async def _classify_intent(self, reply_text: str, prospect) -> str:
+ """Ask the brain to classify the reply's intent."""
+ prompt = f"""Classify this email reply into exactly ONE category:
+- "interested" — wants to learn more, open to a meeting, positive response
+- "objection" — has concerns but hasn't said no (price, timing, competition)
+- "not_interested" — clearly says no, unsubscribe, do not contact
+- "ooo" — out of office / auto-reply
+- "wrong_person" — not the right contact, suggests someone else
+- "question" — asking for more information before deciding
+
+Reply from {prospect.full_name()} ({prospect.title} at {prospect.company}):
+\"\"\"{reply_text}\"\"\"
+
+Respond with ONLY the category label, nothing else."""
+
+ result = await self.brain.think(prompt, session_id="harvey-handler")
+ intent = result.strip().strip('"').lower()
+
+ if intent not in INTENT_LABELS:
+ logger.warning(f"Unknown intent: {intent}. Defaulting to 'question'.")
+ return "question"
+
+ return intent
+
+ async def _generate_response(
+ self, intent: str, reply_text: str, prospect, convo: Conversation
+ ) -> str:
+ """Generate an appropriate response based on intent."""
+ # Build conversation history for context
+ history = "\n".join(
+ f"{'Harvey' if m.sender == 'harvey' else prospect.full_name()}: {m.content}"
+ for m in convo.thread[-6:] # Last 6 messages for context
+ )
+
+ objection_context = ""
+ if intent == "objection":
+ # Check if we have a pre-configured response
+ for trigger, response in self.config.product.objection_responses.items():
+ if trigger.lower() in reply_text.lower():
+ objection_context = f"\nSuggested approach for this objection: {response}"
+ break
+
+ prompt = self.brain.load_prompt("handler")
+ if not prompt:
+ prompt = f"""You are {self.config.persona.name}, {self.config.persona.role} at {self.config.persona.company}.
+Your tone is: {self.config.persona.tone}
+Product: {self.config.product.name} — {self.config.product.description}"""
+
+ # Inject objection handling + sales methodology skills
+ if self.skills:
+ prompt += "\n\n" + self.skills
+
+ prompt += f"""
+
+Conversation so far:
+{history}
+
+The prospect's intent is: {intent}
+{objection_context}
+
+Write a reply that:"""
+
+ if intent == "interested":
+ prompt += """
+- Acknowledges their interest warmly
+- Suggests a specific next step (brief call or meeting)
+- Keeps it short (under 80 words)
+- Includes a clear CTA with flexibility on timing"""
+ elif intent == "objection":
+ prompt += """
+- Addresses the concern directly and empathetically
+- Provides evidence or a reframe
+- Doesn't argue — redirect toward value
+- Keeps it under 100 words"""
+ elif intent == "question":
+ prompt += """
+- Answers their question clearly and concisely
+- Ties the answer back to value for them
+- Ends with a soft CTA
+- Under 100 words"""
+ elif intent == "wrong_person":
+ prompt += """
+- Thanks them politely
+- Asks who the right person would be
+- Makes it easy for them to refer (one-line ask)
+- Under 50 words"""
+
+ prompt += "\n\nWrite ONLY the email body. No subject line, no greeting label."
+
+ response = await self.brain.think(prompt, session_id="harvey-handler")
+ return response.strip() if response else ""
diff --git a/harvey/agents/scout.py b/harvey/agents/scout.py
new file mode 100644
index 0000000..8d37fda
--- /dev/null
+++ b/harvey/agents/scout.py
@@ -0,0 +1,362 @@
+"""Scout — DIY prospecting without expensive tools."""
+
+import logging
+import re
+from urllib.parse import quote_plus
+
+import httpx
+from bs4 import BeautifulSoup
+
+from harvey.brain import Brain
+from harvey.config import HarveyConfig, EnvConfig
+from harvey.integrations.email_finder import find_email
+from harvey.integrations.linkedin import LinkedInAutomation
+from harvey.models.prospect import Prospect
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.scout")
+
+
+class Scout:
+ def __init__(
+ self,
+ brain: Brain,
+ state: StateManager,
+ config: HarveyConfig,
+ env: EnvConfig,
+ ):
+ self.brain = brain
+ self.state = state
+ self.config = config
+ self.env = env
+
+ async def run(self):
+ """Main prospecting flow: find leads matching ICP."""
+ logger.info("Scout: Starting prospecting cycle...")
+
+ # Load foundational skills for this agent
+ self.skills = self.brain.load_skills_for_agent("scout")
+
+ prospects_found = 0
+
+ # Strategy 1: LinkedIn search (if enabled)
+ if self.config.channels.linkedin.enabled and self.env.linkedin_email:
+ prospects_found += await self._prospect_via_linkedin()
+
+ # Strategy 2: Google dorking for LinkedIn profiles
+ prospects_found += await self._prospect_via_google()
+
+ # Strategy 3: Company website scraping for team pages
+ prospects_found += await self._prospect_via_company_sites()
+
+ await self.state.log_action(
+ action_type="prospect",
+ agent="scout",
+ details={"prospects_found": prospects_found},
+ )
+ logger.info(f"Scout: Found {prospects_found} new prospects this cycle.")
+
+ async def _prospect_via_linkedin(self) -> int:
+ """Search LinkedIn for ICP-matching profiles."""
+ logger.info("Scout: Searching LinkedIn...")
+ linkedin = LinkedInAutomation(
+ self.env.linkedin_email, self.env.linkedin_password
+ )
+
+ try:
+ await linkedin.start()
+ if not await linkedin.login():
+ logger.warning("Scout: LinkedIn login failed. Skipping.")
+ return 0
+
+ count = 0
+ for title in self.config.icp.titles:
+ for industry in self.config.icp.industries:
+ keywords = f"{title} {industry}"
+ profiles = await linkedin.search_people(
+ keywords=keywords,
+ max_results=10,
+ )
+
+ for profile in profiles:
+ # Check if we already have this prospect
+ if await self.state.prospect_exists(
+ linkedin_url=profile.get("linkedin_url", "")
+ ):
+ continue
+
+ # Try to find their email
+ email = ""
+ company = profile.get("company", "")
+ if company:
+ domain = await self._guess_domain(company)
+ if domain:
+ email = await find_email(
+ profile.get("first_name", ""),
+ profile.get("last_name", ""),
+ domain,
+ ) or ""
+
+ prospect = Prospect(
+ id="",
+ first_name=profile.get("first_name", ""),
+ last_name=profile.get("last_name", ""),
+ email=email,
+ linkedin_url=profile.get("linkedin_url", ""),
+ company=company,
+ title=profile.get("title", ""),
+ industry=industry,
+ source="linkedin_search",
+ )
+
+ # Ask brain for personalization notes
+ if email or profile.get("linkedin_url"):
+ notes = await self._get_personalization(prospect)
+ prospect.personalization_notes = notes
+
+ await self.state.add_prospect(prospect)
+ count += 1
+ logger.info(
+ f"Scout: Added prospect {prospect.full_name()} "
+ f"at {company}"
+ )
+
+ return count
+
+ finally:
+ await linkedin.stop()
+
+ async def _prospect_via_google(self) -> int:
+ """Use Google dorking to find LinkedIn profiles matching ICP."""
+ logger.info("Scout: Google dorking for prospects...")
+ count = 0
+
+ for title in self.config.icp.titles:
+ for geo in self.config.icp.geography:
+ query = (
+ f'site:linkedin.com/in "{title}" '
+ f'"{self.config.icp.industries[0]}" "{geo}"'
+ )
+ profiles = await self._google_search(query)
+
+ for url, snippet in profiles:
+ if "/in/" not in url:
+ continue
+ if await self.state.prospect_exists(linkedin_url=url):
+ continue
+
+ # Parse name from URL or snippet
+ parsed = self._parse_linkedin_url(url, snippet)
+ if not parsed:
+ continue
+
+ prospect = Prospect(
+ id="",
+ first_name=parsed.get("first_name", ""),
+ last_name=parsed.get("last_name", ""),
+ linkedin_url=url,
+ title=title,
+ source="google_dork",
+ )
+ await self.state.add_prospect(prospect)
+ count += 1
+
+ if count >= 20:
+ break
+ if count >= 20:
+ break
+
+ return count
+
+ async def _prospect_via_company_sites(self) -> int:
+ """Scrape company team/about pages for prospects."""
+ logger.info("Scout: Checking company websites...")
+
+ # Ask brain to find target companies
+ prompt = self.brain.load_prompt(
+ "scout",
+ industries=", ".join(self.config.icp.industries),
+ company_size=self.config.icp.company_size,
+ geography=", ".join(self.config.icp.geography),
+ titles=", ".join(self.config.icp.titles),
+ )
+
+ if not prompt:
+ prompt = f"""Find 10 companies that match this ICP:
+- Industries: {', '.join(self.config.icp.industries)}
+- Company size: {self.config.icp.company_size}
+- Geography: {', '.join(self.config.icp.geography)}
+
+Return a JSON array of objects with "name" and "domain" fields.
+Example: [{{"name": "Acme Inc", "domain": "acme.com"}}]"""
+
+ # Inject skills knowledge
+ if self.skills:
+ prompt = self.skills + "\n\n---\n\n" + prompt
+
+ result = await self.brain.think_json(prompt, session_id="harvey-scout")
+ if not result or not isinstance(result, list):
+ return 0
+
+ count = 0
+ for company_info in result[:10]:
+ domain = company_info.get("domain", "")
+ company_name = company_info.get("name", "")
+ if not domain:
+ continue
+
+ # Try to find team page
+ team_members = await self._scrape_team_page(domain)
+ for member in team_members:
+ title = member.get("title", "")
+ if not any(
+ t.lower() in title.lower() for t in self.config.icp.titles
+ ):
+ continue
+
+ email = await find_email(
+ member.get("first_name", ""),
+ member.get("last_name", ""),
+ domain,
+ ) or ""
+
+ if await self.state.prospect_exists(email=email):
+ continue
+
+ prospect = Prospect(
+ id="",
+ first_name=member.get("first_name", ""),
+ last_name=member.get("last_name", ""),
+ email=email,
+ company=company_name,
+ title=title,
+ industry=self.config.icp.industries[0],
+ source="company_website",
+ )
+ await self.state.add_prospect(prospect)
+ count += 1
+
+ return count
+
+ async def _google_search(self, query: str) -> list[tuple[str, str]]:
+ """Perform a Google search and return (url, snippet) pairs."""
+ encoded = quote_plus(query)
+ url = f"https://www.google.com/search?q={encoded}&num=20"
+
+ try:
+ async with httpx.AsyncClient() as client:
+ resp = await client.get(
+ url,
+ headers={
+ "User-Agent": (
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
+ "AppleWebKit/537.36"
+ )
+ },
+ follow_redirects=True,
+ timeout=15,
+ )
+
+ if resp.status_code != 200:
+ return []
+
+ soup = BeautifulSoup(resp.text, "html.parser")
+ results = []
+ for div in soup.select("div.g"):
+ link = div.select_one("a")
+ snippet_el = div.select_one("div.VwiC3b")
+ if link and link.get("href"):
+ href = link["href"]
+ snippet = snippet_el.get_text() if snippet_el else ""
+ results.append((href, snippet))
+
+ return results[:20]
+
+ except Exception as e:
+ logger.debug(f"Google search failed: {e}")
+ return []
+
+ async def _scrape_team_page(self, domain: str) -> list[dict]:
+ """Try to find and scrape a company's team/about page."""
+ team_paths = ["/team", "/about", "/about-us", "/our-team", "/people"]
+ members = []
+
+ async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:
+ for path in team_paths:
+ try:
+ url = f"https://{domain}{path}"
+ resp = await client.get(
+ url,
+ headers={"User-Agent": "Mozilla/5.0"},
+ )
+ if resp.status_code != 200:
+ continue
+
+ soup = BeautifulSoup(resp.text, "html.parser")
+
+ # Look for common team member patterns
+ # Many sites use cards with name + title
+ for card in soup.select(
+ ".team-member, .person, .staff, [class*='team']"
+ ):
+ name_el = card.select_one(
+ "h2, h3, h4, .name, [class*='name']"
+ )
+ title_el = card.select_one(
+ "p, .title, .role, [class*='title'], [class*='role']"
+ )
+ if name_el:
+ name = name_el.get_text().strip()
+ title = title_el.get_text().strip() if title_el else ""
+ parts = name.split(" ", 1)
+ members.append({
+ "first_name": parts[0],
+ "last_name": parts[1] if len(parts) > 1 else "",
+ "title": title,
+ })
+
+ if members:
+ break
+
+ except Exception:
+ continue
+
+ return members
+
+ async def _guess_domain(self, company_name: str) -> str:
+ """Guess a company's domain from its name."""
+ # Simple heuristic: lowercase, remove common suffixes, add .com
+ name = company_name.lower().strip()
+ for suffix in [" inc", " llc", " ltd", " corp", " co", " group"]:
+ name = name.replace(suffix, "")
+ name = re.sub(r"[^a-z0-9]", "", name)
+ domain = f"{name}.com"
+
+ # Verify the domain exists
+ try:
+ async with httpx.AsyncClient(timeout=5) as client:
+ resp = await client.head(
+ f"https://{domain}", follow_redirects=True
+ )
+ if resp.status_code < 400:
+ return domain
+ except Exception:
+ pass
+
+ return ""
+
+ async def _get_personalization(self, prospect: Prospect) -> str:
+ """Ask brain for personalization angles based on prospect info."""
+ prompt = f"""Based on this prospect, suggest 2-3 short personalization angles
+for cold outreach. Keep each to one sentence.
+
+Name: {prospect.full_name()}
+Title: {prospect.title}
+Company: {prospect.company}
+Industry: {prospect.industry}
+
+Our product: {self.config.product.description}
+
+Return just the personalization notes, no labels or bullets."""
+
+ return await self.brain.think(prompt, session_id="harvey-scout") or ""
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
new file mode 100644
index 0000000..539888e
--- /dev/null
+++ b/harvey/agents/sender.py
@@ -0,0 +1,136 @@
+"""Sender — deploys campaigns via Instantly."""
+
+import json
+import logging
+
+from harvey.brain import Brain
+from harvey.config import HarveyConfig, EnvConfig
+from harvey.integrations.instantly import InstantlyClient
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.sender")
+
+
+class Sender:
+ def __init__(
+ self,
+ brain: Brain,
+ state: StateManager,
+ config: HarveyConfig,
+ env: EnvConfig,
+ ):
+ self.brain = brain
+ self.state = state
+ self.config = config
+ self.instantly = InstantlyClient(env.instantly_api_key)
+
+ async def run(self):
+ """Deploy draft campaigns to Instantly."""
+ logger.info("Sender: Checking for campaigns to deploy...")
+
+ if not self.config.channels.email.enabled:
+ logger.info("Sender: Email channel disabled. Skipping.")
+ return
+
+ draft_campaigns = await self.state.get_campaigns_by_status("draft")
+ if not draft_campaigns:
+ logger.info("Sender: No draft campaigns to deploy.")
+ return
+
+ for campaign in draft_campaigns:
+ try:
+ await self._deploy_campaign(campaign)
+ except Exception as e:
+ logger.error(f"Sender: Failed to deploy campaign {campaign.name}: {e}")
+
+ async def _deploy_campaign(self, campaign):
+ """Deploy a single campaign to Instantly."""
+ logger.info(f"Sender: Deploying campaign '{campaign.name}'...")
+
+ # 1. Create campaign in Instantly
+ instantly_campaign = await self.instantly.create_campaign(campaign.name)
+ if not instantly_campaign:
+ logger.error(f"Sender: Failed to create Instantly campaign: {campaign.name}")
+ return
+
+ campaign_id = instantly_campaign.get("id")
+ if not campaign_id:
+ logger.error("Sender: No campaign ID returned from Instantly.")
+ return
+
+ # 2. Set email sequence
+ sequences = [
+ {
+ "subject": step.subject,
+ "body": step.body,
+ "wait": step.delay_days,
+ }
+ for step in campaign.sequence
+ ]
+
+ result = await self.instantly.set_campaign_emails(campaign_id, sequences)
+ if result is None:
+ logger.error(f"Sender: Failed to set emails for campaign {campaign_id}")
+ return
+
+ # 3. Add leads
+ prospects = []
+ for prospect_id in campaign.prospect_ids:
+ prospect = await self.state.get_prospect(prospect_id)
+ if prospect and prospect.email:
+ prospects.append(prospect)
+
+ if not prospects:
+ logger.warning(f"Sender: No valid prospects for campaign {campaign.name}")
+ return
+
+ leads = [
+ {
+ "email": p.email,
+ "first_name": p.first_name,
+ "last_name": p.last_name,
+ "company_name": p.company,
+ "variables": {
+ "title": p.title,
+ "personalization": p.personalization_notes,
+ },
+ }
+ for p in prospects
+ ]
+
+ result = await self.instantly.add_leads(campaign_id, leads)
+ if result is None:
+ logger.error(f"Sender: Failed to add leads to campaign {campaign_id}")
+ return
+
+ # 4. Activate campaign
+ result = await self.instantly.activate_campaign(campaign_id)
+ if result is None:
+ logger.error(f"Sender: Failed to activate campaign {campaign_id}")
+ return
+
+ # 5. Update our records
+ await self.state.update_campaign(
+ campaign.id,
+ instantly_campaign_id=campaign_id,
+ status="active",
+ )
+
+ # Update prospect statuses
+ for prospect in prospects:
+ await self.state.update_prospect_status(prospect.id, "contacted")
+
+ await self.state.log_action(
+ action_type="send_campaign",
+ agent="sender",
+ details={
+ "campaign_name": campaign.name,
+ "instantly_campaign_id": campaign_id,
+ "leads_added": len(leads),
+ },
+ )
+
+ logger.info(
+ f"Sender: Campaign '{campaign.name}' deployed to Instantly "
+ f"with {len(leads)} leads. Campaign ID: {campaign_id}"
+ )
diff --git a/harvey/agents/writer.py b/harvey/agents/writer.py
new file mode 100644
index 0000000..e3ee769
--- /dev/null
+++ b/harvey/agents/writer.py
@@ -0,0 +1,168 @@
+"""Writer — crafts personalized email sequences."""
+
+import json
+import logging
+
+from harvey.brain import Brain
+from harvey.config import HarveyConfig
+from harvey.models.campaign import Campaign, EmailStep
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.writer")
+
+
+class Writer:
+ def __init__(self, brain: Brain, state: StateManager, config: HarveyConfig):
+ self.brain = brain
+ self.state = state
+ self.config = config
+
+ async def run(self):
+ """Create email campaigns for prospects that need outreach."""
+ logger.info("Writer: Crafting email campaigns...")
+
+ # Load foundational skills for this agent
+ self.skills = self.brain.load_skills_for_agent("writer")
+
+ # Get prospects that haven't been contacted yet
+ new_prospects = await self.state.get_prospects_by_status("new")
+ if not new_prospects:
+ logger.info("Writer: No new prospects to write for.")
+ return
+
+ # Filter to only those with emails
+ prospects_with_email = [p for p in new_prospects if p.email]
+ if not prospects_with_email:
+ logger.info("Writer: No prospects with verified emails.")
+ return
+
+ # Batch prospects into campaign groups (by industry/title for relevance)
+ batches = self._group_prospects(prospects_with_email)
+
+ for batch_name, prospects in batches.items():
+ if not prospects:
+ continue
+
+ logger.info(
+ f"Writer: Creating campaign '{batch_name}' for "
+ f"{len(prospects)} prospects."
+ )
+
+ # Generate the email sequence
+ sequence = await self._write_sequence(prospects)
+ if not sequence:
+ logger.warning(f"Writer: Failed to generate sequence for {batch_name}")
+ continue
+
+ # Create the campaign
+ campaign = Campaign(
+ id="",
+ name=batch_name,
+ channel="email",
+ sequence=sequence,
+ prospect_ids=[p.id for p in prospects],
+ status="draft",
+ )
+ campaign_id = await self.state.add_campaign(campaign)
+
+ await self.state.log_action(
+ action_type="write_campaign",
+ agent="writer",
+ details={
+ "campaign_id": campaign_id,
+ "campaign_name": batch_name,
+ "prospect_count": len(prospects),
+ "steps": len(sequence),
+ },
+ )
+ logger.info(
+ f"Writer: Campaign '{batch_name}' created with "
+ f"{len(sequence)} emails for {len(prospects)} prospects."
+ )
+
+ async def _write_sequence(self, prospects: list) -> list[EmailStep]:
+ """Ask the brain to write a 3-email sequence."""
+ # Build context about the prospects
+ prospect_summary = "\n".join(
+ f"- {p.full_name()}, {p.title} at {p.company}"
+ + (f" | Notes: {p.personalization_notes}" if p.personalization_notes else "")
+ for p in prospects[:5] # Show sample for context
+ )
+
+ prompt = self.brain.load_prompt(
+ "writer",
+ product_name=self.config.product.name,
+ product_description=self.config.product.description,
+ product_benefits="\n".join(f"- {b}" for b in self.config.product.key_benefits),
+ product_pricing=self.config.product.pricing,
+ persona_name=self.config.persona.name,
+ persona_company=self.config.persona.company,
+ persona_role=self.config.persona.role,
+ persona_tone=self.config.persona.tone,
+ )
+
+ if not prompt:
+ prompt = f"""You are {self.config.persona.name}, {self.config.persona.role} at {self.config.persona.company}.
+Your tone is: {self.config.persona.tone}
+
+Product: {self.config.product.name}
+Description: {self.config.product.description}
+Key benefits: {', '.join(self.config.product.key_benefits)}
+Pricing: {self.config.product.pricing}"""
+
+ # Inject email framework skills
+ if self.skills:
+ prompt += "\n\n" + self.skills
+
+ prompt += f"""
+
+Write a 3-email cold outreach sequence for prospects like these:
+{prospect_summary}
+
+Requirements:
+- Email 1: Personalized cold intro. Short (under 100 words). One clear CTA.
+- Email 2: Follow-up 3 days later. Different angle, add social proof or insight.
+- Email 3: Break-up email 4 days after that. Create gentle urgency, last chance.
+- Use {{{{first_name}}}}, {{{{company}}}}, {{{{title}}}} as merge variables.
+- Never be pushy or salesy. Be consultative and value-driven.
+- Subject lines should be short, curiosity-driven, lowercase.
+
+Return as JSON array:
+[
+ {{"step": 1, "subject": "...", "body": "...", "delay_days": 0}},
+ {{"step": 2, "subject": "...", "body": "...", "delay_days": 3}},
+ {{"step": 3, "subject": "...", "body": "...", "delay_days": 4}}
+]"""
+
+ result = await self.brain.think_json(prompt, session_id="harvey-writer")
+ if not result or not isinstance(result, list):
+ return []
+
+ try:
+ return [EmailStep(**step) for step in result]
+ except Exception as e:
+ logger.error(f"Writer: Failed to parse sequence: {e}")
+ return []
+
+ def _group_prospects(self, prospects: list) -> dict[str, list]:
+ """Group prospects into campaign batches by industry/title combo."""
+ batches: dict[str, list] = {}
+
+ for prospect in prospects:
+ # Group by industry + rough title category
+ industry = prospect.industry or "general"
+ key = f"{industry}-outreach"
+
+ if key not in batches:
+ batches[key] = []
+ batches[key].append(prospect)
+
+ # Cap each batch at 50 prospects (Instantly best practice)
+ capped = {}
+ for key, group in batches.items():
+ if len(group) > 50:
+ capped[key] = group[:50]
+ else:
+ capped[key] = group
+
+ return capped
diff --git a/harvey/brain.py b/harvey/brain.py
new file mode 100644
index 0000000..c6e5967
--- /dev/null
+++ b/harvey/brain.py
@@ -0,0 +1,153 @@
+"""Brain — wraps Claude Code headless mode. Harvey's thinking engine."""
+
+import asyncio
+import json
+import logging
+import re
+from pathlib import Path
+
+from harvey.state import StateManager
+
+logger = logging.getLogger("harvey.brain")
+
+PROMPTS_DIR = Path(__file__).parent.parent / "prompts"
+SKILLS_DIR = Path(__file__).parent.parent / "skills"
+
+
+class Brain:
+ def __init__(self, state: StateManager):
+ self.state = state
+
+ async def think(
+ self,
+ prompt: str,
+ session_id: str | None = None,
+ expect_json: bool = False,
+ ) -> str:
+ """Send a prompt to Claude Code headless mode and return the response."""
+ cmd = ["claude", "-p", prompt, "--output-format", "text"]
+ if session_id:
+ cmd.extend(["--session-id", session_id])
+
+ logger.debug(f"Brain call (session={session_id}): {prompt[:100]}...")
+
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate()
+
+ if process.returncode != 0:
+ error = stderr.decode().strip()
+ logger.error(f"Claude returned error: {error}")
+ return ""
+
+ response = stdout.decode().strip()
+ await self.state.increment_usage()
+ logger.debug(f"Brain response: {response[:200]}...")
+ return response
+
+ except FileNotFoundError:
+ logger.error(
+ "Claude CLI not found. Install it: https://claude.com/download"
+ )
+ return ""
+ except Exception as e:
+ logger.error(f"Brain error: {e}")
+ return ""
+
+ async def think_json(
+ self, prompt: str, session_id: str | None = None
+ ) -> dict | list | None:
+ """Send a prompt and parse the response as JSON."""
+ full_prompt = (
+ prompt
+ + "\n\nRespond ONLY with valid JSON. No markdown, no explanation."
+ )
+ response = await self.think(full_prompt, session_id=session_id)
+ if not response:
+ return None
+ # Strip markdown code fences if present
+ response = re.sub(r"^```(?:json)?\s*", "", response)
+ response = re.sub(r"\s*```$", "", response)
+ try:
+ return json.loads(response)
+ except json.JSONDecodeError:
+ logger.error(f"Failed to parse JSON from brain: {response[:200]}")
+ return None
+
+ async def check_usage(self) -> float:
+ """Check current Claude daily usage percentage.
+
+ Runs `claude` with a usage check prompt and parses the output.
+ Returns percentage as float (0.0 to 100.0).
+ """
+ # We track our own call count as a proxy.
+ # For more accurate tracking, we'd parse `claude /usage` output,
+ # but that requires interactive mode. Instead we use our DB counter
+ # and let the user set a max_calls_per_day in config.
+ calls_today = await self.state.get_usage_today()
+ return calls_today
+
+ async def is_within_budget(self, max_daily_calls: int = 200) -> bool:
+ """Check if we're under the daily usage limit.
+
+ The max_daily_claude_percent from config is mapped to a call count.
+ Default budget: 200 calls/day at 100%. So 80% = 160 calls.
+ """
+ calls = await self.check_usage()
+ return calls < max_daily_calls
+
+ def load_prompt(self, prompt_name: str, **kwargs) -> str:
+ """Load a prompt template from the prompts/ directory and fill in variables."""
+ prompt_file = PROMPTS_DIR / f"{prompt_name}.md"
+ if not prompt_file.exists():
+ logger.warning(f"Prompt file not found: {prompt_file}")
+ return ""
+ template = prompt_file.read_text()
+ for key, value in kwargs.items():
+ template = template.replace(f"{{{{{key}}}}}", str(value))
+ return template
+
+ def load_skill(self, skill_name: str) -> str:
+ """Load a skill knowledge file from the skills/ directory."""
+ skill_file = SKILLS_DIR / f"{skill_name}.md"
+ if not skill_file.exists():
+ logger.warning(f"Skill file not found: {skill_file}")
+ return ""
+ return skill_file.read_text()
+
+ def load_skills_for_agent(self, agent_name: str) -> str:
+ """Load all relevant skills for a specific sub-agent.
+
+ Returns concatenated skill content that should be injected
+ into the agent's prompts as foundational knowledge.
+ """
+ skill_map = {
+ "scout": ["prospecting_tactics", "lead_qualification"],
+ "writer": ["email_frameworks", "sales_methodology"],
+ "handler": ["objection_handling", "sales_methodology"],
+ "sender": ["email_frameworks"],
+ "linkedin": ["linkedin_outreach", "prospecting_tactics"],
+ }
+
+ skill_names = skill_map.get(agent_name, [])
+ if not skill_names:
+ return ""
+
+ sections = []
+ for name in skill_names:
+ content = self.load_skill(name)
+ if content:
+ sections.append(content)
+
+ if not sections:
+ return ""
+
+ return (
+ "\n\n---\n## FOUNDATIONAL KNOWLEDGE\n"
+ "Use the following frameworks and best practices to guide your work:\n\n"
+ + "\n\n---\n\n".join(sections)
+ )
diff --git a/harvey/config.py b/harvey/config.py
new file mode 100644
index 0000000..448c771
--- /dev/null
+++ b/harvey/config.py
@@ -0,0 +1,111 @@
+"""Configuration loader for Harvey. Reads harvey.yaml + .env."""
+
+import os
+from pathlib import Path
+
+import yaml
+from dotenv import load_dotenv
+from pydantic import BaseModel
+
+
+class PersonaConfig(BaseModel):
+ name: str
+ company: str
+ role: str
+ email: str
+ linkedin: str
+ tone: str
+
+
+class ProductConfig(BaseModel):
+ name: str
+ description: str
+ pricing: str
+ key_benefits: list[str]
+ objection_responses: dict[str, str]
+
+
+class ICPConfig(BaseModel):
+ industries: list[str]
+ company_size: str
+ titles: list[str]
+ geography: list[str]
+
+
+class EmailChannelConfig(BaseModel):
+ enabled: bool = True
+ provider: str = "instantly"
+ max_daily_sends: int = 50
+
+
+class LinkedInChannelConfig(BaseModel):
+ enabled: bool = True
+ max_daily_connections: int = 20
+ max_daily_messages: int = 10
+
+
+class ChannelsConfig(BaseModel):
+ email: EmailChannelConfig = EmailChannelConfig()
+ linkedin: LinkedInChannelConfig = LinkedInChannelConfig()
+
+
+class QuietHoursConfig(BaseModel):
+ start: str = "22:00"
+ end: str = "07:00"
+ timezone: str = "America/New_York"
+
+
+class UsageConfig(BaseModel):
+ max_daily_claude_percent: float = 80.0
+ heartbeat_interval_minutes: int = 15
+ quiet_hours: QuietHoursConfig = QuietHoursConfig()
+
+
+class HarveyConfig(BaseModel):
+ persona: PersonaConfig
+ product: ProductConfig
+ icp: ICPConfig
+ channels: ChannelsConfig = ChannelsConfig()
+ usage: UsageConfig = UsageConfig()
+
+
+class EnvConfig(BaseModel):
+ instantly_api_key: str = ""
+ linkedin_email: str = ""
+ linkedin_password: str = ""
+ hunter_api_key: str = ""
+
+
+def load_config(config_path: str | None = None) -> HarveyConfig:
+ """Load Harvey configuration from YAML file."""
+ if config_path is None:
+ config_path = _find_config_file()
+ with open(config_path) as f:
+ data = yaml.safe_load(f)
+ return HarveyConfig(**data)
+
+
+def load_env() -> EnvConfig:
+ """Load environment variables from .env file."""
+ load_dotenv()
+ return EnvConfig(
+ instantly_api_key=os.getenv("INSTANTLY_API_KEY", ""),
+ linkedin_email=os.getenv("LINKEDIN_EMAIL", ""),
+ linkedin_password=os.getenv("LINKEDIN_PASSWORD", ""),
+ hunter_api_key=os.getenv("HUNTER_API_KEY", ""),
+ )
+
+
+def _find_config_file() -> str:
+ """Search for harvey.yaml in common locations."""
+ candidates = [
+ Path.cwd() / "harvey.yaml",
+ Path.cwd().parent / "harvey.yaml",
+ Path(__file__).parent.parent / "harvey.yaml",
+ ]
+ for path in candidates:
+ if path.exists():
+ return str(path)
+ raise FileNotFoundError(
+ "harvey.yaml not found. Create one from harvey.yaml.example"
+ )
diff --git a/harvey/integrations/__init__.py b/harvey/integrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/harvey/integrations/calendar.py b/harvey/integrations/calendar.py
new file mode 100644
index 0000000..1bca0c3
--- /dev/null
+++ b/harvey/integrations/calendar.py
@@ -0,0 +1,17 @@
+"""Calendar integration — placeholder for future implementation."""
+
+import logging
+
+logger = logging.getLogger("harvey.calendar")
+
+
+class CalendarClient:
+ """Placeholder for calendar integration (Cal.com, Calendly, etc.)."""
+
+ async def get_available_slots(self, date_range: str) -> list[dict]:
+ logger.info("Calendar integration not yet implemented.")
+ return []
+
+ async def book_meeting(self, prospect_email: str, slot: dict) -> bool:
+ logger.info("Calendar integration not yet implemented.")
+ return False
diff --git a/harvey/integrations/email_finder.py b/harvey/integrations/email_finder.py
new file mode 100644
index 0000000..86cd1f5
--- /dev/null
+++ b/harvey/integrations/email_finder.py
@@ -0,0 +1,140 @@
+"""Email discovery — find email addresses without paid tools."""
+
+import asyncio
+import logging
+import re
+from typing import Optional
+
+import dns.resolver
+import aiosmtplib
+
+logger = logging.getLogger("harvey.email_finder")
+
+# Cache MX records per domain to avoid repeated lookups
+_mx_cache: dict[str, str] = {}
+
+
+def generate_patterns(first_name: str, last_name: str, domain: str) -> list[str]:
+ """Generate common email patterns for a person at a domain."""
+ first = first_name.lower().strip()
+ last = last_name.lower().strip()
+
+ if not first or not last or not domain:
+ return []
+
+ # Remove non-alpha characters
+ first = re.sub(r"[^a-z]", "", first)
+ last = re.sub(r"[^a-z]", "", last)
+
+ return [
+ f"{first}@{domain}",
+ f"{first}.{last}@{domain}",
+ f"{first}{last}@{domain}",
+ f"{first[0]}{last}@{domain}",
+ f"{first}{last[0]}@{domain}",
+ f"{first[0]}.{last}@{domain}",
+ f"{last}.{first}@{domain}",
+ f"{last}@{domain}",
+ f"{first}_{last}@{domain}",
+ f"{first}-{last}@{domain}",
+ ]
+
+
+async def get_mx_host(domain: str) -> Optional[str]:
+ """Get the primary MX host for a domain."""
+ if domain in _mx_cache:
+ return _mx_cache[domain]
+
+ try:
+ loop = asyncio.get_event_loop()
+ answers = await loop.run_in_executor(
+ None, lambda: dns.resolver.resolve(domain, "MX")
+ )
+ # Get the lowest priority MX record
+ mx_host = str(sorted(answers, key=lambda x: x.preference)[0].exchange).rstrip(".")
+ _mx_cache[domain] = mx_host
+ return mx_host
+ except Exception as e:
+ logger.debug(f"MX lookup failed for {domain}: {e}")
+ return None
+
+
+async def verify_email_smtp(email: str) -> bool:
+ """Verify an email exists via SMTP RCPT TO check.
+
+ Note: Many servers don't support this (catch-all domains, etc.)
+ so a failed check doesn't guarantee the email is invalid.
+ A successful check is a strong signal though.
+ """
+ domain = email.split("@")[1]
+ mx_host = await get_mx_host(domain)
+ if not mx_host:
+ return False
+
+ try:
+ smtp = aiosmtplib.SMTP(hostname=mx_host, port=25, timeout=10)
+ await smtp.connect()
+ await smtp.ehlo()
+
+ # Try RCPT TO
+ code, _ = await smtp.vrfy(email)
+ if code == 250:
+ await smtp.quit()
+ return True
+
+ # VRFY often disabled, try MAIL FROM + RCPT TO
+ await smtp.mail("[email protected]")
+ code, message = await smtp.rcpt(email)
+ await smtp.quit()
+
+ # 250 = accepted, 550 = rejected
+ return code == 250
+
+ except Exception as e:
+ logger.debug(f"SMTP verification failed for {email}: {e}")
+ return False
+
+
+async def find_email(
+ first_name: str,
+ last_name: str,
+ domain: str,
+ verify: bool = True,
+) -> Optional[str]:
+ """Try to find a valid email for a person at a company domain.
+
+ 1. Generate common email patterns
+ 2. Check MX records exist for domain
+ 3. Verify each pattern via SMTP
+ 4. Return first verified email, or best guess if verification unavailable
+ """
+ patterns = generate_patterns(first_name, last_name, domain)
+ if not patterns:
+ return None
+
+ # First check if domain has MX records at all
+ mx_host = await get_mx_host(domain)
+ if not mx_host:
+ logger.info(f"No MX records for {domain}. Returning best guess.")
+ return patterns[0] # first.last@ is most common
+
+ if not verify:
+ return patterns[0]
+
+ # Try to verify each pattern
+ for email in patterns:
+ logger.debug(f"Checking {email}...")
+ try:
+ is_valid = await verify_email_smtp(email)
+ if is_valid:
+ logger.info(f"Verified email: {email}")
+ return email
+ except Exception:
+ continue
+
+ # Rate limit between checks
+ await asyncio.sleep(1)
+
+ # If no verification worked, return the most common pattern
+ logger.info(f"No verified email found. Best guess: {patterns[1]}")
+ return patterns[1] # first.last@domain is the safest guess
diff --git a/harvey/integrations/instantly.py b/harvey/integrations/instantly.py
new file mode 100644
index 0000000..7421c59
--- /dev/null
+++ b/harvey/integrations/instantly.py
@@ -0,0 +1,182 @@
+"""Instantly.ai API client for cold email campaigns."""
+
+import logging
+from typing import Any
+
+import httpx
+
+logger = logging.getLogger("harvey.instantly")
+
+BASE_URL = "https://api.instantly.ai/api/v2"
+
+
+class InstantlyClient:
+ def __init__(self, api_key: str):
+ self.api_key = api_key
+ self.headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+
+ async def _request(
+ self, method: str, endpoint: str, data: dict | None = None
+ ) -> dict | list | None:
+ """Make an authenticated request to the Instantly API."""
+ url = f"{BASE_URL}/{endpoint.lstrip('/')}"
+ async with httpx.AsyncClient(timeout=30) as client:
+ response = await client.request(
+ method, url, headers=self.headers, json=data
+ )
+ if response.status_code >= 400:
+ logger.error(
+ f"Instantly API error {response.status_code}: {response.text}"
+ )
+ return None
+ if response.status_code == 204:
+ return {}
+ return response.json()
+
+ # ── Campaigns ──
+
+ async def create_campaign(self, name: str) -> dict | None:
+ """Create a new campaign. Returns campaign data with id."""
+ result = await self._request("POST", "/campaigns", {"name": name})
+ if result:
+ logger.info(f"Created campaign: {name} (id={result.get('id')})")
+ return result
+
+ async def get_campaign(self, campaign_id: str) -> dict | None:
+ """Get campaign details."""
+ return await self._request("GET", f"/campaigns/{campaign_id}")
+
+ async def list_campaigns(self, limit: int = 100) -> list:
+ """List all campaigns."""
+ result = await self._request("GET", f"/campaigns?limit={limit}")
+ return result if isinstance(result, list) else []
+
+ async def update_campaign_schedule(
+ self,
+ campaign_id: str,
+ schedule: dict,
+ ) -> dict | None:
+ """Update campaign sending schedule."""
+ return await self._request(
+ "PATCH", f"/campaigns/{campaign_id}", {"schedule": schedule}
+ )
+
+ async def activate_campaign(self, campaign_id: str) -> dict | None:
+ """Start a campaign."""
+ return await self._request(
+ "POST", f"/campaigns/{campaign_id}/activate"
+ )
+
+ async def pause_campaign(self, campaign_id: str) -> dict | None:
+ """Pause a campaign."""
+ return await self._request(
+ "POST", f"/campaigns/{campaign_id}/pause"
+ )
+
+ # ── Campaign Emails (Sequences) ──
+
+ async def set_campaign_emails(
+ self,
+ campaign_id: str,
+ sequences: list[dict],
+ ) -> dict | None:
+ """Set the email sequence for a campaign.
+
+ sequences format:
+ [
+ {
+ "subject": "Subject line",
+ "body": "Email body (HTML or plain text)",
+ "wait": 0 # days to wait after previous step
+ },
+ ...
+ ]
+ """
+ return await self._request(
+ "POST",
+ f"/campaigns/{campaign_id}/emails",
+ {"sequences": [sequences]},
+ )
+
+ # ── Leads ──
+
+ async def add_leads(
+ self,
+ campaign_id: str,
+ leads: list[dict],
+ ) -> dict | None:
+ """Add leads to a campaign.
+
+ leads format:
+ [
+ {
+ "email": "[email protected]",
+ "first_name": "John",
+ "last_name": "Doe",
+ "company_name": "Acme Inc",
+ "variables": {"custom_var": "value"}
+ }
+ ]
+ """
+ return await self._request(
+ "POST",
+ "/leads",
+ {"campaign_id": campaign_id, "leads": leads},
+ )
+
+ async def get_lead(self, email: str) -> dict | None:
+ """Get lead details by email."""
+ return await self._request("GET", f"/leads?email={email}")
+
+ # ── Replies / Emails ──
+
+ async def get_campaign_emails_sent(
+ self, campaign_id: str, limit: int = 100
+ ) -> list:
+ """Get emails sent for a campaign."""
+ result = await self._request(
+ "GET", f"/emails?campaign_id={campaign_id}&limit={limit}"
+ )
+ return result if isinstance(result, list) else []
+
+ async def get_replies(self, campaign_id: str | None = None) -> list:
+ """Get replies, optionally filtered by campaign."""
+ endpoint = "/emails/replies"
+ if campaign_id:
+ endpoint += f"?campaign_id={campaign_id}"
+ result = await self._request("GET", endpoint)
+ return result if isinstance(result, list) else []
+
+ async def send_reply(
+ self,
+ reply_to_uuid: str,
+ body: str,
+ ) -> dict | None:
+ """Send a reply to a lead's email."""
+ return await self._request(
+ "POST",
+ "/emails/reply",
+ {"reply_to_uuid": reply_to_uuid, "body": body},
+ )
+
+ # ── Analytics ──
+
+ async def get_campaign_analytics(self, campaign_id: str) -> dict | None:
+ """Get campaign performance stats."""
+ return await self._request(
+ "GET", f"/campaigns/{campaign_id}/analytics"
+ )
+
+ # ── Account / Warmup ──
+
+ async def list_accounts(self) -> list:
+ """List connected email accounts."""
+ result = await self._request("GET", "/accounts")
+ return result if isinstance(result, list) else []
+
+ async def check_warmup_status(self, account_id: str) -> dict | None:
+ """Check warmup status for an email account."""
+ return await self._request("GET", f"/accounts/{account_id}/warmup")
diff --git a/harvey/integrations/linkedin.py b/harvey/integrations/linkedin.py
new file mode 100644
index 0000000..dc1ce04
--- /dev/null
+++ b/harvey/integrations/linkedin.py
@@ -0,0 +1,274 @@
+"""LinkedIn browser automation via Playwright."""
+
+import asyncio
+import json
+import logging
+import random
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger("harvey.linkedin")
+
+COOKIES_PATH = Path(__file__).parent.parent.parent / "data" / "linkedin_cookies.json"
+
+
+class LinkedInAutomation:
+ def __init__(self, email: str, password: str):
+ self.email = email
+ self.password = password
+ self.browser = None
+ self.context = None
+ self.page = None
+
+ async def _random_delay(self, min_s: float = 2.0, max_s: float = 6.0):
+ """Human-like random delay between actions."""
+ await asyncio.sleep(random.uniform(min_s, max_s))
+
+ async def start(self):
+ """Launch browser and set up context."""
+ from playwright.async_api import async_playwright
+
+ pw = await async_playwright().start()
+ self.browser = await pw.chromium.launch(headless=True)
+
+ # Load cookies if we have them (avoids re-login)
+ if COOKIES_PATH.exists():
+ cookies = json.loads(COOKIES_PATH.read_text())
+ self.context = await self.browser.new_context()
+ await self.context.add_cookies(cookies)
+ logger.info("Loaded saved LinkedIn cookies.")
+ else:
+ self.context = await self.browser.new_context(
+ viewport={"width": 1280, "height": 800},
+ user_agent=(
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/120.0.0.0 Safari/537.36"
+ ),
+ )
+
+ self.page = await self.context.new_page()
+
+ async def stop(self):
+ """Save cookies and close browser."""
+ if self.context:
+ cookies = await self.context.cookies()
+ COOKIES_PATH.parent.mkdir(parents=True, exist_ok=True)
+ COOKIES_PATH.write_text(json.dumps(cookies))
+ logger.info("Saved LinkedIn cookies.")
+ if self.browser:
+ await self.browser.close()
+
+ async def login(self) -> bool:
+ """Log into LinkedIn."""
+ if not self.page:
+ await self.start()
+
+ await self.page.goto("https://www.linkedin.com/login")
+ await self._random_delay(1, 3)
+
+ # Check if already logged in
+ if "feed" in self.page.url:
+ logger.info("Already logged into LinkedIn.")
+ return True
+
+ try:
+ await self.page.fill("#username", self.email)
+ await self._random_delay(0.5, 1.5)
+ await self.page.fill("#password", self.password)
+ await self._random_delay(0.5, 1.5)
+ await self.page.click('button[type="submit"]')
+ await self.page.wait_for_load_state("networkidle", timeout=15000)
+
+ if "feed" in self.page.url or "mynetwork" in self.page.url:
+ logger.info("Successfully logged into LinkedIn.")
+ # Save cookies for future sessions
+ cookies = await self.context.cookies()
+ COOKIES_PATH.parent.mkdir(parents=True, exist_ok=True)
+ COOKIES_PATH.write_text(json.dumps(cookies))
+ return True
+
+ # Check for security challenge
+ if "checkpoint" in self.page.url:
+ logger.warning(
+ "LinkedIn security checkpoint detected. "
+ "Please log in manually and save cookies."
+ )
+ return False
+
+ logger.warning(f"Login may have failed. Current URL: {self.page.url}")
+ return False
+
+ except Exception as e:
+ logger.error(f"LinkedIn login failed: {e}")
+ return False
+
+ async def search_people(
+ self,
+ keywords: str = "",
+ title: str = "",
+ company: str = "",
+ location: str = "",
+ max_results: int = 25,
+ ) -> list[dict]:
+ """Search LinkedIn for people matching criteria.
+
+ Returns list of dicts with: name, title, company, linkedin_url, location
+ """
+ if not self.page:
+ await self.start()
+ if not await self.login():
+ return []
+
+ # Build search URL
+ search_parts = []
+ if keywords:
+ search_parts.append(f"keywords={keywords}")
+ if title:
+ search_parts.append(f"title={title}")
+
+ search_url = (
+ f"https://www.linkedin.com/search/results/people/"
+ f"?{'&'.join(search_parts)}"
+ )
+
+ results = []
+ page_num = 1
+
+ while len(results) < max_results:
+ url = f"{search_url}&page={page_num}"
+ await self.page.goto(url)
+ await self._random_delay(3, 6)
+ await self.page.wait_for_load_state("networkidle", timeout=15000)
+
+ # Extract search result cards
+ cards = await self.page.query_selector_all(
+ "div.entity-result__item"
+ )
+
+ if not cards:
+ # Try alternate selector
+ cards = await self.page.query_selector_all(
+ 'li.reusable-search__result-container'
+ )
+
+ if not cards:
+ logger.info(f"No results found on page {page_num}.")
+ break
+
+ for card in cards:
+ if len(results) >= max_results:
+ break
+
+ try:
+ profile = await self._extract_search_card(card)
+ if profile:
+ results.append(profile)
+ except Exception as e:
+ logger.debug(f"Error extracting search card: {e}")
+ continue
+
+ page_num += 1
+ await self._random_delay(4, 8)
+
+ # Safety: don't go beyond 5 pages
+ if page_num > 5:
+ break
+
+ logger.info(f"Found {len(results)} LinkedIn profiles.")
+ return results
+
+ async def _extract_search_card(self, card) -> Optional[dict]:
+ """Extract person info from a LinkedIn search result card."""
+ # Get profile link
+ link_el = await card.query_selector("a.app-aware-link")
+ if not link_el:
+ return None
+ href = await link_el.get_attribute("href")
+ if not href or "/in/" not in href:
+ return None
+ linkedin_url = href.split("?")[0]
+
+ # Get name
+ name_el = await card.query_selector("span.entity-result__title-text a span")
+ name = await name_el.inner_text() if name_el else ""
+ name = name.strip()
+
+ # Get title/headline
+ title_el = await card.query_selector("div.entity-result__primary-subtitle")
+ title_text = await title_el.inner_text() if title_el else ""
+ title_text = title_text.strip()
+
+ # Get location
+ loc_el = await card.query_selector("div.entity-result__secondary-subtitle")
+ location = await loc_el.inner_text() if loc_el else ""
+ location = location.strip()
+
+ # Split name
+ parts = name.split(" ", 1)
+ first_name = parts[0] if parts else ""
+ last_name = parts[1] if len(parts) > 1 else ""
+
+ # Try to extract company from title (often "Title at Company")
+ company = ""
+ if " at " in title_text:
+ company = title_text.split(" at ", 1)[1].strip()
+ title_text = title_text.split(" at ", 1)[0].strip()
+
+ return {
+ "first_name": first_name,
+ "last_name": last_name,
+ "title": title_text,
+ "company": company,
+ "linkedin_url": linkedin_url,
+ "location": location,
+ }
+
+ async def extract_profile(self, linkedin_url: str) -> Optional[dict]:
+ """Scrape a LinkedIn profile page for detailed info."""
+ if not self.page:
+ await self.start()
+ if not await self.login():
+ return None
+
+ await self.page.goto(linkedin_url)
+ await self._random_delay(3, 5)
+ await self.page.wait_for_load_state("networkidle", timeout=15000)
+
+ try:
+ # Name
+ name_el = await self.page.query_selector("h1")
+ name = await name_el.inner_text() if name_el else ""
+
+ # Headline
+ headline_el = await self.page.query_selector(
+ "div.text-body-medium"
+ )
+ headline = await headline_el.inner_text() if headline_el else ""
+
+ # Location
+ loc_el = await self.page.query_selector(
+ "span.text-body-small.inline"
+ )
+ location = await loc_el.inner_text() if loc_el else ""
+
+ # About section
+ about_el = await self.page.query_selector(
+ "section.pv-about-section div.inline-show-more-text"
+ )
+ about = await about_el.inner_text() if about_el else ""
+
+ parts = name.strip().split(" ", 1)
+
+ return {
+ "first_name": parts[0] if parts else "",
+ "last_name": parts[1] if len(parts) > 1 else "",
+ "headline": headline.strip(),
+ "location": location.strip(),
+ "about": about.strip(),
+ "linkedin_url": linkedin_url,
+ }
+
+ except Exception as e:
+ logger.error(f"Error extracting profile {linkedin_url}: {e}")
+ return None
diff --git a/harvey/main.py b/harvey/main.py
new file mode 100644
index 0000000..01694f2
--- /dev/null
+++ b/harvey/main.py
@@ -0,0 +1,194 @@
+"""Harvey's main heartbeat loop. Always Be Closing."""
+
+import asyncio
+import logging
+import signal
+import sys
+from datetime import datetime, time
+
+import pytz
+
+from harvey.brain import Brain
+from harvey.config import load_config, load_env, HarveyConfig
+from harvey.state import StateManager
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+)
+logger = logging.getLogger("harvey")
+
+
+def in_quiet_hours(config: HarveyConfig) -> bool:
+ """Check if we're currently in quiet hours."""
+ qh = config.usage.quiet_hours
+ tz = pytz.timezone(qh.timezone)
+ now = datetime.now(tz).time()
+ start = time.fromisoformat(qh.start)
+ end = time.fromisoformat(qh.end)
+
+ if start <= end:
+ return start <= now <= end
+ else:
+ # Quiet hours cross midnight (e.g., 22:00 - 07:00)
+ return now >= start or now <= end
+
+
+def seconds_until_quiet_hours_end(config: HarveyConfig) -> int:
+ """Calculate seconds until quiet hours end."""
+ qh = config.usage.quiet_hours
+ tz = pytz.timezone(qh.timezone)
+ now = datetime.now(tz)
+ end = time.fromisoformat(qh.end)
+ end_today = now.replace(hour=end.hour, minute=end.minute, second=0)
+
+ if end_today <= now:
+ # End time is tomorrow
+ end_today = end_today.replace(day=end_today.day + 1)
+
+ delta = end_today - now
+ return max(int(delta.total_seconds()), 60)
+
+
+async def decide_next_action(brain: Brain, state: StateManager, config: HarveyConfig) -> str:
+ """Ask Claude what Harvey should do next based on current state."""
+ summary = await state.get_state_summary()
+
+ prompt = brain.load_prompt(
+ "system",
+ company_name=config.persona.company,
+ product_description=config.product.description,
+ )
+
+ prompt += f"""
+
+Current state:
+- Prospects by status: {summary['prospects']}
+- Draft campaigns waiting to send: {summary['draft_campaigns']}
+- Active campaigns running: {summary['active_campaigns']}
+- Open conversations needing replies: {summary['open_conversations']}
+- Claude calls used today: {summary['usage_today']}
+
+Based on this state, what should I do next? Pick exactly ONE action:
+- "prospect" — if we need more leads (fewer than 20 prospects with status 'new')
+- "write_campaign" — if we have new prospects but no draft campaigns ready
+- "send_campaign" — if we have draft campaigns ready to deploy
+- "handle_replies" — if there are open conversations needing responses
+- "idle" — if everything is running and nothing needs attention
+
+Respond with ONLY the action name, nothing else."""
+
+ response = await brain.think(prompt, session_id="harvey-decision")
+ action = response.strip().strip('"').lower()
+
+ valid_actions = {"prospect", "write_campaign", "send_campaign", "handle_replies", "idle"}
+ if action not in valid_actions:
+ logger.warning(f"Unknown action from brain: {action}. Defaulting to idle.")
+ action = "idle"
+
+ return action
+
+
+async def heartbeat():
+ """Harvey's main loop. Wakes up, decides, acts, sleeps. Repeat."""
+ logger.info("=" * 60)
+ logger.info("Harvey is online. Always Be Closing.")
+ logger.info("=" * 60)
+
+ config = load_config()
+ env = load_env()
+ state = StateManager()
+ brain = Brain(state)
+
+ await state.init_db()
+ logger.info("Database initialized.")
+
+ # Import agents here to avoid circular imports
+ from harvey.agents.scout import Scout
+ from harvey.agents.writer import Writer
+ from harvey.agents.sender import Sender
+ from harvey.agents.handler import Handler
+
+ scout = Scout(brain, state, config, env)
+ writer = Writer(brain, state, config)
+ sender = Sender(brain, state, config, env)
+ handler = Handler(brain, state, config, env)
+
+ interval = config.usage.heartbeat_interval_minutes * 60
+ max_calls = int(200 * (config.usage.max_daily_claude_percent / 100))
+
+ while True:
+ try:
+ # 1. Check quiet hours
+ if in_quiet_hours(config):
+ sleep_for = seconds_until_quiet_hours_end(config)
+ logger.info(f"Quiet hours. Sleeping for {sleep_for // 60} minutes.")
+ await asyncio.sleep(sleep_for)
+ continue
+
+ # 2. Check usage budget
+ if not await brain.is_within_budget(max_calls):
+ logger.info("Daily usage limit reached. Sleeping until tomorrow.")
+ # Sleep for 1 hour and re-check (date will eventually roll over)
+ await asyncio.sleep(3600)
+ continue
+
+ # 3. Decide what to do
+ logger.info("Thinking about what to do next...")
+ action = await decide_next_action(brain, state, config)
+ logger.info(f"Decision: {action}")
+
+ # 4. Execute
+ if action == "prospect":
+ await scout.run()
+ elif action == "write_campaign":
+ await writer.run()
+ elif action == "send_campaign":
+ await sender.run()
+ elif action == "handle_replies":
+ await handler.run()
+ elif action == "idle":
+ logger.info("Nothing to do. Waiting for next cycle.")
+
+ # 5. Log the action
+ await state.log_action(action_type=action, agent="main")
+
+ # 6. Sleep until next heartbeat
+ logger.info(
+ f"Cycle complete. Sleeping for {config.usage.heartbeat_interval_minutes} minutes."
+ )
+ await asyncio.sleep(interval)
+
+ except KeyboardInterrupt:
+ logger.info("Harvey shutting down. Deals don't close themselves, but I need a break.")
+ break
+ except Exception as e:
+ logger.error(f"Error in heartbeat: {e}", exc_info=True)
+ logger.info("Recovering... sleeping 60s before retry.")
+ await asyncio.sleep(60)
+
+
+def main():
+ """Entry point."""
+ # Graceful shutdown on SIGTERM (for Docker)
+ loop = asyncio.new_event_loop()
+
+ def shutdown(sig, frame):
+ logger.info("Received shutdown signal.")
+ for task in asyncio.all_tasks(loop):
+ task.cancel()
+ loop.stop()
+
+ signal.signal(signal.SIGTERM, shutdown)
+
+ try:
+ loop.run_until_complete(heartbeat())
+ except KeyboardInterrupt:
+ logger.info("Goodbye.")
+ finally:
+ loop.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/harvey/models/__init__.py b/harvey/models/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/harvey/models/campaign.py b/harvey/models/campaign.py
new file mode 100644
index 0000000..422d25e
--- /dev/null
+++ b/harvey/models/campaign.py
@@ -0,0 +1,31 @@
+"""Campaign data model."""
+
+import json
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+
+class EmailStep(BaseModel):
+ step: int
+ subject: str
+ body: str
+ delay_days: int = 0 # days after previous step
+
+
+class Campaign(BaseModel):
+ id: str
+ name: str = ""
+ channel: str = "email" # email/linkedin
+ instantly_campaign_id: str = ""
+ sequence: list[EmailStep] = []
+ status: str = "draft" # draft/active/paused/completed
+ prospect_ids: list[str] = []
+ created_at: datetime = Field(default_factory=datetime.utcnow)
+
+ def sequence_json(self) -> str:
+ return json.dumps([s.model_dump() for s in self.sequence])
+
+ @classmethod
+ def sequence_from_json(cls, data: str) -> list[EmailStep]:
+ return [EmailStep(**s) for s in json.loads(data)]
diff --git a/harvey/models/conversation.py b/harvey/models/conversation.py
new file mode 100644
index 0000000..82dfb6a
--- /dev/null
+++ b/harvey/models/conversation.py
@@ -0,0 +1,31 @@
+"""Conversation data model."""
+
+import json
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+
+class Message(BaseModel):
+ sender: str # "harvey" or "prospect"
+ content: str
+ timestamp: datetime = Field(default_factory=datetime.utcnow)
+
+
+class Conversation(BaseModel):
+ id: str
+ prospect_id: str
+ campaign_id: str = ""
+ channel: str = "email"
+ thread: list[Message] = []
+ intent: str = "" # interested/objection/not_interested/ooo/wrong_person
+ status: str = "open" # open/replied/meeting_booked/closed
+ created_at: datetime = Field(default_factory=datetime.utcnow)
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
+
+ def thread_json(self) -> str:
+ return json.dumps([m.model_dump(mode="json") for m in self.thread])
+
+ @classmethod
+ def thread_from_json(cls, data: str) -> list[Message]:
+ return [Message(**m) for m in json.loads(data)]
diff --git a/harvey/models/prospect.py b/harvey/models/prospect.py
new file mode 100644
index 0000000..9feca1e
--- /dev/null
+++ b/harvey/models/prospect.py
@@ -0,0 +1,26 @@
+"""Prospect data model."""
+
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+
+class Prospect(BaseModel):
+ id: str
+ first_name: str = ""
+ last_name: str = ""
+ email: str = ""
+ linkedin_url: str = ""
+ company: str = ""
+ title: str = ""
+ industry: str = ""
+ company_size: str = ""
+ source: str = ""
+ status: str = "new" # new/contacted/replied/meeting/closed/lost
+ score: int = 0
+ personalization_notes: str = ""
+ created_at: datetime = Field(default_factory=datetime.utcnow)
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
+
+ def full_name(self) -> str:
+ return f"{self.first_name} {self.last_name}".strip()
diff --git a/harvey/state.py b/harvey/state.py
new file mode 100644
index 0000000..ea5f8c9
--- /dev/null
+++ b/harvey/state.py
@@ -0,0 +1,317 @@
+"""SQLite state manager. All of Harvey's memory lives here."""
+
+import json
+import uuid
+from datetime import datetime, date
+from pathlib import Path
+
+import aiosqlite
+
+from harvey.models.prospect import Prospect
+from harvey.models.campaign import Campaign, EmailStep
+from harvey.models.conversation import Conversation, Message
+
+DB_PATH = Path(__file__).parent.parent / "data" / "harvey.db"
+
+
+def _new_id() -> str:
+ return uuid.uuid4().hex[:12]
+
+
+class StateManager:
+ def __init__(self, db_path: str | None = None):
+ self.db_path = db_path or str(DB_PATH)
+
+ async def init_db(self):
+ """Create all tables if they don't exist."""
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.executescript("""
+ CREATE TABLE IF NOT EXISTS prospects (
+ id TEXT PRIMARY KEY,
+ first_name TEXT DEFAULT '',
+ last_name TEXT DEFAULT '',
+ email TEXT DEFAULT '',
+ linkedin_url TEXT DEFAULT '',
+ company TEXT DEFAULT '',
+ title TEXT DEFAULT '',
+ industry TEXT DEFAULT '',
+ company_size TEXT DEFAULT '',
+ source TEXT DEFAULT '',
+ status TEXT DEFAULT 'new',
+ score INTEGER DEFAULT 0,
+ personalization_notes TEXT DEFAULT '',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS campaigns (
+ id TEXT PRIMARY KEY,
+ name TEXT DEFAULT '',
+ channel TEXT DEFAULT 'email',
+ instantly_campaign_id TEXT DEFAULT '',
+ sequence_json TEXT DEFAULT '[]',
+ prospect_ids_json TEXT DEFAULT '[]',
+ status TEXT DEFAULT 'draft',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS conversations (
+ id TEXT PRIMARY KEY,
+ prospect_id TEXT REFERENCES prospects(id),
+ campaign_id TEXT DEFAULT '',
+ channel TEXT DEFAULT 'email',
+ thread_json TEXT DEFAULT '[]',
+ intent TEXT DEFAULT '',
+ status TEXT DEFAULT 'open',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS actions (
+ id TEXT PRIMARY KEY,
+ action_type TEXT,
+ agent TEXT,
+ details_json TEXT DEFAULT '{}',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS usage_log (
+ id TEXT PRIMARY KEY,
+ date TEXT,
+ claude_calls INTEGER DEFAULT 0,
+ usage_percent REAL DEFAULT 0.0,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_prospects_status ON prospects(status);
+ CREATE INDEX IF NOT EXISTS idx_campaigns_status ON campaigns(status);
+ CREATE INDEX IF NOT EXISTS idx_conversations_status ON conversations(status);
+ CREATE INDEX IF NOT EXISTS idx_usage_date ON usage_log(date);
+ """)
+
+ # ── Prospects ──
+
+ async def add_prospect(self, prospect: Prospect) -> str:
+ if not prospect.id:
+ prospect.id = _new_id()
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ """INSERT OR IGNORE INTO prospects
+ (id, first_name, last_name, email, linkedin_url, company,
+ title, industry, company_size, source, status, score,
+ personalization_notes, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ prospect.id, prospect.first_name, prospect.last_name,
+ prospect.email, prospect.linkedin_url, prospect.company,
+ prospect.title, prospect.industry, prospect.company_size,
+ prospect.source, prospect.status, prospect.score,
+ prospect.personalization_notes,
+ prospect.created_at.isoformat(),
+ prospect.updated_at.isoformat(),
+ ),
+ )
+ await db.commit()
+ return prospect.id
+
+ async def get_prospect(self, prospect_id: str) -> Prospect | None:
+ async with aiosqlite.connect(self.db_path) as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(
+ "SELECT * FROM prospects WHERE id = ?", (prospect_id,)
+ ) as cursor:
+ row = await cursor.fetchone()
+ if not row:
+ return None
+ return Prospect(**dict(row))
+
+ async def get_prospects_by_status(self, status: str) -> list[Prospect]:
+ async with aiosqlite.connect(self.db_path) as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(
+ "SELECT * FROM prospects WHERE status = ? ORDER BY created_at DESC",
+ (status,),
+ ) as cursor:
+ rows = await cursor.fetchall()
+ return [Prospect(**dict(r)) for r in rows]
+
+ async def update_prospect_status(self, prospect_id: str, status: str):
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ "UPDATE prospects SET status = ?, updated_at = ? WHERE id = ?",
+ (status, datetime.utcnow().isoformat(), prospect_id),
+ )
+ await db.commit()
+
+ async def prospect_exists(self, email: str = "", linkedin_url: str = "") -> bool:
+ """Check if a prospect already exists by email or LinkedIn URL."""
+ async with aiosqlite.connect(self.db_path) as db:
+ if email:
+ async with db.execute(
+ "SELECT 1 FROM prospects WHERE email = ?", (email,)
+ ) as cursor:
+ if await cursor.fetchone():
+ return True
+ if linkedin_url:
+ async with db.execute(
+ "SELECT 1 FROM prospects WHERE linkedin_url = ?", (linkedin_url,)
+ ) as cursor:
+ if await cursor.fetchone():
+ return True
+ return False
+
+ async def count_prospects_by_status(self) -> dict[str, int]:
+ async with aiosqlite.connect(self.db_path) as db:
+ async with db.execute(
+ "SELECT status, COUNT(*) FROM prospects GROUP BY status"
+ ) as cursor:
+ rows = await cursor.fetchall()
+ return {row[0]: row[1] for row in rows}
+
+ # ── Campaigns ──
+
+ async def add_campaign(self, campaign: Campaign) -> str:
+ if not campaign.id:
+ campaign.id = _new_id()
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ """INSERT INTO campaigns
+ (id, name, channel, instantly_campaign_id, sequence_json,
+ prospect_ids_json, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ campaign.id, campaign.name, campaign.channel,
+ campaign.instantly_campaign_id, campaign.sequence_json(),
+ json.dumps(campaign.prospect_ids), campaign.status,
+ campaign.created_at.isoformat(),
+ ),
+ )
+ await db.commit()
+ return campaign.id
+
+ async def get_campaigns_by_status(self, status: str) -> list[Campaign]:
+ async with aiosqlite.connect(self.db_path) as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(
+ "SELECT * FROM campaigns WHERE status = ?", (status,)
+ ) as cursor:
+ rows = await cursor.fetchall()
+ campaigns = []
+ for r in rows:
+ d = dict(r)
+ d["sequence"] = Campaign.sequence_from_json(d.pop("sequence_json"))
+ d["prospect_ids"] = json.loads(d.pop("prospect_ids_json"))
+ campaigns.append(Campaign(**d))
+ return campaigns
+
+ async def update_campaign(self, campaign_id: str, **kwargs):
+ async with aiosqlite.connect(self.db_path) as db:
+ for key, value in kwargs.items():
+ await db.execute(
+ f"UPDATE campaigns SET {key} = ? WHERE id = ?",
+ (value, campaign_id),
+ )
+ await db.commit()
+
+ # ── Conversations ──
+
+ async def add_conversation(self, convo: Conversation) -> str:
+ if not convo.id:
+ convo.id = _new_id()
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ """INSERT INTO conversations
+ (id, prospect_id, campaign_id, channel, thread_json,
+ intent, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ convo.id, convo.prospect_id, convo.campaign_id,
+ convo.channel, convo.thread_json(), convo.intent,
+ convo.status, convo.created_at.isoformat(),
+ convo.updated_at.isoformat(),
+ ),
+ )
+ await db.commit()
+ return convo.id
+
+ async def get_conversations_by_status(self, status: str) -> list[Conversation]:
+ async with aiosqlite.connect(self.db_path) as db:
+ db.row_factory = aiosqlite.Row
+ async with db.execute(
+ "SELECT * FROM conversations WHERE status = ?", (status,)
+ ) as cursor:
+ rows = await cursor.fetchall()
+ convos = []
+ for r in rows:
+ d = dict(r)
+ d["thread"] = Conversation.thread_from_json(d.pop("thread_json"))
+ convos.append(Conversation(**d))
+ return convos
+
+ async def update_conversation(self, convo_id: str, **kwargs):
+ async with aiosqlite.connect(self.db_path) as db:
+ for key, value in kwargs.items():
+ await db.execute(
+ f"UPDATE conversations SET {key} = ?, updated_at = ? WHERE id = ?",
+ (value, datetime.utcnow().isoformat(), convo_id),
+ )
+ await db.commit()
+
+ # ── Actions Log ──
+
+ async def log_action(self, action_type: str, agent: str, details: dict | None = None):
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ "INSERT INTO actions (id, action_type, agent, details_json) VALUES (?, ?, ?, ?)",
+ (_new_id(), action_type, agent, json.dumps(details or {})),
+ )
+ await db.commit()
+
+ # ── Usage Tracking ──
+
+ async def get_usage_today(self) -> int:
+ today = date.today().isoformat()
+ async with aiosqlite.connect(self.db_path) as db:
+ async with db.execute(
+ "SELECT claude_calls FROM usage_log WHERE date = ?", (today,)
+ ) as cursor:
+ row = await cursor.fetchone()
+ return row[0] if row else 0
+
+ async def increment_usage(self):
+ today = date.today().isoformat()
+ async with aiosqlite.connect(self.db_path) as db:
+ await db.execute(
+ """INSERT INTO usage_log (id, date, claude_calls)
+ VALUES (?, ?, 1)
+ ON CONFLICT(date) DO UPDATE SET claude_calls = claude_calls + 1""",
+ (_new_id(), today),
+ )
+ await db.commit()
+
+ # ── Summary for Decision Making ──
+
+ async def get_state_summary(self) -> dict:
+ """Get a high-level summary of current state for the decision engine."""
+ prospect_counts = await self.count_prospects_by_status()
+ async with aiosqlite.connect(self.db_path) as db:
+ async with db.execute(
+ "SELECT COUNT(*) FROM campaigns WHERE status = 'draft'"
+ ) as cursor:
+ draft_campaigns = (await cursor.fetchone())[0]
+ async with db.execute(
+ "SELECT COUNT(*) FROM campaigns WHERE status = 'active'"
+ ) as cursor:
+ active_campaigns = (await cursor.fetchone())[0]
+ async with db.execute(
+ "SELECT COUNT(*) FROM conversations WHERE status = 'open'"
+ ) as cursor:
+ open_conversations = (await cursor.fetchone())[0]
+
+ return {
+ "prospects": prospect_counts,
+ "draft_campaigns": draft_campaigns,
+ "active_campaigns": active_campaigns,
+ "open_conversations": open_conversations,
+ "usage_today": await self.get_usage_today(),
+ }
diff --git a/prompts/handler.md b/prompts/handler.md
new file mode 100644
index 0000000..409c489
--- /dev/null
+++ b/prompts/handler.md
@@ -0,0 +1,16 @@
+You are Harvey, responding to replies from prospects. Every reply is an opportunity.
+
+Guidelines:
+1. MATCH THEIR ENERGY — if they're casual, be casual. If they're formal, be formal.
+2. FAST — keep responses short. They already know who you are from the original email.
+3. ANSWER FIRST — if they asked a question, answer it immediately. Don't dodge.
+4. NO DESPERATION — never say "just checking in" or "just following up" or "I'd love to..."
+5. BE SPECIFIC — when suggesting a meeting, propose 2-3 specific times.
+6. KNOW WHEN TO STOP — if they say no, thank them and move on. One "no" is enough.
+7. OBJECTION = OPPORTUNITY — address concerns with empathy, then redirect to value.
+
+Intent-specific guidance:
+- INTERESTED: Move toward a meeting within 1-2 messages. Don't oversell.
+- OBJECTION: Acknowledge the concern, provide one proof point, ask one question.
+- QUESTION: Answer clearly, tie back to their specific situation.
+- WRONG PERSON: Thank them warmly, ask for a name or warm intro. Make it easy.
diff --git a/prompts/qualifier.md b/prompts/qualifier.md
new file mode 100644
index 0000000..ef1760d
--- /dev/null
+++ b/prompts/qualifier.md
@@ -0,0 +1,11 @@
+Score prospects on a 1-10 scale based on how well they match the ICP.
+
+Scoring criteria:
+- Title match (0-3): Exact ICP title = 3, adjacent title = 2, related = 1
+- Company fit (0-3): Right industry + size = 3, one match = 2, tangential = 1
+- Engagement signals (0-2): Recently active on LinkedIn = 1, posted about relevant topics = 2
+- Reachability (0-2): Verified email = 2, LinkedIn only = 1, no contact info = 0
+
+Score 7+: High priority — outreach immediately
+Score 4-6: Medium priority — include in batch campaigns
+Score 1-3: Low priority — skip unless pipeline is thin
diff --git a/prompts/scout.md b/prompts/scout.md
new file mode 100644
index 0000000..5d10398
--- /dev/null
+++ b/prompts/scout.md
@@ -0,0 +1,14 @@
+You are Harvey's prospecting engine. Your job is to find companies and decision-makers that match the Ideal Customer Profile (ICP).
+
+Target ICP:
+- Industries: {{industries}}
+- Company size: {{company_size}}
+- Geography: {{geography}}
+- Decision-maker titles: {{titles}}
+
+When identifying prospects:
+1. Focus on companies that would genuinely benefit from our product
+2. Look for signals of need (hiring for related roles, recent funding, tech stack changes)
+3. Prioritize quality over quantity — 10 great prospects beat 100 mediocre ones
+4. Never add the same person twice
+5. Capture any personalization angles you find (recent posts, company news, mutual connections)
diff --git a/prompts/system.md b/prompts/system.md
new file mode 100644
index 0000000..dc15cf5
--- /dev/null
+++ b/prompts/system.md
@@ -0,0 +1,12 @@
+You are Harvey, an autonomous AI sales agent at {{company_name}}. You are professional, consultative, and confident — like Harvey Specter. You never beg, you never spam. You find the right people, craft compelling outreach, and always be closing.
+
+Your philosophy:
+- Lead with value, not features
+- Every message should earn the right to send the next one
+- Be direct but never pushy
+- Personalization is everything — generic outreach is spam
+- The goal is always a conversation, not a hard sell
+- When someone says no, respect it immediately
+
+Your product: {{product_description}}
+Your company: {{company_name}}
diff --git a/prompts/writer.md b/prompts/writer.md
new file mode 100644
index 0000000..b2124c1
--- /dev/null
+++ b/prompts/writer.md
@@ -0,0 +1,25 @@
+You are Harvey, writing cold outreach emails for {{persona_company}}.
+
+Your identity:
+- Name: {{persona_name}}
+- Role: {{persona_role}}
+- Tone: {{persona_tone}}
+
+Product info:
+- Product: {{product_name}}
+- Description: {{product_description}}
+- Key benefits:
+{{product_benefits}}
+- Pricing: {{product_pricing}}
+
+Email writing rules:
+1. SHORT — under 100 words per email. Busy people don't read novels.
+2. PERSONAL — reference something specific about the prospect or their company.
+3. VALUE-FIRST — lead with an insight or observation, not your product.
+4. ONE CTA — each email has exactly one clear ask.
+5. NO JARGON — write like a human, not a marketing brochure.
+6. LOWERCASE SUBJECTS — more casual, higher open rates.
+7. NO ATTACHMENTS — no links in email 1 (deliverability).
+8. CONVERSATIONAL — read it out loud. If it sounds robotic, rewrite it.
+
+Merge variables available: {{first_name}}, {{company}}, {{title}}
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..08a55d7
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,10 @@
+pyyaml>=6.0
+python-dotenv>=1.0
+httpx>=0.27
+playwright>=1.40
+beautifulsoup4>=4.12
+dnspython>=2.4
+aiosmtplib>=3.0
+aiosqlite>=0.19
+pydantic>=2.5
+pytz>=2024.1
diff --git a/skills/email_frameworks.md b/skills/email_frameworks.md
new file mode 100644
index 0000000..8cafeaa
--- /dev/null
+++ b/skills/email_frameworks.md
@@ -0,0 +1,109 @@
+# Email Copywriting Frameworks
+
+Harvey should select the appropriate framework based on the prospect's situation, industry, and where they are in the outreach sequence.
+
+---
+
+## AIDA — Attention, Interest, Desire, Action
+**Best for:** First cold email. Works when you have a strong hook.
+
+- **Attention**: Subject line + opening line that identifies their specific problem
+- **Interest**: How you solve it, differentiated from alternatives
+- **Desire**: Social proof, results, what they'll miss without it
+- **Action**: One clear, low-friction CTA
+
+Example structure:
+```
+Subject: {{first_name}}, quick question about {{company}}'s growth
+
+Noticed {{company}} just {{trigger event}}. ← Attention
+We help {{similar companies}} solve {{problem}} by {{method}}. ← Interest
+{{Client name}} saw {{specific result}} in {{timeframe}}. ← Desire
+Worth a 15-min chat this week? ← Action
+```
+
+---
+
+## PAS — Problem, Agitate, Solve
+**Best for:** When the prospect has a clear pain point. Great for follow-ups.
+
+- **Problem**: Name the specific problem they're facing
+- **Agitate**: Make them feel the cost of NOT solving it
+- **Solve**: Position your product as the answer
+
+Example structure:
+```
+Subject: the {{problem}} problem
+
+Most {{title}}s at {{industry}} companies struggle with {{problem}}. ← Problem
+Without fixing it, {{consequence}} — and it only gets worse as ← Agitate
+you scale.
+We built {{product}} specifically for this. {{One-line solution}}. ← Solve
+Open to seeing how it works?
+```
+
+---
+
+## BAB — Before, After, Bridge
+**Best for:** Painting a vision. Great for email 2 or 3 in a sequence.
+
+- **Before**: Their current painful reality
+- **After**: What life looks like with the problem solved
+- **Bridge**: Your product is how they get there
+
+Example structure:
+```
+Subject: what if {{pain point}} wasn't a problem?
+
+Right now, your team probably spends {{X hours}} on {{task}}. ← Before
+Imagine that handled automatically — freeing your team to ← After
+focus on {{higher-value work}}.
+That's exactly what {{product}} does for teams like yours. ← Bridge
+```
+
+---
+
+## QVC — Question, Value, CTA
+**Best for:** Ultra-short emails. Great for busy executives and break-up emails.
+
+- **Question**: One relevant, thought-provoking question
+- **Value**: One sentence of value
+- **CTA**: One ask
+
+Example structure:
+```
+Subject: quick thought
+
+How is {{company}} currently handling {{process}}?
+We've helped {{similar company}} cut {{metric}} by {{percent}}.
+Worth a quick call?
+```
+
+---
+
+## The 3Ps — Praise, Picture, Push
+**Best for:** When you can reference something specific the prospect did.
+
+- **Praise**: Genuine compliment about their work/company
+- **Picture**: Paint a picture of how you can help them do even more
+- **Push**: Gentle nudge toward action
+
+---
+
+## Framework Selection Rules
+
+1. **Email 1 (cold intro)**: Use AIDA or PAS — hook them with relevance
+2. **Email 2 (follow-up)**: Use BAB or QVC — different angle, shorter
+3. **Email 3 (break-up)**: Use QVC — ultra-short, create gentle FOMO
+4. **Executive prospects**: Always QVC — they scan, not read
+5. **Technical prospects**: Use PAS — they respond to problem-solving
+6. **When you have a trigger event**: Use 3Ps — lead with the praise
+
+## Universal Rules
+- Under 100 words for cold emails
+- Lowercase subject lines (higher open rates)
+- No links in email 1 (deliverability)
+- One CTA per email, always
+- Never use "I hope this email finds you well" or "just following up"
+- Personalization in the first line, always
+- Mobile-friendly: short paragraphs, 2-3 lines max
diff --git a/skills/lead_qualification.md b/skills/lead_qualification.md
new file mode 100644
index 0000000..fd9d8dc
--- /dev/null
+++ b/skills/lead_qualification.md
@@ -0,0 +1,82 @@
+# Lead Qualification Skills
+
+Harvey uses a hybrid qualification approach: BANT for initial screening, enhanced with ICP scoring for prioritization.
+
+---
+
+## BANT Framework (Initial Qualification)
+
+### Budget
+- Can they afford the solution?
+- Signals: company size, funding stage, job postings for related roles
+- Green flags: recently funded, hiring in your product's domain
+- Red flags: very small team with no budget indicators
+
+### Authority
+- Is this person a decision-maker or influencer?
+- Decision-maker titles: VP, Director, Head of, C-suite, Founder
+- Influencer titles: Manager, Lead, Senior — can champion internally
+- If not the authority: ask for the right person (don't waste sequences)
+
+### Need
+- Do they have the problem you solve?
+- Signals: tech stack, industry challenges, LinkedIn posts about pain points
+- Validate by: checking their current tools, recent job posts, company stage
+
+### Timeline
+- Are they likely to buy soon?
+- Signals: active evaluation (G2/Capterra reviews), recent vendor changes
+- "Not now" is okay — schedule a future touchpoint
+
+---
+
+## ICP Scoring System
+
+Score every prospect 1-10 before outreach:
+
+| Criteria | Points | Details |
+|----------|--------|---------|
+| **Title match** | 0-3 | Exact ICP title = 3, adjacent = 2, related = 1 |
+| **Company fit** | 0-3 | Right industry + size = 3, one match = 2, tangential = 1 |
+| **Engagement signals** | 0-2 | Active on LinkedIn = 1, posts about relevant topics = 2 |
+| **Reachability** | 0-2 | Verified email = 2, LinkedIn only = 1, no contact = 0 |
+
+### Priority Tiers
+- **Score 8-10**: High priority — personalized outreach immediately
+- **Score 5-7**: Medium priority — include in batch campaigns
+- **Score 3-4**: Low priority — only if pipeline needs volume
+- **Score 1-2**: Skip — not worth the outreach
+
+---
+
+## MEDDIC (For Complex Deals — Future Use)
+
+When Harvey handles enterprise prospects or multi-stakeholder deals:
+
+- **Metrics**: What quantifiable outcomes does the buyer care about?
+- **Economic Buyer**: Who controls the budget?
+- **Decision Criteria**: What factors will they use to decide?
+- **Decision Process**: What steps do they go through to buy?
+- **Identify Pain**: What's the core problem driving urgency?
+- **Champion**: Is there an internal advocate for your solution?
+
+---
+
+## Disqualification Signals
+
+Harvey should NOT pursue prospects who:
+- Have fewer employees than the minimum ICP threshold
+- Are in a completely unrelated industry
+- Have no discoverable contact information
+- Already use a deeply entrenched competitor (unless switching signals exist)
+- Explicitly opted out of communications
+
+## Enrichment Priorities
+
+When qualifying, gather in this order:
+1. Company domain + size (free: LinkedIn, website)
+2. Decision-maker name + title (free: LinkedIn search)
+3. Email address (free: pattern guessing + SMTP verification)
+4. Recent company news (free: Google search)
+5. Tech stack (free: BuiltWith, Wappalyzer)
+6. Personalization angles (free: LinkedIn posts, company blog)
diff --git a/skills/linkedin_outreach.md b/skills/linkedin_outreach.md
new file mode 100644
index 0000000..bad84e7
--- /dev/null
+++ b/skills/linkedin_outreach.md
@@ -0,0 +1,131 @@
+# LinkedIn Outreach Skills
+
+Harvey's LinkedIn playbook for building relationships and generating conversations.
+
+---
+
+## Connection Request Strategy
+
+### To Note or Not to Note
+- **No note**: 34.3% acceptance rate (slightly higher than with notes)
+- **Personalized note**: 32.3% acceptance rate (but allows pre-framing)
+- **Rule**: Use notes only when you have something genuinely relevant to say. A generic note hurts more than no note at all.
+
+### Good Connection Notes (under 300 chars)
+```
+"Hi {{first_name}} — saw your post about {{topic}}. Thought-provoking stuff.
+Would love to connect."
+
+"Hi {{first_name}} — we're both in the {{industry}} space. Always good to
+connect with fellow {{title}}s."
+
+"{{first_name}} — {{mutual_connection}} mentioned you're doing great work
+at {{company}}. Would love to connect."
+```
+
+### Bad Connection Notes (never do these)
+- "I'd love to tell you about our product..." (sales pitch on connect)
+- "We help companies like yours..." (too salesy)
+- Generic "Let's connect!" with no context
+
+---
+
+## Messaging Sequence (Post-Connection)
+
+### Day 0: Connection Accepted
+- Do NOT pitch immediately
+- Optional: Like or comment on their recent post (build familiarity)
+
+### Day 1-2: First Message
+- Thank them for connecting
+- Ask a genuine question or share a relevant insight
+- NO pitch, NO links, NO asks
+
+```
+"Thanks for connecting, {{first_name}}! Been following what {{company}}
+is doing with {{initiative}} — really impressive growth.
+
+Quick question: how are you all currently handling {{relevant_process}}?"
+```
+
+### Day 4-5: Second Message (if they replied)
+- Continue the conversation naturally
+- Introduce your product ONLY if there's a natural opening
+- Frame as "we do something similar" not "buy our thing"
+
+```
+"That's interesting — we actually built something that tackles exactly that.
+A few {{industry}} companies are using it to {{benefit}}.
+
+Would you be open to a quick look? No pressure at all."
+```
+
+### Day 4-5: Second Message (if NO reply)
+- One gentle follow-up only
+- Add value (share an article, insight, or observation)
+
+```
+"Hey {{first_name}} — came across this {{article/stat}} about {{topic}}
+and thought of {{company}}. Figured it might be useful.
+
+[Link or brief summary]"
+```
+
+### After 2 Messages with No Reply
+- Stop. Do not send more LinkedIn messages.
+- Move them to email outreach if you have their address.
+
+---
+
+## Profile Engagement Strategy (Warm-Up)
+
+Before reaching out to high-value prospects, warm them up:
+
+1. **Week 1**: View their profile (they see the notification)
+2. **Week 1-2**: Like 2-3 of their posts
+3. **Week 2**: Leave a thoughtful comment on a post
+4. **Week 2-3**: Send connection request (they now recognize your name)
+
+This sequence increases acceptance rates by up to 25%.
+
+---
+
+## Content for Engagement
+
+When commenting on prospects' posts:
+- Add substance, not just "Great post!"
+- Share a relevant experience or data point
+- Ask a follow-up question
+- Keep it under 3 sentences
+
+Good: "This resonates. We saw the same pattern with {{related insight}}.
+Curious — did you find that {{follow-up question}}?"
+
+Bad: "Great insight! 🔥 Totally agree!"
+
+---
+
+## Rate Limits & Safety
+
+To avoid LinkedIn restrictions:
+- **Connection requests**: Max 20/day, spread throughout the day
+- **Messages**: Max 10/day to new connections
+- **Profile views**: Max 50/day
+- **Random delays**: 3-8 seconds between actions
+- **Session length**: Max 2 hours, then break for 1+ hours
+- **Weekly limits**: Max 100 connection requests/week
+- **Cookie persistence**: Reuse sessions, don't re-login each time
+- **Human patterns**: Don't operate during obviously off-hours for your timezone
+
+---
+
+## LinkedIn-Specific Personalization Sources
+
+When crafting messages, look for:
+1. Recent posts or articles they've shared
+2. Job changes (new role = high receptivity window)
+3. Company milestones (funding, product launches, hiring)
+4. Mutual connections
+5. Shared groups or interests
+6. Their "About" section
+7. Featured content on their profile
diff --git a/skills/objection_handling.md b/skills/objection_handling.md
new file mode 100644
index 0000000..d615c12
--- /dev/null
+++ b/skills/objection_handling.md
@@ -0,0 +1,79 @@
+# Objection Handling Skills
+
+Harvey uses proven frameworks to handle objections. The goal is never to "overcome" an objection — it's to understand the concern and redirect toward value.
+
+---
+
+## Core Framework: LAARC
+**Listen → Acknowledge → Assess → Respond → Confirm**
+
+1. **Listen**: Read the full reply. Identify the actual objection, not just the surface words.
+2. **Acknowledge**: Show you heard them. "That makes sense" or "I appreciate you being direct."
+3. **Assess**: Ask a clarifying question if the objection is vague.
+4. **Respond**: Address the concern with evidence, reframe, or flexibility.
+5. **Confirm**: Check that the concern is resolved. "Does that address your concern?"
+
+---
+
+## The 4 Objection Categories
+
+Every objection falls into one of these buckets:
+
+### 1. BUDGET — "It's too expensive" / "No budget"
+**Strategy**: Reframe around ROI and cost of inaction.
+
+Responses:
+- "Totally understand. Most of our clients felt the same way initially. {{Client}} found that {{product}} paid for itself in {{timeframe}} through {{specific savings}}."
+- "What's the cost of NOT solving {{problem}}? Most teams we work with are losing {{X}} per month to {{inefficiency}}."
+- "We have flexible options. Worth a quick call to see if there's a fit for your budget?"
+
+### 2. AUTHORITY — "I'm not the right person" / "Need to check with my boss"
+**Strategy**: Ask for a referral or offer to help them make the case.
+
+Responses:
+- "No worries at all — who would be the best person to chat with about this?"
+- "Totally get it. Would it help if I put together a one-pager you could share with {{decision maker title}}?"
+- "Happy to loop them in. Want me to send a brief summary you can forward?"
+
+### 3. NEED — "We already have a solution" / "Not a priority right now"
+**Strategy**: Differentiate or plant a seed for later.
+
+Responses:
+- "Makes sense. Curious — what's the one thing you wish your current solution did better?"
+- "Totally fair. When it does become a priority, what would need to change?"
+- "I hear that a lot. The teams that switched to us from {{competitor}} say the biggest difference was {{differentiator}}."
+
+### 4. TIMING — "Not right now" / "Maybe next quarter"
+**Strategy**: Respect their timeline but stay in their orbit.
+
+Responses:
+- "Completely understand. When would be a good time to reconnect?"
+- "No rush at all. Mind if I send over a quick case study in the meantime? That way you'll have context when the timing is right."
+- "Got it. I'll circle back in {{timeframe}} — does that work?"
+
+---
+
+## Advanced Techniques
+
+### The Isolate & Reverse
+When a prospect gives a vague objection:
+1. Isolate: "If we could solve {{concern}}, would you be open to exploring this?"
+2. This reveals if it's a real objection or a brush-off.
+
+### The Feel-Felt-Found
+For emotional objections:
+"I understand how you feel. {{Similar company}} felt the same way. What they found was {{positive outcome}}."
+
+### The Cost of Inaction
+For status quo bias:
+"What happens if nothing changes in the next 6 months? Based on what you've shared, {{consequence}}."
+
+---
+
+## Rules for Harvey
+1. Never argue with an objection
+2. One response attempt per objection — if they push back again, respect it
+3. "Not interested" is final — thank them and close gracefully
+4. Always end an objection response with a question or soft CTA
+5. Match their energy and formality level
+6. If genuinely not a fit, say so — credibility > conversion
diff --git a/skills/prospecting_tactics.md b/skills/prospecting_tactics.md
new file mode 100644
index 0000000..9e0140e
--- /dev/null
+++ b/skills/prospecting_tactics.md
@@ -0,0 +1,148 @@
+# DIY Prospecting Tactics
+
+Harvey's playbook for finding leads without expensive tools like Apollo, ZoomInfo, or Clearbit.
+
+---
+
+## Strategy 1: Google Dorking
+
+### Find LinkedIn Profiles
+```
+site:linkedin.com/in "VP Marketing" "SaaS" "San Francisco"
+site:linkedin.com/in "Head of Growth" "marketing agency"
+site:linkedin.com/in "{{title}}" "{{industry}}" "{{location}}"
+```
+
+### Find Company Team Pages
+```
+site:{{domain}} "team" OR "about" OR "leadership"
+"{{company name}}" "team" "{{title}}"
+```
+
+### Find Companies in an Industry
+```
+"{{industry}}" "Series A" OR "Series B" site:crunchbase.com
+"{{industry}}" company "{{location}}" "employees" site:linkedin.com/company
+```
+
+### Find Email Patterns
+```
+"@{{domain}}" email
+site:{{domain}} "contact" OR "email" OR "@"
+"{{first_name}} {{last_name}}" "{{company}}" email
+```
+
+---
+
+## Strategy 2: LinkedIn Search
+
+### People Search Operators
+- **Title**: Search "VP Marketing" to find exact title matches
+- **Company**: Filter by current company
+- **Location**: Filter by geographic region
+- **Industry**: Filter by LinkedIn industry categories
+- **Connections**: 2nd-degree connections have higher accept rates
+
+### Sales Navigator (if available)
+- Boolean search: "VP Marketing" AND "SaaS" NOT "consultant"
+- Saved searches with alerts for new matches
+- Lead lists for organized outreach
+
+### Without Sales Navigator
+- Use LinkedIn's basic search with keyword combinations
+- Browse "People Also Viewed" on relevant profiles
+- Check company pages → "People" tab for employees
+- Search within relevant LinkedIn Groups
+
+---
+
+## Strategy 3: Company Website Scraping
+
+### Team/About Pages
+Most companies list leadership on /team, /about, /about-us, /our-team, /people, /leadership pages.
+
+**Extract:**
+- Name + title from team cards
+- Sometimes email or LinkedIn links directly listed
+- Company size indicator from number of team members
+
+### Job Postings
+- Companies hiring for roles your product supports = high-intent prospects
+- Check /careers, /jobs pages
+- Also check job boards: Indeed, LinkedIn Jobs, Wellfound (for startups)
+
+### Tech Stack Discovery
+- **BuiltWith/Wappalyzer**: Identify their current tools
+- Useful for: "I see you're using {{competitor}} — here's how we compare"
+- Free browser extensions available
+
+---
+
+## Strategy 4: Email Pattern Discovery
+
+### Common Email Formats (in order of prevalence)
+1. `[email protected]` (most common)
+4. `[email protected]` (first initial + last name)
+
+### Verification Methods (Free)
+1. **MX Record Check**: Verify the domain accepts email (dns lookup)
+2. **SMTP RCPT TO**: Ask the mail server if the address exists
+3. **Hunter.io Free Tier**: 25 searches/mo + 50 verifications/mo
+4. **Email format from known addresses**: If you know one person's email at a company, the pattern applies to everyone
+
+### Catch-All Domains
+Some domains accept all addresses (catch-all). SMTP verification won't work for these. Rely on pattern + domain verification instead.
+
+---
+
+## Strategy 5: Trigger Events
+
+High-value timing signals that indicate a prospect might be ready to buy:
+
+1. **New hire in relevant role** — they're building the function you support
+2. **Recent funding** — they have budget to spend
+3. **New product launch** — they need marketing/growth support
+4. **Job posting for your product's domain** — they're investing in the area
+5. **Competitor using your product** — social proof angle
+6. **Company expansion** — growing teams need new tools
+7. **Leadership change** — new leaders bring new tools
+8. **Tech stack change** — they're evaluating alternatives
+
+### Where to find trigger events (free)
+- Google News alerts for target companies
+- LinkedIn: follow target companies for updates
+- Crunchbase (free tier): funding announcements
+- Company blogs and press release pages
+- Job boards: new postings in relevant departments
+
+---
+
+## Strategy 6: Referral Mining
+
+When a prospect says "I'm not the right person":
+1. Ask who IS the right person (name + title)
+2. Ask if they'd be open to making an intro
+3. If no intro, use their name as social proof: "{{name}} on your team suggested I reach out..."
+
+When a deal closes:
+1. Ask for referrals to similar companies
+2. Ask if they know peers in other companies with similar challenges
+3. LinkedIn: check their connections for ICP matches
+
+---
+
+## Daily Prospecting Quotas
+
+For sustainable pipeline building:
+- **Research**: 20-30 companies per day
+- **New prospects identified**: 10-15 per day
+- **Emails verified**: 10-15 per day
+- **Total prospects added to DB**: 10-15 per day
+- **Quality check**: Score every prospect before adding to outreach
diff --git a/skills/sales_methodology.md b/skills/sales_methodology.md
new file mode 100644
index 0000000..662cf68
--- /dev/null
+++ b/skills/sales_methodology.md
@@ -0,0 +1,145 @@
+# Sales Methodology
+
+Harvey's core operating philosophy and decision-making framework.
+
+---
+
+## The ABC Loop: Always Be Closing
+
+Harvey's heartbeat loop maps to the sales cycle:
+
+```
+Prospect → Qualify → Outreach → Engage → Close → Learn → Repeat
+```
+
+At every stage, Harvey should be moving prospects forward:
+- **Prospect**: Find the right people
+- **Qualify**: Score and prioritize them
+- **Outreach**: Reach out with relevant, personalized messaging
+- **Engage**: Handle replies with the goal of a meeting
+- **Close**: Book the meeting (future: close the deal)
+- **Learn**: Track what worked, adjust
+
+---
+
+## Multi-Channel Orchestration
+
+### Channel Selection by Prospect Type
+
+| Prospect Type | Primary Channel | Secondary | Notes |
+|---------------|----------------|-----------|-------|
+| C-Suite / Founders | Email | LinkedIn | Keep emails ultra-short |
+| VP / Director | Email + LinkedIn | - | Both channels simultaneously |
+| Manager / IC | LinkedIn | Email | LinkedIn often more effective |
+| Unknown seniority | Email | LinkedIn | Default to email first |
+
+### Sequencing Across Channels
+
+A typical multi-channel sequence:
+```
+Day 1: LinkedIn — view profile
+Day 2: LinkedIn — like a post
+Day 3: Email 1 — cold intro (AIDA or PAS)
+Day 4: LinkedIn — send connection request
+Day 6: Email 2 — follow-up (BAB or QVC)
+Day 8: LinkedIn — message (if connected)
+Day 10: Email 3 — break-up (QVC)
+```
+
+### Rules
+- Never hit the same channel twice in a row
+- Maximum 7 touchpoints total before stopping
+- If they reply on any channel, switch ALL future communication to that channel
+- If they connect on LinkedIn but don't reply to messages, try email
+- If they open emails but don't reply, try LinkedIn
+
+---
+
+## Conversation Flow: Reply to Meeting
+
+The goal of every reply conversation is to book a meeting within 2-3 exchanges.
+
+### Flow:
+```
+Prospect replies (interested) →
+Harvey acknowledges + proposes meeting →
+Prospect agrees/suggests time →
+Harvey confirms + sends calendar link
+```
+
+### Rules:
+- Propose 2-3 specific time slots (not "when works for you?")
+- Include timezone
+- Keep each reply under 80 words
+- If they ask a question, answer it AND propose a meeting in the same reply
+- Never send more than 3 unreplied messages in a conversation
+
+---
+
+## Tone Calibration
+
+### COSTAR Framework for Every Message
+
+- **C**ontext: Who is this person? What do they do? What's their company?
+- **O**bjective: What do I want from this specific message?
+- **S**tyle: Professional but conversational. Never corporate-speak.
+- **T**one: Confident, helpful, peer-to-peer (never salesy or desperate)
+- **A**udience: Match their seniority and industry vocabulary
+- **R**esponse format: Short paragraphs, clear CTA
+
+### Harvey's Voice
+- Writes like a smart colleague, not a sales bot
+- Uses contractions (we're, you're, it's)
+- Asks questions instead of making statements
+- Never uses: "just following up", "checking in", "I hope this finds you well", "reaching out", "picking your brain"
+- Acknowledges that their time is valuable
+- Is comfortable with silence — doesn't over-follow-up
+
+---
+
+## Decision Priorities
+
+When Harvey has multiple possible actions, prioritize in this order:
+
+1. **Handle replies** — hot leads cool fast. Always respond first.
+2. **Send campaigns** — deploy what's ready. Pipeline doesn't fill itself.
+3. **Write campaigns** — create sequences for prospects waiting in queue.
+4. **Prospect** — only when pipeline needs fresh leads.
+5. **Idle** — everything is running. Don't force unnecessary actions.
+
+---
+
+## Key Metrics Harvey Tracks
+
+### Activity Metrics
+- Prospects found per day
+- Emails sent per day
+- LinkedIn actions per day
+- Replies received per day
+
+### Performance Metrics
+- Reply rate (target: 5-15% for cold email)
+- Positive reply rate (target: 2-5%)
+- Meeting book rate (target: 1-3% of emails sent)
+- Email open rate (target: 40-60%)
+
+### Learning Metrics
+- Which subject lines get opened?
+- Which email frameworks get replies?
+- Which ICP segments respond best?
+- What time of day gets best engagement?
+- Which objection responses work?
+
+---
+
+## Ethical Guidelines
+
+Harvey operates with integrity:
+1. **Never lie** about who Harvey is (if asked, be transparent about being AI-assisted)
+2. **Never spam** — quality over quantity, always
+3. **Respect opt-outs** immediately and permanently
+4. **CAN-SPAM compliance** — include company info, honor unsubscribes
+5. **GDPR awareness** — be careful with EU prospects
+6. **LinkedIn TOS** — stay within rate limits, no fake profiles
+7. **One "no" is enough** — never re-contact someone who declined
+8. **If it's not a fit, say so** — credibility matters more than any single deal