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.
Fix 8 bugs, add tests, polish for open source
Ethanf9948909630f
diff --git a/.env.example b/.env.exampleindex ca2de95..a76995a 100644--- a/.env.example+++ b/.env.example@@ -14,5 +14,10 @@ CLOUDFLARE_API_TOKEN=your_api_token_here# Hunter.io (optional, free tier = 50 lookups/mo)HUNTER_API_KEY=your_hunter_api_key_here+# Serper.dev (optional, $5/mo for 2,500 Google searches)+# Most reliable search backend for prospect discovery+# Sign up at: https://serper.dev+SERPER_API_KEY=your_serper_api_key_here+# Calendar (later)# CALENDLY_API_KEY=your_calendly_api_key_herediff --git a/Dockerfile b/Dockerfileindex 79d6072..5e23c12 100644--- a/Dockerfile+++ b/Dockerfile@@ -20,6 +20,7 @@ RUN pip install --no-cache-dir -r requirements.txt# Copy projectCOPY harvey/ harvey/COPY prompts/ prompts/+COPY skills/ skills/COPY harvey.yaml .# Create data directorydiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..136312a--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Ethan Rogers++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/harvey/agents/handler.py b/harvey/agents/handler.pyindex 5f948ae..7bee143 100644--- a/harvey/agents/handler.py+++ b/harvey/agents/handler.py@@ -89,17 +89,15 @@ class Handler:if not lead_email or not reply_text:return- logger.info(f"Handler: Reply from {lead_email}")+ # Dedup: skip if we already processed this reply+ if reply_uuid and await self.state.is_reply_processed(reply_uuid):+ logger.debug(f"Handler: Reply {reply_uuid} already processed. Skipping.")+ return- # 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)+ logger.info(f"Handler: Reply from {lead_email}")- 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)+ # Find the prospect by email (indexed lookup)+ prospect = await self.state.get_prospect_by_email(lead_email)if not prospect:logger.warning(f"Handler: No prospect found for {lead_email}")@@ -181,6 +179,10 @@ class Handler:},)+ # Mark reply as processed to avoid double-handling+ if reply_uuid:+ await self.state.mark_reply_processed(reply_uuid)+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:diff --git a/harvey/agents/scout.py b/harvey/agents/scout.pyindex d243ac0..4a01367 100644--- a/harvey/agents/scout.py+++ b/harvey/agents/scout.py@@ -994,15 +994,21 @@ Respond ONLY with the JSON array."""def _parse_linkedin_url(self, url: str, snippet: str) -> dict | None:"""Parse a LinkedIn profile URL and snippet to extract name."""- match = re.search(r"/in/([a-zA-Z]+-[a-zA-Z]+)", url)+ match = re.search(r"/in/([\w][\w-]+)", url)if match:- parts = match.group(1).split("-")+ slug = match.group(1)+ # Remove trailing hex/numeric IDs that LinkedIn appends+ slug = re.sub(r"-[0-9a-f]{4,}$", "", slug)+ parts = slug.split("-")+ # Filter out empty parts and very short noise+ parts = [p for p in parts if len(p) > 1 or p.isalpha()]if len(parts) >= 2:return {"first_name": parts[0].title(),- "last_name": parts[1].title(),+ "last_name": " ".join(p.title() for p in parts[1:]),}+ # Fallback: parse from snippet (e.g., "First Last - Title at Company")name_match = re.match(r"^([A-Z][a-z]+)\s+([A-Z][a-z]+)", snippet)if name_match:return {diff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex 539888e..e8366c9 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -2,6 +2,7 @@import jsonimport logging+from datetime import datefrom harvey.brain import Brainfrom harvey.config import HarveyConfig, EnvConfig@@ -37,6 +38,14 @@ class Sender:logger.info("Sender: No draft campaigns to deploy.")return+ # Enforce daily send limit+ max_sends = self.config.channels.email.max_daily_sends+ sends_today = await self._count_sends_today()+ remaining = max_sends - sends_today+ if remaining <= 0:+ logger.info(f"Sender: Daily send limit reached ({sends_today}/{max_sends}). Skipping.")+ return+for campaign in draft_campaigns:try:await self._deploy_campaign(campaign)@@ -73,7 +82,7 @@ class Sender:logger.error(f"Sender: Failed to set emails for campaign {campaign_id}")return- # 3. Add leads+ # 3. Add leads (capped to remaining daily budget)prospects = []for prospect_id in campaign.prospect_ids:prospect = await self.state.get_prospect(prospect_id)@@ -84,6 +93,17 @@ class Sender:logger.warning(f"Sender: No valid prospects for campaign {campaign.name}")return+ # Check remaining daily send budget+ max_sends = self.config.channels.email.max_daily_sends+ sends_today = await self._count_sends_today()+ remaining = max_sends - sends_today+ if remaining <= 0:+ logger.info(f"Sender: Daily limit reached. Deferring campaign '{campaign.name}'.")+ return+ if len(prospects) > remaining:+ logger.info(f"Sender: Capping leads from {len(prospects)} to {remaining} (daily limit).")+ prospects = prospects[:remaining]+leads = [{"email": p.email,@@ -134,3 +154,15 @@ class Sender:f"Sender: Campaign '{campaign.name}' deployed to Instantly "f"with {len(leads)} leads. Campaign ID: {campaign_id}")++ async def _count_sends_today(self) -> int:+ """Count how many prospects were contacted today."""+ import aiosqlite+ today = date.today().isoformat()+ async with aiosqlite.connect(self.state.db_path) as db:+ async with db.execute(+ "SELECT COUNT(*) FROM prospects WHERE status = 'contacted' AND updated_at LIKE ?",+ (f"{today}%",),+ ) as cursor:+ row = await cursor.fetchone()+ return row[0] if row else 0diff --git a/harvey/agents/writer.py b/harvey/agents/writer.pyindex e3ee769..ca395bd 100644--- a/harvey/agents/writer.py+++ b/harvey/agents/writer.py@@ -65,6 +65,10 @@ class Writer:)campaign_id = await self.state.add_campaign(campaign)+ # Mark prospects so they aren't picked up again+ for p in prospects:+ await self.state.update_prospect_status(p.id, "queued")+await self.state.log_action(action_type="write_campaign",agent="writer",diff --git a/harvey/cli.py b/harvey/cli.pyindex 5ac9b76..ab07952 100644--- a/harvey/cli.py+++ b/harvey/cli.py@@ -53,7 +53,7 @@ def cmd_train(args):from harvey.trainer import Trainertrainer = Trainer()- asyncio.run(trainer.train_from_url(args.url, max_pages=args.max_pages))+ asyncio.run(trainer.train(args.url, max_pages=args.max_pages))def cmd_dashboard(args):diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex 35b6a44..fa9cdaf 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -7,6 +7,7 @@ import osimport signalimport subprocessimport sys+import uuidfrom datetime import datetimefrom pathlib import Path@@ -300,7 +301,7 @@ async def add_feedback(request: Request):comment = data.get("comment", "")if not comment:return {"success": False, "message": "Comment is required."}- feedback_id = _new_id()+ feedback_id = uuid.uuid4().hex[:12]db_path = str(DB_PATH)if DB_PATH.exists():async with aiosqlite.connect(db_path) as db:diff --git a/harvey/main.py b/harvey/main.pyindex 0d8cfd3..acf93b0 100644--- a/harvey/main.py+++ b/harvey/main.py@@ -4,7 +4,7 @@ import asyncioimport loggingimport signalimport sys-from datetime import datetime, time+from datetime import datetime, time, timedeltaimport pytz@@ -45,7 +45,7 @@ def seconds_until_quiet_hours_end(config: HarveyConfig) -> int:if end_today <= now:# End time is tomorrow- end_today = end_today.replace(day=end_today.day + 1)+ end_today = end_today + timedelta(days=1)delta = end_today - nowreturn max(int(delta.total_seconds()), 60)diff --git a/harvey/state.py b/harvey/state.pyindex 7c6430a..4a812f2 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -110,15 +110,21 @@ class StateManager:CREATE TABLE IF NOT EXISTS usage_log (id TEXT PRIMARY KEY,- date TEXT,+ date TEXT UNIQUE,claude_calls INTEGER DEFAULT 0,usage_percent REAL DEFAULT 0.0,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);+ CREATE TABLE IF NOT EXISTS processed_replies (+ reply_id TEXT PRIMARY KEY,+ processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );+CREATE INDEX IF NOT EXISTS idx_companies_domain ON companies(domain);CREATE INDEX IF NOT EXISTS idx_prospects_company_id ON prospects(company_id);CREATE INDEX IF NOT EXISTS idx_prospects_status ON prospects(status);+ CREATE INDEX IF NOT EXISTS idx_prospects_email ON prospects(email);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_feedback_entity ON feedback(entity_type, entity_id);@@ -258,6 +264,23 @@ class StateManager:)await db.commit()+ async def get_prospect_by_email(self, email: str) -> "Prospect | None":+ """Look up a prospect by email address (indexed query)."""+ if not email:+ return None+ async with aiosqlite.connect(self.db_path) as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ "SELECT * FROM prospects WHERE email = ?", (email,)+ ) as cursor:+ row = await cursor.fetchone()+ if not row:+ return None+ d = dict(row)+ d["email_verified"] = bool(d.get("email_verified", 0))+ d["phone_verified"] = bool(d.get("phone_verified", 0))+ return Prospect(**d)+async def prospect_exists(self, email: str = "", linkedin_url: str = "") -> bool:async with aiosqlite.connect(self.db_path) as db:if email:@@ -320,6 +343,27 @@ class StateManager:rows = await cursor.fetchall()return [dict(r) for r in rows]+ # ── Reply Deduplication ──++ async def is_reply_processed(self, reply_id: str) -> bool:+ """Check if a reply has already been processed."""+ if not reply_id:+ return False+ async with aiosqlite.connect(self.db_path) as db:+ async with db.execute(+ "SELECT 1 FROM processed_replies WHERE reply_id = ?", (reply_id,)+ ) as cursor:+ return bool(await cursor.fetchone())++ async def mark_reply_processed(self, reply_id: str):+ """Mark a reply as processed to avoid double-handling."""+ async with aiosqlite.connect(self.db_path) as db:+ await db.execute(+ "INSERT OR IGNORE INTO processed_replies (reply_id) VALUES (?)",+ (reply_id,),+ )+ await db.commit()+# ── Campaigns ──async def add_campaign(self, campaign: Campaign) -> str:diff --git a/prompts/qualifier.md b/prompts/qualifier.mddeleted file mode 100644index ef1760d..0000000--- a/prompts/qualifier.md+++ /dev/null@@ -1,11 +0,0 @@-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 thindiff --git a/skills/README.md b/skills/README.mdnew file mode 100644index 0000000..10104d0--- /dev/null+++ b/skills/README.md@@ -0,0 +1,46 @@+# Skills++Skills are editable Markdown files that give Harvey foundational sales knowledge. Each agent loads the skills it needs before making decisions.++## How Skills Work++When an agent runs, it calls `brain.load_skills_for_agent("agent_name")` which concatenates the relevant skill files and injects them into the prompt. This means you can change Harvey's behavior by editing these files — no code changes needed.++## Skill → Agent Mapping++| Skill | Scout | Writer | Handler | Sender | LinkedIn |+|-------|-------|--------|---------|--------|----------|+| `prospecting_tactics.md` | x | | | | x |+| `lead_qualification.md` | x | | | | |+| `account_navigation.md` | x | | | | |+| `email_frameworks.md` | | x | | x | |+| `sales_methodology.md` | | x | x | | |+| `offer_strategy.md` | | x | x | | |+| `objection_handling.md` | | | x | | |+| `linkedin_outreach.md` | | | | | x |+| `product_knowledge.md` | x | x | x | x | x |+| `competitive_intel.md` | | x | x | | |++## Built-in Skills++- **`prospecting_tactics.md`** — Google dorking queries, company website scraping, trigger events, referral mining+- **`lead_qualification.md`** — BANT screening, ICP scoring, MEDDIC framework, disqualification criteria+- **`account_navigation.md`** — Multi-contact handling, entry point strategy, multi-threading rules+- **`email_frameworks.md`** — Cold email copywriting rules, banned AI patterns, 5 frameworks (AIDA, PAS, BAB, QVC, 3Ps)+- **`sales_methodology.md`** — ABC Loop, conversation flow, tone calibration, ethical guidelines+- **`offer_strategy.md`** — Offer ladder by engagement level, closing mechanics, timing rules+- **`objection_handling.md`** — LAARC framework, 4 objection categories with responses+- **`linkedin_outreach.md`** — Connection sequences, messaging templates, rate limits++## Auto-Generated Skills++These are created by `harvey train <url>` and are specific to your product:++- **`product_knowledge.md`** — Features, benefits, pricing, use cases, pain points, buying triggers+- **`competitive_intel.md`** — Battle cards for each competitor, differentiation angles, migration paths++## Adding or Editing Skills++1. Edit any `.md` file in this directory+2. Changes take effect on the next heartbeat cycle (no restart needed)+3. To add a new skill, create the file and add it to the `skill_map` in `harvey/brain.py`diff --git a/tests/__init__.py b/tests/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tests/test_config.py b/tests/test_config.pynew file mode 100644index 0000000..471e68b--- /dev/null+++ b/tests/test_config.py@@ -0,0 +1,61 @@+"""Tests for configuration loading."""++import tempfile+import os++import yaml++from harvey.config import HarveyConfig, EnvConfig, load_env+++def test_config_from_dict():+ """HarveyConfig can be constructed from a dict (YAML-like)."""+ data = {+ "persona": {+ "name": "Harvey",+ "company": "Acme",+ "role": "BDR",+ "email": "[email protected]",+ "linkedin": "",+ "tone": "professional",+ },+ "product": {+ "name": "Widget",+ "description": "A great widget",+ "pricing": "$99/mo",+ "key_benefits": ["Fast", "Reliable"],+ "objection_responses": {"too expensive": "Consider the ROI"},+ },+ "icp": {+ "industries": ["SaaS"],+ "company_size": "10-200",+ "titles": ["VP of Sales"],+ "geography": ["US"],+ },+ }+ config = HarveyConfig(**data)+ assert config.persona.name == "Harvey"+ assert config.product.name == "Widget"+ assert config.icp.industries == ["SaaS"]+ assert config.channels.email.max_daily_sends == 50 # default+ assert config.usage.heartbeat_interval_minutes == 15 # default+++def test_env_config_defaults():+ """EnvConfig has sensible defaults when env vars are unset."""+ env = EnvConfig()+ assert env.instantly_api_key == ""+ assert env.serper_api_key == ""+++def test_offer_config_defaults():+ """OfferConfig defaults to book_call via calendar_link."""+ data = {+ "persona": {"name": "H", "company": "A", "role": "B", "email": "e", "linkedin": "", "tone": "t"},+ "product": {"name": "P", "description": "D", "pricing": "$1", "key_benefits": [], "objection_responses": {}},+ "icp": {"industries": [], "company_size": "", "titles": [], "geography": []},+ }+ config = HarveyConfig(**data)+ assert config.product.offer.goal == "book_call"+ assert config.product.offer.booking_method == "calendar_link"+ assert config.product.offer.meeting_duration == "15 minutes"diff --git a/tests/test_models.py b/tests/test_models.pynew file mode 100644index 0000000..3c61f74--- /dev/null+++ b/tests/test_models.py@@ -0,0 +1,62 @@+"""Tests for data models."""++from harvey.models.prospect import Prospect+from harvey.models.campaign import Campaign, EmailStep+from harvey.models.company import Company+from harvey.models.conversation import Conversation, Message+++def test_prospect_is_valid():+ """Prospect requires first_name, last_name, and title."""+ p = Prospect(first_name="Jane", last_name="Doe", title="VP of Sales")+ assert p.is_valid()+++def test_prospect_invalid_missing_title():+ p = Prospect(first_name="Jane", last_name="Doe")+ assert not p.is_valid()+++def test_prospect_invalid_missing_name():+ p = Prospect(title="VP of Sales")+ assert not p.is_valid()+++def test_prospect_full_name():+ p = Prospect(first_name="Jane", last_name="Doe", title="VP")+ assert p.full_name() == "Jane Doe"+++def test_campaign_sequence_json_round_trip():+ steps = [+ EmailStep(step=1, subject="Hi", body="Hello there", delay_days=0),+ EmailStep(step=2, subject="Follow up", body="Just checking in", delay_days=3),+ ]+ c = Campaign(id="", name="Test", channel="email", sequence=steps, prospect_ids=["p1", "p2"])+ json_str = c.sequence_json()+ restored = Campaign.sequence_from_json(json_str)+ assert len(restored) == 2+ assert restored[0].subject == "Hi"+ assert restored[1].delay_days == 3+++def test_company_defaults():+ c = Company(name="Acme", domain="acme.com")+ assert c.website == ""+ assert c.industry == ""+++def test_conversation_thread_json_round_trip():+ msgs = [+ Message(sender="harvey", content="Hi there"),+ Message(sender="prospect", content="Interested!"),+ ]+ convo = Conversation(+ id="", prospect_id="p1", campaign_id="c1", channel="email",+ thread=msgs, intent="interested", status="open",+ )+ json_str = convo.thread_json()+ restored = Conversation.thread_from_json(json_str)+ assert len(restored) == 2+ assert restored[0].sender == "harvey"+ assert restored[1].content == "Interested!"diff --git a/tests/test_state.py b/tests/test_state.pynew file mode 100644index 0000000..d0d36e7--- /dev/null+++ b/tests/test_state.py@@ -0,0 +1,115 @@+"""Tests for state management (SQLite operations)."""++import asyncio+import tempfile+import os++import pytest+import pytest_asyncio++from harvey.state import StateManager+from harvey.models.prospect import Prospect+from harvey.models.company import Company+++@pytest_asyncio.fixture+async def state():+ """Create a StateManager with a temp database."""+ with tempfile.TemporaryDirectory() as tmpdir:+ db_path = os.path.join(tmpdir, "test.db")+ sm = StateManager(db_path)+ await sm.init_db()+ yield sm+++async def test_add_and_get_company(state):+ company = Company(name="Acme", domain="acme.com", industry="SaaS")+ company_id = await state.add_company(company)+ assert company_id++ fetched = await state.get_company_by_domain("acme.com")+ assert fetched is not None+ assert fetched.name == "Acme"+++async def test_company_exists(state):+ company = Company(name="Acme", domain="acme.com")+ await state.add_company(company)+ assert await state.company_exists("acme.com")+ assert not await state.company_exists("notreal.com")+++async def test_add_and_get_prospect(state):+ p = Prospect(+ first_name="Jane", last_name="Doe", email="[email protected]",+ title="VP Sales", status="new",+ )+ prospect_id = await state.add_prospect(p)+ assert prospect_id++ assert await state.prospect_exists(email="[email protected]")+ assert not await state.prospect_exists(email="[email protected]")+++async def test_get_prospect_by_email(state):+ p = Prospect(+ first_name="Jane", last_name="Doe", email="[email protected]",+ title="VP Sales",+ )+ await state.add_prospect(p)++ found = await state.get_prospect_by_email("[email protected]")+ assert found is not None+ assert found.first_name == "Jane"++ not_found = await state.get_prospect_by_email("[email protected]")+ assert not_found is None+++async def test_prospect_status_update(state):+ p = Prospect(first_name="Jane", last_name="Doe", email="[email protected]", title="VP")+ pid = await state.add_prospect(p)+ await state.update_prospect_status(pid, "contacted")++ prospects = await state.get_prospects_by_status("contacted")+ assert len(prospects) == 1+ assert prospects[0].status == "contacted"+++async def test_usage_tracking(state):+ """Usage increment should use UPSERT, not insert duplicate rows."""+ await state.increment_usage()+ await state.increment_usage()+ await state.increment_usage()++ count = await state.get_usage_today()+ assert count == 3+++async def test_reply_deduplication(state):+ assert not await state.is_reply_processed("reply-123")+ await state.mark_reply_processed("reply-123")+ assert await state.is_reply_processed("reply-123")+ # Marking again should not error+ await state.mark_reply_processed("reply-123")+++async def test_contacts_for_company(state):+ company = Company(name="Acme", domain="acme.com")+ cid = await state.add_company(company)++ p1 = Prospect(first_name="Jane", last_name="Doe", email="[email protected]", title="VP", company_id=cid)+ p2 = Prospect(first_name="John", last_name="Doe", email="[email protected]", title="Dir", company_id=cid)+ await state.add_prospect(p1)+ await state.add_prospect(p2)++ contacts = await state.get_contacts_for_company(cid)+ assert len(contacts) == 2