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.
Add conversation stages, analyst agent, dedup, parallel execution
Ethand0b1e06880a6
diff --git a/harvey/agents/analyst.py b/harvey/agents/analyst.pyindex ae0f6d2..4629ffc 100644--- a/harvey/agents/analyst.py+++ b/harvey/agents/analyst.py@@ -1,20 +1,140 @@-"""Analyst — learns from outcomes. Placeholder for future implementation."""+"""Analyst — tracks performance and identifies what's working."""+import jsonimport logging+from datetime import datetime+from pathlib import Path++from harvey.state import StateManagerlogger = 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+ """Analyzes campaign performance, reply rates, and ICP segment conversion.++ Runs during idle cycles and writes a report to data/analytics.json."""+ def __init__(self, state: StateManager):+ self.state = state+async def run(self):- logger.info("Analyst: Not yet implemented. Coming soon.")+ """Generate analytics report from current pipeline data."""+ logger.info("Analyst: Running performance analysis...")++ report = {+ "generated_at": datetime.utcnow().isoformat(),+ "pipeline": await self._pipeline_summary(),+ "campaigns": await self._campaign_performance(),+ "intents": await self._intent_breakdown(),+ "stages": await self._stage_breakdown(),+ "insights": [],+ }++ # Generate insights+ report["insights"] = self._generate_insights(report)++ # Write report+ data_dir = Path(self.state.db_path).parent+ report_path = data_dir / "analytics.json"+ with open(report_path, "w") as f:+ json.dump(report, f, indent=2)++ logger.info(f"Analyst: Report written to {report_path}")++ # Log key metrics+ pipeline = report["pipeline"]+ total = sum(pipeline.values())+ if total > 0:+ reply_rate = pipeline.get("replied", 0) / max(pipeline.get("contacted", 0), 1) * 100+ logger.info(+ f"Analyst: {total} prospects | "+ f"{pipeline.get('contacted', 0)} contacted | "+ f"Reply rate: {reply_rate:.1f}%"+ )++ for insight in report["insights"]:+ logger.info(f"Analyst: Insight — {insight}")++ async def _pipeline_summary(self) -> dict:+ """Count prospects by status."""+ return await self.state.count_prospects_by_status()++ async def _campaign_performance(self) -> list[dict]:+ """Get stats for each campaign."""+ return await self.state.get_campaign_stats()++ async def _intent_breakdown(self) -> dict:+ """Count replies by intent classification."""+ return await self.state.get_intent_distribution()++ async def _stage_breakdown(self) -> dict:+ """Count conversations by sales stage."""+ return await self.state.get_stage_distribution()++ def _generate_insights(self, report: dict) -> list[str]:+ """Derive actionable insights from the data."""+ insights = []+ pipeline = report["pipeline"]+ intents = report["intents"]+ campaigns = report["campaigns"]++ # Pipeline health+ total_contacted = pipeline.get("contacted", 0)+ total_replied = pipeline.get("replied", 0)+ total_interested = intents.get("interested", 0)+ total_objections = intents.get("objection", 0)+ total_not_interested = intents.get("not_interested", 0)++ if total_contacted > 10:+ reply_rate = total_replied / total_contacted * 100+ if reply_rate < 5:+ insights.append(+ f"Reply rate is low ({reply_rate:.1f}%). "+ "Consider testing different subject lines or email frameworks."+ )+ elif reply_rate > 15:+ insights.append(+ f"Reply rate is strong ({reply_rate:.1f}%). "+ "Current messaging is resonating well."+ )++ # Objection patterns+ total_replies = sum(intents.values()) if intents else 0+ if total_replies > 5:+ objection_pct = total_objections / total_replies * 100+ if objection_pct > 40:+ insights.append(+ f"{objection_pct:.0f}% of replies are objections. "+ "Review objection handling skills or adjust targeting."+ )++ # Interest conversion+ if total_interested > 0 and total_contacted > 0:+ interest_rate = total_interested / total_contacted * 100+ insights.append(+ f"Interest rate: {interest_rate:.1f}% of contacted prospects show interest."+ )++ # Campaign comparison+ if len(campaigns) >= 2:+ best = max(campaigns, key=lambda c: c.get("reply_rate", 0))+ if best.get("reply_rate", 0) > 0:+ insights.append(+ f"Best performing campaign: '{best['name']}' "+ f"with {best['reply_rate']}% reply rate."+ )++ # Pipeline bottleneck+ stages = report["stages"]+ if stages.get("engaged", 0) > 3 and stages.get("closing", 0) == 0:+ insights.append(+ "Prospects are engaging but none are reaching the closing stage. "+ "The handler may need to be more assertive about proposing meetings."+ )++ if not insights:+ insights.append("Not enough data yet. Keep prospecting and sending campaigns.")++ return insightsdiff --git a/harvey/agents/handler.py b/harvey/agents/handler.pyindex 7bee143..6357648 100644--- a/harvey/agents/handler.py+++ b/harvey/agents/handler.py@@ -138,16 +138,21 @@ class Handler:intent=intent,)+ # 2b. Advance conversation stage based on intent+ new_stage = self._determine_stage(intent, convo.stage, reply_text)+ if new_stage != convo.stage:+ await self.state.update_conversation(convo.id, stage=new_stage)+ convo.stage = new_stage+ logger.info(f"Handler: Stage for {lead_email}: {convo.stage} → {new_stage}")+# 3. Generate and send response based on intentif intent == "not_interested":- # Graceful exit — no response needed, mark as closed- await self.state.update_conversation(convo.id, status="closed")+ await self.state.update_conversation(convo.id, status="closed", stage="closed_lost")await self.state.update_prospect_status(prospect.id, "lost")logger.info(f"Handler: {lead_email} not interested. Closing.")returnif intent == "ooo":- # Don't respond, let the sequence continue laterlogger.info(f"Handler: {lead_email} is OOO. Will follow up later.")return@@ -207,6 +212,49 @@ Respond with ONLY the category label, nothing else."""return intent+ def _determine_stage(self, intent: str, current_stage: str, reply_text: str) -> str:+ """Advance the conversation stage based on intent and context."""+ text_lower = reply_text.lower()++ # Terminal states+ if intent == "not_interested":+ return "closed_lost"++ # Stage advancement rules+ if intent == "interested":+ if current_stage == "initial_outreach":+ return "engaged"+ if current_stage == "engaged":+ # Check if they're asking about specifics → qualifying+ if any(w in text_lower for w in ["price", "cost", "how much", "pricing", "demo", "trial"]):+ return "presenting"+ return "qualifying"+ if current_stage in ("qualifying", "presenting"):+ return "negotiating"+ if current_stage == "negotiating":+ return "closing"++ if intent == "objection":+ # Objections typically happen during presenting or negotiating+ if current_stage in ("initial_outreach", "engaged"):+ return "qualifying"+ # Stay in current stage during objection handling++ if intent == "question":+ if current_stage == "initial_outreach":+ return "engaged"+ if current_stage == "engaged":+ return "qualifying"++ if intent == "wrong_person":+ return current_stage # Don't advance++ # Check for meeting/call signals+ if any(w in text_lower for w in ["let's meet", "schedule", "calendar", "book a call", "free on", "available"]):+ return "closing"++ return current_stage+async def _generate_response(self, intent: str, reply_text: str, prospect, convo: Conversation) -> str:diff --git a/harvey/agents/scout.py b/harvey/agents/scout.pyindex 4a01367..5903a4a 100644--- a/harvey/agents/scout.py+++ b/harvey/agents/scout.py@@ -490,7 +490,12 @@ class Scout:email = foundemail_verified = True- if email and await self.state.prospect_exists(email=email):+ if await self.state.prospect_exists(+ email=email,+ first_name=first_name,+ last_name=last_name,+ company=company["name"],+ ):continueprospect = Prospect(diff --git a/harvey/main.py b/harvey/main.pyindex acf93b0..3b2af3d 100644--- a/harvey/main.py+++ b/harvey/main.py@@ -109,11 +109,13 @@ async def heartbeat():from harvey.agents.writer import Writerfrom harvey.agents.sender import Senderfrom harvey.agents.handler import Handler+ from harvey.agents.analyst import Analystscout = Scout(brain, state, config, env)writer = Writer(brain, state, config)sender = Sender(brain, state, config, env)handler = Handler(brain, state, config, env)+ analyst = Analyst(state)interval = config.usage.heartbeat_interval_minutes * 60max_calls = int(200 * (config.usage.max_daily_claude_percent / 100))@@ -136,20 +138,41 @@ async def heartbeat():# 3. Decide what to dologger.info("Thinking about what to do next...")+ summary = await state.get_state_summary()action = await decide_next_action(brain, state, config)- logger.info(f"Decision: {action}")-- # 4. Execute- if action == "prospect":- await scout.run()+ logger.info(f"Primary action: {action}")++ # 4. Execute — run independent agents in parallel where possible+ # Handler is always safe to run alongside other agents+ tasks = []+ has_open_convos = summary.get("open_conversations", 0) > 0++ if action == "handle_replies":+ tasks.append(("handle_replies", handler.run()))+ elif action == "prospect":+ tasks.append(("prospect", scout.run()))+ # Also handle replies in parallel if needed+ if has_open_convos:+ tasks.append(("handle_replies", handler.run()))elif action == "write_campaign":- await writer.run()+ tasks.append(("write_campaign", writer.run()))+ if has_open_convos:+ tasks.append(("handle_replies", handler.run()))elif action == "send_campaign":- await sender.run()- elif action == "handle_replies":- await handler.run()+ tasks.append(("send_campaign", sender.run()))elif action == "idle":- logger.info("Nothing to do. Waiting for next cycle.")+ tasks.append(("analyze", analyst.run()))++ if len(tasks) > 1:+ logger.info(f"Running {len(tasks)} agents in parallel: {[t[0] for t in tasks]}")++ # Run all tasks, catch errors per-task+ results = await asyncio.gather(+ *[t[1] for t in tasks], return_exceptions=True+ )+ for (name, _), result in zip(tasks, results):+ if isinstance(result, Exception):+ logger.error(f"Agent {name} failed: {result}")# 5. Log the actionawait state.log_action(action_type=action, agent="main")diff --git a/harvey/models/conversation.py b/harvey/models/conversation.pyindex 82dfb6a..575f6a4 100644--- a/harvey/models/conversation.py+++ b/harvey/models/conversation.py@@ -12,6 +12,19 @@ class Message(BaseModel):timestamp: datetime = Field(default_factory=datetime.utcnow)+# Sales stages: tracks where the deal is in the pipeline+STAGES = [+ "initial_outreach", # first emails sent, no reply yet+ "engaged", # prospect replied positively+ "qualifying", # assessing fit (budget, authority, need, timing)+ "presenting", # sharing product details, case studies+ "negotiating", # discussing terms, pricing, objections+ "closing", # moving toward a meeting or deal+ "closed_won", # meeting booked or deal closed+ "closed_lost", # prospect said no or went dark+]++class Conversation(BaseModel):id: strprospect_id: str@@ -19,6 +32,7 @@ class Conversation(BaseModel):channel: str = "email"thread: list[Message] = []intent: str = "" # interested/objection/not_interested/ooo/wrong_person+ stage: str = "initial_outreach" # sales pipeline stagestatus: str = "open" # open/replied/meeting_booked/closedcreated_at: datetime = Field(default_factory=datetime.utcnow)updated_at: datetime = Field(default_factory=datetime.utcnow)diff --git a/harvey/state.py b/harvey/state.pyindex 4a812f2..9e35b09 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -87,6 +87,7 @@ class StateManager:channel TEXT DEFAULT 'email',thread_json TEXT DEFAULT '[]',intent TEXT DEFAULT '',+ stage TEXT DEFAULT 'initial_outreach',status TEXT DEFAULT 'open',created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP@@ -281,7 +282,10 @@ class StateManager:d["phone_verified"] = bool(d.get("phone_verified", 0))return Prospect(**d)- async def prospect_exists(self, email: str = "", linkedin_url: str = "") -> bool:+ async def prospect_exists(+ self, email: str = "", linkedin_url: str = "",+ first_name: str = "", last_name: str = "", company: str = "",+ ) -> bool:async with aiosqlite.connect(self.db_path) as db:if email:async with db.execute(@@ -295,6 +299,14 @@ class StateManager:) as cursor:if await cursor.fetchone():return True+ # Name + company dedup (case-insensitive)+ if first_name and last_name and company:+ async with db.execute(+ "SELECT 1 FROM prospects WHERE LOWER(first_name) = ? AND LOWER(last_name) = ? AND LOWER(company) = ?",+ (first_name.lower(), last_name.lower(), company.lower()),+ ) as cursor:+ if await cursor.fetchone():+ return Truereturn Falseasync def count_prospects_by_status(self) -> dict[str, int]:@@ -418,12 +430,12 @@ class StateManager:await db.execute("""INSERT INTO conversations(id, prospect_id, campaign_id, channel, thread_json,- intent, status, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ intent, stage, 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.stage, convo.status, convo.created_at.isoformat(),convo.updated_at.isoformat(),),)@@ -463,6 +475,57 @@ class StateManager:)await db.commit()+ # ── Analytics ──++ async def get_campaign_stats(self) -> list[dict]:+ """Get performance stats for each campaign."""+ async with aiosqlite.connect(self.db_path) as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ """SELECT c.id, c.name, c.status, c.prospect_ids_json,+ (SELECT COUNT(*) FROM conversations+ WHERE campaign_id = c.id) as reply_count,+ (SELECT COUNT(*) FROM conversations+ WHERE campaign_id = c.id AND intent = 'interested') as interested_count,+ (SELECT COUNT(*) FROM conversations+ WHERE campaign_id = c.id AND intent = 'objection') as objection_count,+ (SELECT COUNT(*) FROM conversations+ WHERE campaign_id = c.id AND intent = 'not_interested') as not_interested_count+ FROM campaigns c+ WHERE c.status IN ('active', 'completed')+ ORDER BY c.created_at DESC"""+ ) as cursor:+ rows = await cursor.fetchall()+ stats = []+ for r in rows:+ d = dict(r)+ prospect_ids = json.loads(d.get("prospect_ids_json", "[]"))+ d["leads_count"] = len(prospect_ids)+ d["reply_rate"] = (+ round(d["reply_count"] / len(prospect_ids) * 100, 1)+ if prospect_ids else 0+ )+ stats.append(d)+ return stats++ async def get_intent_distribution(self) -> dict[str, int]:+ """Count conversations by intent."""+ async with aiosqlite.connect(self.db_path) as db:+ async with db.execute(+ "SELECT intent, COUNT(*) FROM conversations WHERE intent != '' GROUP BY intent"+ ) as cursor:+ rows = await cursor.fetchall()+ return {row[0]: row[1] for row in rows}++ async def get_stage_distribution(self) -> dict[str, int]:+ """Count conversations by sales stage."""+ async with aiosqlite.connect(self.db_path) as db:+ async with db.execute(+ "SELECT stage, COUNT(*) FROM conversations WHERE stage != '' GROUP BY stage"+ ) as cursor:+ rows = await cursor.fetchall()+ return {row[0]: row[1] for row in rows}+# ── Usage Tracking ──async def get_usage_today(self) -> int:diff --git a/prompts/handler.md b/prompts/handler.mdindex 409c489..3b4f921 100644--- a/prompts/handler.md+++ b/prompts/handler.md@@ -1,5 +1,14 @@You are Harvey, responding to replies from prospects. Every reply is an opportunity.+Current conversation stage: {{stage}}++Stage-specific behavior:+- INITIAL_OUTREACH/ENGAGED: Build rapport. Don't pitch. Ask about their challenges.+- QUALIFYING: Understand their needs. Ask BANT questions naturally (not like a checklist).+- PRESENTING: Share relevant details about how we help. Use specific examples.+- NEGOTIATING: Address concerns directly. Be transparent about pricing/terms.+- CLOSING: Propose a meeting with specific times. Make it easy to say yes.+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.