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.
Harden Harvey: fix verified-email/reply-reprocessing/double-send bugs, XSS + SQL injection, add opt-out handling, deterministic decisions, WAL + migrations, dashboard overhaul, 84-test suite
Ethan521b4677908e
diff --git a/.env.example b/.env.exampleindex a76995a..051dd55 100644--- a/.env.example+++ b/.env.example@@ -1,23 +1,54 @@-# Instantly API-INSTANTLY_API_KEY=your_instantly_api_key_here+# ============================================================+# Harvey environment variables+# Copy this file to .env and fill in your values: cp .env.example .env+# Never commit .env — it is gitignored.+# Only INSTANTLY_API_KEY is required. Everything else is optional.+# ============================================================-# LinkedIn (for browser automation)-LINKEDIN_EMAIL=your_linkedin_email-LINKEDIN_PASSWORD=your_linkedin_password+# ------------------------------------------------------------+# Instantly — cold email sending platform [REQUIRED]+# Where to get it: https://app.instantly.ai → Settings → Integrations → API Keys+# Note: API access requires Instantly's Growth plan or higher.+# Used by: Sender agent (deploy campaigns), Handler agent (read replies).+INSTANTLY_API_KEY=-# Cloudflare Browser Rendering (for deep website crawling during training)-# $5/mo paid plan = ~12,000 pages/month. Free plan available with limits.-# Get credentials at: https://dash.cloudflare.com → Workers & Pages → Browser Rendering-CLOUDFLARE_ACCOUNT_ID=your_account_id_here-CLOUDFLARE_API_TOKEN=your_api_token_here+# ------------------------------------------------------------+# LinkedIn — browser-automation prospecting [OPTIONAL]+# These are the credentials of the LinkedIn account Harvey will log into+# with Playwright. WARNING: automation violates LinkedIn's Terms of Service+# and can get the account restricted or banned. Use a account you can+# afford to lose, keep the default rate limits, or leave blank to skip —+# Harvey will prospect via web search and company websites instead.+LINKEDIN_EMAIL=+LINKEDIN_PASSWORD=-# Hunter.io (optional, free tier = 50 lookups/mo)-HUNTER_API_KEY=your_hunter_api_key_here+# ------------------------------------------------------------+# Cloudflare Browser Rendering — deep website crawling during training [OPTIONAL]+# Enables JS-rendered crawling of your own site when running `harvey train`.+# Where to get it:+# Account ID: https://dash.cloudflare.com → right sidebar of any zone, or the URL+# API Token: https://dash.cloudflare.com/profile/api-tokens → Create Token+# → grant "Browser Rendering: Edit" permission+# Cost: ~$5/mo on the paid Workers plan (~12,000 pages). Free tier has limits.+# Without these, Harvey uses its built-in HTTP crawler (no JS rendering).+CLOUDFLARE_ACCOUNT_ID=+CLOUDFLARE_API_TOKEN=-# 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+# ------------------------------------------------------------+# Hunter.io — email discovery/verification fallback [OPTIONAL]+# Where to get it: https://hunter.io → sign up → API → API Keys+# Free tier: 50 lookups/month. Used when pattern + SMTP verification+# can't confirm a prospect's email address.+HUNTER_API_KEY=-# Calendar (later)-# CALENDLY_API_KEY=your_calendly_api_key_here+# ------------------------------------------------------------+# Serper.dev — Google Search API for prospecting [OPTIONAL, recommended]+# Where to get it: https://serper.dev → sign up → Dashboard → API Key+# Cost: ~$5 for 2,500 searches (no subscription). The most reliable search+# backend; without it Harvey falls back to DuckDuckGo/Bing scraping,+# which can be rate-limited.+SERPER_API_KEY=++# ------------------------------------------------------------+# Calendly — meeting auto-booking [NOT YET USED — roadmap]+# CALENDLY_API_KEY=diff --git a/Dockerfile b/Dockerfileindex 5e23c12..9aec13e 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,30 +1,45 @@FROM python:3.12-slim-# Install system dependencies+ENV PYTHONUNBUFFERED=1 \+ PYTHONDONTWRITEBYTECODE=1 \+ PIP_NO_CACHE_DIR=1 \+ PLAYWRIGHT_BROWSERS_PATH=/ms-playwright++# System deps (curl needed for the Claude CLI installer)RUN apt-get update && apt-get install -y --no-install-recommends \- curl \+ curl ca-certificates \&& 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+# Python deps first (cached layer — rebuilds only when requirements change),+# then Chromium + its system libraries in the same layer cleanup pass.COPY requirements.txt .-RUN pip install --no-cache-dir -r requirements.txt--# Copy project-COPY harvey/ harvey/-COPY prompts/ prompts/-COPY skills/ skills/-COPY harvey.yaml .+RUN pip install --no-cache-dir -r requirements.txt \+ && playwright install --with-deps chromium \+ && rm -rf /var/lib/apt/lists/* /root/.cache++# Non-root user; owns app data and the shared browser install+RUN useradd --create-home --uid 1000 harvey \+ && mkdir -p /app/data \+ && chown -R harvey:harvey /app /ms-playwright++# Copy project (config/prompts are typically bind-mounted over these at runtime)+COPY --chown=harvey:harvey harvey/ harvey/+COPY --chown=harvey:harvey prompts/ prompts/+COPY --chown=harvey:harvey skills/ skills/+COPY --chown=harvey:harvey harvey.yaml .++USER harvey+ENV PATH="/home/harvey/.local/bin:${PATH}"++# Claude Code CLI, installed as the runtime user so ~/.local/bin is correct.+# `|| true` keeps the build working offline; the CLI is required at runtime.+RUN curl -fsSL https://claude.ai/install.sh | sh || true-# Create data directory-RUN mkdir -p /app/data+# Healthy = the heartbeat loop has touched the database recently+# (2h window tolerates long heartbeat intervals and quiet-hour idling).+HEALTHCHECK --interval=5m --timeout=10s --start-period=3m --retries=3 \+ CMD python -c "import os,sys,time; p='/app/data/harvey.db'; sys.exit(0 if os.path.exists(p) and time.time()-os.path.getmtime(p) < 7200 else 1)"-# Run HarveyCMD ["python", "-m", "harvey.main"]diff --git a/README.md b/README.mdindex 8370b4a..f65cf8e 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@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.+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. It ships with compliant defaults — hard opt-out handling, send limits, honest-identity rules — because outreach that gets your domain blacklisted isn't outreach. Read [Legal & Deliverability](#legal--deliverability-read-this-before-sending-anything) before your first campaign.```$ python -m harvey@@ -125,16 +125,16 @@ Quiet hours are also configurable. Harvey won't run between 10pm and 7am (or wha----## Quick Start+## Quick Start (5 Minutes)### Prerequisites-- [Claude Code CLI](https://claude.ai/download) installed and authenticated (with a Max subscription)+- [Claude Code CLI](https://claude.ai/download) installed and authenticated (`claude login`) with a Max subscription- Python 3.11+-- An [Instantly](https://instantly.ai) account with API access (for cold email)-- A LinkedIn account (for prospecting — optional)+- An [Instantly](https://instantly.ai) account with API access — Growth plan or higher (for cold email)+- A LinkedIn account (for prospecting — optional, and see the [ToS warning](#legal--deliverability-read-this-before-sending-anything) below)-### 1. Clone and Open in Claude+### Option A — Let Claude set you up (easiest)```bashgit clone https://github.com/ethanplusai/harvey.git@@ -142,15 +142,29 @@ cd harveyclaude```-That's it. Claude reads the project, sees it's unconfigured, and walks you through everything — installs dependencies, connects your email platform, trains on your product, and gets Harvey running. Just follow along.+Claude reads the project, sees it's unconfigured, and walks you through everything — installs dependencies, connects your email platform, trains on your product, and gets Harvey running. Just follow along.-### 2. Run Harvey (after setup)--Once configured, start Harvey anytime:+### Option B — Manual (still 5 minutes)```bash+# 1. Clone and install (~1 min)+git clone https://github.com/ethanplusai/harvey.gitcd harvey-source .venv/bin/activate+python3 -m venv .venv && source .venv/bin/activate+pip install -e .+python -m playwright install chromium # only needed for LinkedIn prospecting++# 2. Add your API keys (~1 min)+cp .env.example .env+# Edit .env — only INSTANTLY_API_KEY is required; every variable is+# documented inline with where to get it.++# 3. Run the interactive setup wizard (~3 min)+# Checks prerequisites, tests your keys, and trains Harvey on your+# product (point it at your website and it teaches itself).+harvey setup++# 4. Start closingharvey run```@@ -232,7 +246,7 @@ After setup, Harvey writes all config files for you. Just run `harvey run` to stTo re-run setup anytime: `harvey setup`-### 4. Deploy (VPS)+### Deploy to a VPS (always-on)For always-on operation, deploy with Docker:@@ -392,6 +406,63 @@ Harvey stores everything in SQLite (`data/harvey.db`):---+## Legal & Deliverability (Read This Before Sending Anything)++Harvey automates outreach, but **you are the sender**. Cold email is legal in most places when done right and expensive when done wrong (CAN-SPAM fines run to $53,088 *per email*). Harvey ships with compliant defaults — keep them.++### The law, in practice++**CAN-SPAM (US)** — every commercial email must have:+- A truthful subject line and accurate from-name/address (Harvey's copywriting rules enforce this — no fake "re:" threads, no impersonation)+- A working unsubscribe mechanism, honored within 10 business days (Harvey treats any opt-out wording — "stop", "remove me", "unsubscribe" — as immediate and permanent)+- Your valid physical mailing address in the footer — **enable this in your Instantly campaign settings before launching**++**GDPR / PECR (EU & UK)** — B2B cold email requires a defensible *legitimate interest*: the pitch must be genuinely relevant to the recipient's professional role. You must be able to say where you got their data, and objecting must be effortless. If you can't articulate why a specific person would care, Harvey shouldn't email them — and its qualification rules say so.++**Bot disclosure** — some jurisdictions (e.g. California's B.O.T. Act) require disclosing automation in commercial communications. Harvey is instructed to *always* answer truthfully if a prospect asks whether they're talking to an AI. Never configure it otherwise.++**LinkedIn** — browser automation violates LinkedIn's Terms of Service and can get the account restricted or banned. This feature is off by default in the wizard; if you enable it, use conservative limits and an account you can afford to lose.++### Deliverability: warm up or burn out++Sending cold email from your main company domain, or at volume from day one, will land you in spam permanently. Before your first campaign:++1. **Buy a dedicated sending domain** (e.g. `getacme.com` instead of `acme.com`) so your primary domain's reputation is never at risk. Point it at your real site.+2. **Set up SPF, DKIM, and DMARC** on the sending domain. Instantly's docs walk you through it; without all three, Gmail and Outlook will junk you.+3. **Warm up for 2–4 weeks** before real volume. Instantly has built-in warmup — turn it on and leave it on.+4. **Ramp slowly**: start at 10–20 emails/day per inbox, add ~5/day. Harvey's default `max_daily_sends: 50` is a ceiling, not a starting point.+5. **Watch bounce and spam rates.** Bounce rate above ~3% or any spam complaints: pause, fix your list quality, ramp again. Harvey verifies emails before sending to keep bounces low, but the platform metrics are your ground truth.++None of this is legal advice — if you're sending at scale or into regulated industries, talk to a lawyer.++---++## Troubleshooting & FAQ++**`command not found: harvey`** — Activate the venv first: `source .venv/bin/activate`. If you installed with `pip install -e .` inside the venv, the `harvey` command lives there.++**`externally-managed-environment` on pip install** — You're using system Python. Create a venv: `python3 -m venv .venv && source .venv/bin/activate`.++**Claude headless mode fails / setup step 1 fails** — Run `claude login` and confirm your Max subscription is active. Test manually: `claude -p "say hi"`. In Docker, make sure `~/.claude` is mounted into the container (see `docker-compose.yml`).++**Instantly API returns 401** — Wrong key, or your plan doesn't include API access (requires Growth or higher). Regenerate the key under Settings → Integrations → API Keys.++**Emails land in spam** — Almost always a domain problem, not a copy problem. Check SPF/DKIM/DMARC, confirm warmup ran for 2+ weeks, and cut your daily volume in half. See [Legal & Deliverability](#legal--deliverability-read-this-before-sending-anything).++**Harvey isn't finding prospects / search is rate-limited** — Free search backends (DuckDuckGo, Bing) throttle aggressively. Add a `SERPER_API_KEY` (~$5 for 2,500 Google searches) to `.env` for reliable search.++**Training crawl finds almost nothing** — Your site is probably JavaScript-rendered. Add Cloudflare Browser Rendering credentials to `.env` (documented in `.env.example`) or fill in `harvey.yaml` manually via `harvey setup`.++**Harvey does nothing during the day** — Check `quiet_hours` and `timezone` in `harvey.yaml`, and whether it hit `max_daily_claude_percent`. `harvey status` shows current state; the `actions` table in `data/harvey.db` shows every decision it made.++**How do I stop Harvey immediately?** — `Ctrl+C` locally, or `docker compose down` on a VPS. Nothing sends while it's stopped; state is in SQLite so it resumes cleanly.++**Can I run it without LinkedIn?** — Yes. Leave the LinkedIn credentials blank and Harvey prospects via web search and company websites only. This is the recommended (and default) mode.++**Where does my data live?** — Everything is local: `data/harvey.db` (SQLite) plus your `.env` and `harvey.yaml`. Nothing is sent anywhere except to the APIs you configured.++---+## Roadmap- [x] Core heartbeat loopdiff --git a/docker-compose.yml b/docker-compose.ymlindex 9840099..c3a63fd 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -8,9 +8,13 @@ services:# 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+ - ./skills:/app/skills+ # Mount Claude auth (required for Max plan usage).+ # Not read-only: the CLI refreshes OAuth tokens in place.+ # The container runs as non-root user "harvey" (uid 1000).+ - ~/.claude:/home/harvey/.clauderestart: unless-stopped+ init: truelogging:driver: "json-file"options:diff --git a/harvey/__main__.py b/harvey/__main__.pyindex e8e094e..06cc245 100644--- a/harvey/__main__.py+++ b/harvey/__main__.py@@ -2,4 +2,5 @@from harvey.cli import main-main()+if __name__ == "__main__":+ main()diff --git a/harvey/agents/analyst.py b/harvey/agents/analyst.pyindex 4629ffc..a37d6be 100644--- a/harvey/agents/analyst.py+++ b/harvey/agents/analyst.py@@ -35,13 +35,18 @@ class Analyst:# Generate insightsreport["insights"] = self._generate_insights(report)- # Write report+ # Write report atomically (temp file + rename) so a crash mid-write+ # never leaves a corrupt analytics.json for the dashboard to choke on.data_dir = Path(self.state.db_path).parentreport_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}")+ try:+ tmp_path = report_path.with_suffix(".json.tmp")+ with open(tmp_path, "w") as f:+ json.dump(report, f, indent=2)+ tmp_path.replace(report_path)+ logger.info(f"Analyst: Report written to {report_path}")+ except OSError as e:+ logger.error(f"Analyst: Failed to write report: {e}")# Log key metricspipeline = report["pipeline"]@@ -74,64 +79,106 @@ class Analyst:return await self.state.get_stage_distribution()def _generate_insights(self, report: dict) -> list[str]:- """Derive actionable insights from the data."""+ """Derive actionable insights from the data.++ Every insight names the metric, the threshold it crossed, and the+ specific file or config to change — so a human (or Harvey itself)+ can act on it without further analysis.+ """insights = []- pipeline = report["pipeline"]- intents = report["intents"]- campaigns = report["campaigns"]+ pipeline = report.get("pipeline") or {}+ intents = report.get("intents") or {}+ campaigns = report.get("campaigns") or []+ stages = report.get("stages") or {}# Pipeline health+ total_new = pipeline.get("new", 0)+ total_queued = pipeline.get("queued", 0)total_contacted = pipeline.get("contacted", 0)total_replied = pipeline.get("replied", 0)+ total_opted_out = pipeline.get("opted_out", 0)total_interested = intents.get("interested", 0)total_objections = intents.get("objection", 0)- total_not_interested = intents.get("not_interested", 0)+ total_unsubscribes = intents.get("unsubscribe", 0) + total_opted_out+ total_escalations = intents.get("escalate", 0)if total_contacted > 10:reply_rate = total_replied / total_contacted * 100if reply_rate < 5:insights.append(- f"Reply rate is low ({reply_rate:.1f}%). "- "Consider testing different subject lines or email frameworks."+ f"ACTION: Reply rate is low ({reply_rate:.1f}%, benchmark 5-10%). "+ "Rewrite email 1 in prompts/writer.md with a sharper observation, "+ "and test 2-3 new subject lines via skills/email_frameworks.md.")elif reply_rate > 15:insights.append(- f"Reply rate is strong ({reply_rate:.1f}%). "- "Current messaging is resonating well."+ f"KEEP: Reply rate is strong ({reply_rate:.1f}%). Don't change the "+ "current messaging. Scale prospecting to feed it more leads."+ )++ # Deliverability / reputation warning — the most urgent signal+ if total_contacted > 10:+ optout_rate = total_unsubscribes / total_contacted * 100+ if optout_rate > 2:+ insights.append(+ f"URGENT: Opt-out rate is {optout_rate:.1f}% (>2% risks blacklisting). "+ "Pause sending, tighten ICP targeting in harvey.yaml, and reduce "+ "max_daily_sends until the list quality improves.")+ if total_escalations > 0:+ insights.append(+ f"HUMAN NEEDED: {total_escalations} conversation(s) escalated (angry/legal). "+ "Review conversations with status 'needs_human' in the dashboard before "+ "any further sending to those domains."+ )+# Objection patternstotal_replies = sum(intents.values()) if intents else 0if total_replies > 5:objection_pct = total_objections / total_replies * 100if objection_pct > 40:insights.append(- f"{objection_pct:.0f}% of replies are objections. "- "Review objection handling skills or adjust targeting."+ f"ACTION: {objection_pct:.0f}% of replies are objections. Add the "+ "recurring objections to objection_responses in harvey.yaml and "+ "skills/objection_handling.md, or narrow targeting to better-fit accounts.")# Interest conversionif total_interested > 0 and total_contacted > 0:interest_rate = total_interested / total_contacted * 100insights.append(- f"Interest rate: {interest_rate:.1f}% of contacted prospects show interest."+ f"Interest rate: {interest_rate:.1f}% of contacted prospects show interest "+ f"({total_interested} of {total_contacted}).")- # Campaign comparison- if len(campaigns) >= 2:- best = max(campaigns, key=lambda c: c.get("reply_rate", 0))- if best.get("reply_rate", 0) > 0:+ # Campaign comparison — name winner AND loser so the fix is obvious+ rated = [c for c in campaigns if c.get("reply_rate") is not None]+ if len(rated) >= 2:+ best = max(rated, key=lambda c: c.get("reply_rate", 0))+ worst = min(rated, key=lambda c: c.get("reply_rate", 0))+ if best.get("reply_rate", 0) > 0 and best is not worst:insights.append(- f"Best performing campaign: '{best['name']}' "- f"with {best['reply_rate']}% reply rate."+ f"ACTION: '{best.get('name')}' ({best.get('reply_rate')}% replies) beats "+ f"'{worst.get('name')}' ({worst.get('reply_rate', 0)}%). Reuse the winner's "+ "angle and subject-line style for the next campaign; pause or rewrite the loser.")- # Pipeline bottleneck- stages = report["stages"]+ # Pipeline bottlenecksif 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."+ "ACTION: Prospects engage but none reach closing. Update prompts/handler.md "+ "CLOSING guidance to propose specific meeting times earlier (by message 2)."+ )+ if total_queued > 0 and total_contacted == 0:+ insights.append(+ f"BLOCKED: {total_queued} prospects are queued but nothing has been sent. "+ "Check the Instantly API key and Sender logs — campaigns may be failing to deploy."+ )+ if total_new < 10 and total_queued == 0:+ insights.append(+ f"ACTION: Prospect pool is nearly empty ({total_new} new). Scout should run "+ "next cycle; if it keeps coming up dry, broaden the ICP in harvey.yaml.")if not insights:diff --git a/harvey/agents/handler.py b/harvey/agents/handler.pyindex 6357648..79ad67d 100644--- a/harvey/agents/handler.py+++ b/harvey/agents/handler.py@@ -18,8 +18,52 @@ INTENT_LABELS = {"ooo","wrong_person","question",+ "unsubscribe",+ "escalate",}+# Intents that get an automated reply. Everything else is closed,+# deferred, or escalated to a human.+AUTO_REPLY_INTENTS = {"interested", "objection", "question", "wrong_person"}++# Hard opt-out phrases. If any of these appear, we ALWAYS honor the+# opt-out regardless of what the LLM classifier says.+OPT_OUT_PATTERNS = (+ "unsubscribe",+ "opt out",+ "opt-out",+ "remove me",+ "take me off",+ "stop emailing",+ "stop contacting",+ "stop sending",+ "do not contact",+ "do not email",+ "don't contact",+ "don't email",+ "never contact",+ "delete my info",+ "delete my data",+)++# Phrases that mean a human must take over. Never auto-reply to these.+ESCALATION_PATTERNS = (+ "lawyer",+ "attorney",+ "legal action",+ "lawsuit",+ "cease and desist",+ "harassment",+ "harassing",+ "report you",+ "reporting you",+ "spam complaint",+ "ftc",+ "gdpr",+ "can-spam",+ "blacklist",+)+class Handler:def __init__(@@ -33,6 +77,7 @@ class Handler:self.state = stateself.config = configself.instantly = InstantlyClient(env.instantly_api_key)+ self.skills = ""async def run(self):"""Check for new replies and handle them."""@@ -57,48 +102,59 @@ class Handler:continue# 2. Get replies from Instantly- replies = await self.instantly.get_replies(campaign.instantly_campaign_id)+ try:+ replies = await self.instantly.get_replies(campaign.instantly_campaign_id)+ except Exception as e:+ logger.error(f"Handler: Failed to fetch replies for {campaign.name}: {e}")+ continueif not replies:continuefor reply in replies:+ if not isinstance(reply, dict):+ continuetry:- await self._handle_reply(reply, campaign)- total_handled += 1+ handled = await self._handle_reply(reply, campaign)+ if handled:+ total_handled += 1except 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", ""))+ async def _handle_reply(self, reply: dict, campaign) -> bool:+ """Process a single reply. Returns True if a new reply was handled."""+ lead_email = (reply.get("lead_email") or reply.get("from_email") or "").strip().lower()+ reply_text = (reply.get("body") or reply.get("text") or "").strip()+ reply_uuid = str(reply.get("uuid") or reply.get("id") or "")if not lead_email or not reply_text:- return+ return False# Dedup: skip if we already processed this replyif reply_uuid and await self.state.is_reply_processed(reply_uuid):logger.debug(f"Handler: Reply {reply_uuid} already processed. Skipping.")- return+ return Falselogger.info(f"Handler: Reply from {lead_email}")+ try:+ await self._process_reply(lead_email, reply_text, reply_uuid, campaign)+ finally:+ # ALWAYS mark processed — even on early exits (opt-out, OOO,+ # unknown prospect) — so the same reply is never re-handled+ # or double-replied on the next cycle.+ if reply_uuid:+ await self.state.mark_reply_processed(reply_uuid)+ return True++ async def _process_reply(self, lead_email: str, reply_text: str, reply_uuid: str, campaign):+ """Classify, record, and respond to a single reply."""# 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}")return@@ -106,8 +162,15 @@ class Handler:# Update prospect statusawait self.state.update_prospect_status(prospect.id, "replied")- # 1. Classify intent- intent = await self._classify_intent(reply_text, prospect)+ # 1. Classify intent. Hard keyword checks run FIRST and override+ # the LLM — opt-outs and legal threats must never be missed.+ text_lower = reply_text.lower()+ if any(p in text_lower for p in OPT_OUT_PATTERNS):+ intent = "unsubscribe"+ elif any(p in text_lower for p in ESCALATION_PATTERNS):+ intent = "escalate"+ else:+ intent = await self._classify_intent(reply_text, prospect)logger.info(f"Handler: Intent for {lead_email}: {intent}")# 2. Get or create conversation@@ -128,7 +191,7 @@ class Handler:intent=intent,status="open",)- await self.state.add_conversation(convo)+ convo.id = await self.state.add_conversation(convo)else:convo.thread.append(Message(sender="prospect", content=reply_text))convo.intent = intent@@ -141,21 +204,53 @@ class Handler:# 2b. Advance conversation stage based on intentnew_stage = self._determine_stage(intent, convo.stage, reply_text)if new_stage != convo.stage:+ logger.info(f"Handler: Stage for {lead_email}: {convo.stage} -> {new_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 intent+ # 3. Route based on intent+ if intent == "unsubscribe":+ # Honor opt-outs ALWAYS. No reply, no future contact.+ await self.state.update_conversation(convo.id, status="closed", stage="closed_lost")+ await self.state.update_prospect_status(prospect.id, "opted_out")+ await self.state.log_action(+ action_type="opt_out",+ agent="handler",+ details={"prospect_email": lead_email},+ )+ logger.info(f"Handler: {lead_email} opted out. Suppressed permanently. No reply sent.")+ return++ if intent == "escalate":+ # Angry / legal / compliance replies go to a human. Never auto-reply.+ await self.state.update_conversation(convo.id, status="needs_human")+ await self.state.log_action(+ action_type="escalation",+ agent="handler",+ details={+ "prospect_email": lead_email,+ "reply_preview": reply_text[:200],+ },+ )+ logger.warning(+ f"Handler: ESCALATED reply from {lead_email} — needs human review. No auto-reply sent."+ )+ return+if intent == "not_interested":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.")+ logger.info(f"Handler: {lead_email} not interested. Closing. One no is enough.")returnif intent == "ooo":logger.info(f"Handler: {lead_email} is OOO. Will follow up later.")return+ if intent not in AUTO_REPLY_INTENTS:+ logger.warning(f"Handler: No auto-reply policy for intent '{intent}'. Skipping reply.")+ return+# For interested, objection, question, wrong_person — generate a replyresponse = await self._generate_response(intent, reply_text, prospect, convo)if not response:@@ -184,48 +279,64 @@ 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:- "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+- "not_interested" — a clear no, not now, or "we're all set"+- "unsubscribe" — asks to stop being contacted, remove from list, opt out+- "escalate" — angry, hostile, threatens legal action, or mentions spam/compliance- "ooo" — out of office / auto-reply- "wrong_person" — not the right contact, suggests someone else- "question" — asking for more information before deciding+When in doubt between "not_interested" and "unsubscribe", choose "unsubscribe".+When in doubt between anything and "escalate", choose "escalate".+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+ if not result:+ # Classifier failed. Do NOT auto-reply blind — flag for a human.+ logger.warning("Handler: Intent classifier returned nothing. Escalating.")+ return "escalate"++ # Robust extraction: take the first recognized label anywhere in+ # the response (models sometimes add explanation despite instructions).+ cleaned = result.strip().strip('"').strip("'").lower()+ if cleaned in INTENT_LABELS:+ return cleaned+ for label in sorted(INTENT_LABELS, key=len, reverse=True):+ if label in cleaned:+ return label++ logger.warning(f"Handler: Unknown intent '{cleaned[:80]}'. Defaulting to 'question'.")+ return "question"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":+ if intent in ("not_interested", "unsubscribe"):return "closed_lost"+ if intent == "escalate":+ return current_stage # Human decides what happens next+# Stage advancement rulesif intent == "interested":+ # Meeting/call signals from an interested prospect → closing+ if any(w in text_lower for w in ["let's meet", "schedule", "calendar", "book a call", "free on", "available"]):+ return "closing"if current_stage == "initial_outreach":return "engaged"if current_stage == "engaged":- # Check if they're asking about specifics → qualifying+ # Check if they're asking about specifics → presentingif any(w in text_lower for w in ["price", "cost", "how much", "pricing", "demo", "trial"]):return "presenting"return "qualifying"@@ -246,13 +357,6 @@ Respond with ONLY the category label, nothing else."""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_stageasync def _generate_response(@@ -273,7 +377,7 @@ Respond with ONLY the category label, nothing else."""objection_context = f"\nSuggested approach for this objection: {response}"break- prompt = self.brain.load_prompt("handler")+ prompt = self.brain.load_prompt("handler", stage=convo.stage)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}@@ -318,7 +422,14 @@ Write a reply that:"""- 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."+ prompt += "\n\nWrite ONLY the email body. No subject line, no greeting label, no signature block, no markdown."response = await self.brain.think(prompt, session_id="harvey-handler")- return response.strip() if response else ""+ if not response:+ return ""+ response = response.strip()+ # Guard against the model returning meta-text instead of an email+ if response.lower().startswith(("i can't", "i cannot", "as an ai", "sorry,")):+ logger.warning("Handler: Model returned meta-text instead of an email. Discarding.")+ return ""+ return responsediff --git a/harvey/agents/scout.py b/harvey/agents/scout.pyindex 5903a4a..0040702 100644--- a/harvey/agents/scout.py+++ b/harvey/agents/scout.py@@ -13,6 +13,15 @@ Search backends (in priority order):Each cycle runs 2-3 queries max to avoid rate limits. Queries aretracked in the DB so they spread across heartbeat cycles.++Hardening notes:+- All outbound HTTP goes through ``_fetch`` which adds timeouts, retries+ with exponential backoff + jitter, rotating user-agents, and detection+ of rate-limit / block / captcha responses.+- Every parse path is defensive: malformed HTML or JSON never crashes a+ cycle, it just yields zero results for that source.+- Prospects and companies are deduplicated both against the DB and+ in-memory across every strategy within a cycle."""import asyncio@@ -20,7 +29,7 @@ import jsonimport loggingimport randomimport re-from urllib.parse import quote_plus, urlparse+from urllib.parse import parse_qs, quote_plus, urlparseimport httpxfrom bs4 import BeautifulSoup@@ -40,6 +49,48 @@ MAX_QUERIES_PER_CYCLE = 3# Delay between search requests (seconds)SEARCH_DELAY = (2, 5)+# HTTP hardening knobs+HTTP_TIMEOUT = 15.0+SCRAPE_TIMEOUT = 12.0+MAX_RETRIES = 3+BACKOFF_BASE = 1.5 # seconds; grows exponentially per attempt+MAX_RESULTS_PER_QUERY = 20+MAX_COMPANIES_PER_CYCLE = 10+MAX_PROSPECTS_PER_CYCLE = 25++# Rotate a small pool of realistic desktop user-agents. Scrapers that always+# send one UA are trivially fingerprinted and blocked.+USER_AGENTS = [+ "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",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 "+ "(KHTML, like Gecko) Version/17.1 Safari/605.1.15",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) "+ "Gecko/20100101 Firefox/122.0",+]++# Signals that a response is a block / bot-challenge rather than real content.+_BLOCK_MARKERS = (+ "unusual traffic",+ "captcha",+ "are you a robot",+ "verify you are human",+ "detected unusual activity",+ "access denied",+ "/sorry/index",+)++# Seniority / title vocabulary reused for ICP heuristics.+_SENIOR_KEYWORDS = (+ "ceo", "cto", "cfo", "cmo", "coo", "cro", "chief", "founder",+ "co-founder", "president", "owner", "partner", "vp", "vice president",+ "svp", "evp", "head of", "director",+)+class Scout:def __init__(@@ -55,6 +106,9 @@ class Scout:self.env = envself.skills = ""self._queries_this_cycle = 0+ # In-memory dedup guards, reset each cycle.+ self._seen_prospect_keys: set[str] = set()+ self._seen_domains: set[str] = set()async def run(self):"""Main prospecting flow: find leads matching ICP."""@@ -62,18 +116,23 @@ class Scout:self.skills = self.brain.load_skills_for_agent("scout")self._queries_this_cycle = 0+ self._seen_prospect_keys = set()+ self._seen_domains = set()prospects_found = 0- # Strategy 1: LinkedIn search (if enabled)+ # Each strategy is isolated so one failing does not abort the cycle.+ strategies = []if self.config.channels.linkedin.enabled and self.env.linkedin_email:- prospects_found += await self._prospect_via_linkedin()+ strategies.append(("linkedin", self._prospect_via_linkedin))+ strategies.append(("profile_search", self._prospect_via_profile_search))+ strategies.append(("company_discovery", self._prospect_via_company_discovery))- # Strategy 2: Search for LinkedIn profiles via web search- prospects_found += await self._prospect_via_profile_search()-- # Strategy 3: Discover companies, then scrape team pages- prospects_found += await self._prospect_via_company_discovery()+ for name, strategy in strategies:+ try:+ prospects_found += await strategy()+ except Exception as e:+ logger.warning(f"Scout: strategy '{name}' failed: {e}")await self.state.log_action(action_type="prospect",@@ -82,6 +141,141 @@ class Scout:)logger.info(f"Scout: Found {prospects_found} new prospects this cycle.")+ # ── Prospect dedup helpers ──++ def _prospect_key(self, prospect: Prospect) -> str:+ """Stable identity key so we never emit the same person twice."""+ if prospect.email:+ return f"email:{prospect.email.lower().strip()}"+ if prospect.linkedin_url:+ # Normalise LinkedIn URLs (strip protocol/query/trailing slash).+ u = prospect.linkedin_url.lower().split("?")[0].rstrip("/")+ u = re.sub(r"^https?://(www\.)?", "", u)+ return f"li:{u}"+ return (+ f"name:{prospect.first_name.lower().strip()}"+ f"|{prospect.last_name.lower().strip()}"+ f"|{prospect.company.lower().strip()}"+ )++ async def _is_duplicate_prospect(self, prospect: Prospect) -> bool:+ """True if we've already seen this prospect this cycle or in the DB."""+ key = self._prospect_key(prospect)+ if key in self._seen_prospect_keys:+ return True+ try:+ if await self.state.prospect_exists(+ email=prospect.email,+ linkedin_url=prospect.linkedin_url,+ first_name=prospect.first_name,+ last_name=prospect.last_name,+ company=prospect.company,+ ):+ self._seen_prospect_keys.add(key)+ return True+ except Exception as e:+ logger.debug(f"prospect_exists check failed: {e}")+ return False++ def _remember_prospect(self, prospect: Prospect):+ self._seen_prospect_keys.add(self._prospect_key(prospect))++ # ── Central HTTP layer (timeouts, retries, backoff, UA rotation) ──++ def _headers(self, extra: dict | None = None) -> dict:+ headers = {+ "User-Agent": random.choice(USER_AGENTS),+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language": "en-US,en;q=0.9",+ }+ if extra:+ headers.update(extra)+ return headers++ @staticmethod+ def _looks_blocked(text: str) -> bool:+ if not text:+ return False+ low = text[:4000].lower()+ return any(marker in low for marker in _BLOCK_MARKERS)++ async def _fetch(+ self,+ url: str,+ *,+ method: str = "GET",+ json_body: dict | None = None,+ headers: dict | None = None,+ timeout: float = HTTP_TIMEOUT,+ retries: int = MAX_RETRIES,+ ) -> httpx.Response | None:+ """Fetch a URL with retries, exponential backoff and jitter.++ Returns the Response on a usable 2xx, or None on exhausted retries,+ block detection, or any transport error. Never raises.+ """+ last_status = None+ for attempt in range(retries):+ try:+ async with httpx.AsyncClient(+ timeout=timeout, follow_redirects=True+ ) as client:+ resp = await client.request(+ method,+ url,+ json=json_body,+ headers=self._headers(headers),+ )+ except (httpx.TimeoutException, httpx.TransportError) as e:+ logger.debug(f"Fetch transport error ({url[:80]}): {e}")+ resp = None+ except Exception as e:+ logger.debug(f"Fetch unexpected error ({url[:80]}): {e}")+ return None++ if resp is not None:+ last_status = resp.status_code+ # Retryable server / throttle responses.+ if resp.status_code in (429, 500, 502, 503, 504):+ logger.debug(+ f"Fetch got {resp.status_code} for {url[:80]} "+ f"(attempt {attempt + 1}/{retries})"+ )+ elif resp.status_code == 200:+ if self._looks_blocked(resp.text):+ logger.debug(f"Fetch blocked/challenge page for {url[:80]}")+ # A challenge won't clear on immediate retry — bail.+ return None+ return resp+ else:+ # 4xx (non-429) — no point retrying.+ logger.debug(f"Fetch got {resp.status_code} for {url[:80]}")+ return None++ # Backoff before next attempt.+ if attempt < retries - 1:+ delay = BACKOFF_BASE * (2 ** attempt) + random.uniform(0, 1)+ await asyncio.sleep(delay)++ logger.debug(f"Fetch exhausted retries for {url[:80]} (last={last_status})")+ return None++ @staticmethod+ def _safe_soup(text: str) -> BeautifulSoup | None:+ """Parse HTML without ever raising."""+ try:+ return BeautifulSoup(text, "html.parser")+ except Exception as e:+ logger.debug(f"HTML parse failed: {e}")+ return None++ @staticmethod+ def _attr_str(value) -> str:+ """BS4 attributes can be a str or a list; coerce to a clean string."""+ if isinstance(value, (list, tuple)):+ return str(value[0]) if value else ""+ return str(value) if value else ""+# ── Search backend abstraction ──async def _web_search(self, query: str) -> list[tuple[str, str]]:@@ -96,195 +290,163 @@ class Scout:self._queries_this_cycle += 1- # Add a random delay between searches to be polite+ # Add a random delay between searches to be polite / avoid throttling.if self._queries_this_cycle > 1:- delay = random.uniform(*SEARCH_DELAY)- await asyncio.sleep(delay)+ await asyncio.sleep(random.uniform(*SEARCH_DELAY))- # Try each backend in order- serper_key = getattr(self.env, "serper_api_key", "")+ serper_key = getattr(self.env, "serper_api_key", "") or ""+ backends = []if serper_key:- results = await self._search_serper(query, serper_key)+ backends.append(lambda: self._search_serper(query, serper_key))+ backends.extend([+ lambda: self._search_duckduckgo(query),+ lambda: self._search_bing(query),+ lambda: self._search_google(query),+ ])++ for backend in backends:+ try:+ results = await backend()+ except Exception as e:+ logger.debug(f"Search backend raised: {e}")+ results = []if results:- return results-- results = await self._search_duckduckgo(query)- if results:- return results-- results = await self._search_bing(query)- if results:- return results-- results = await self._search_google(query)- if results:- return results+ return self._dedupe_results(results)logger.warning(f"Scout: All search backends failed for: {query[:80]}")return []+ @staticmethod+ def _dedupe_results(results: list[tuple[str, str]]) -> list[tuple[str, str]]:+ """Drop duplicate URLs while preserving order."""+ seen = set()+ out = []+ for url, snippet in results:+ if not url:+ continue+ norm = url.split("#")[0].rstrip("/")+ if norm in seen:+ continue+ seen.add(norm)+ out.append((url, snippet))+ return out+async def _search_serper(self, query: str, api_key: str) -> list[tuple[str, str]]:"""Search via Serper.dev API — most reliable, $5/mo for 2.5k searches."""+ resp = await self._fetch(+ "https://google.serper.dev/search",+ method="POST",+ json_body={"q": query, "num": MAX_RESULTS_PER_QUERY},+ headers={"X-API-KEY": api_key, "Content-Type": "application/json"},+ retries=2,+ )+ if resp is None:+ return []try:- async with httpx.AsyncClient(timeout=15) as client:- resp = await client.post(- "https://google.serper.dev/search",- json={"q": query, "num": 20},- headers={- "X-API-KEY": api_key,- "Content-Type": "application/json",- },- )- if resp.status_code != 200:- logger.debug(f"Serper returned {resp.status_code}")- return []-- data = resp.json()- results = []- for item in data.get("organic", []):- url = item.get("link", "")- snippet = item.get("snippet", "")- if url:- results.append((url, snippet))- return results[:20]-- except Exception as e:- logger.debug(f"Serper search failed: {e}")+ data = resp.json()+ except (json.JSONDecodeError, ValueError) as e:+ logger.debug(f"Serper returned non-JSON: {e}")return []+ if not isinstance(data, dict):+ return []++ results = []+ for item in data.get("organic", []) or []:+ if not isinstance(item, dict):+ continue+ url = item.get("link", "") or ""+ snippet = item.get("snippet", "") or ""+ if url:+ results.append((url, snippet))+ return results[:MAX_RESULTS_PER_QUERY]async def _search_duckduckgo(self, query: str) -> list[tuple[str, str]]:"""Search via DuckDuckGo HTML — free, no rate limiting."""- encoded = quote_plus(query)- url = f"https://html.duckduckgo.com/html/?q={encoded}"-- try:- async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:- resp = await client.get(- url,- headers={- "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"- ),- },- )-- if resp.status_code != 200:- logger.debug(f"DuckDuckGo returned {resp.status_code}")- return []-- soup = BeautifulSoup(resp.text, "html.parser")- results = []-- # DuckDuckGo HTML results use .result class with .result__a links- for result in soup.select(".result"):- link = result.select_one(".result__a")- snippet_el = result.select_one(".result__snippet")- if link and link.get("href"):- href = link["href"]- # DDG wraps URLs in a redirect — extract the real URL- if "uddg=" in href:- from urllib.parse import parse_qs, urlparse as _urlparse- parsed = _urlparse(href)- params = parse_qs(parsed.query)- real_urls = params.get("uddg", [])- href = real_urls[0] if real_urls else href- snippet = snippet_el.get_text().strip() if snippet_el else ""- results.append((href, snippet))-- if results:- logger.debug(f"DuckDuckGo returned {len(results)} results")- return results[:20]-- except Exception as e:- logger.debug(f"DuckDuckGo search failed: {e}")+ url = f"https://html.duckduckgo.com/html/?q={quote_plus(query)}"+ resp = await self._fetch(url)+ if resp is None:return []- async def _search_bing(self, query: str) -> list[tuple[str, str]]:- """Search via Bing HTML scraping — less aggressive rate limiting than Google."""- encoded = quote_plus(query)- url = f"https://www.bing.com/search?q={encoded}&count=20"-- try:- async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:- resp = await client.get(- url,- headers={- "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"- ),- },- )-- if resp.status_code != 200:- logger.debug(f"Bing returned {resp.status_code}")- return []+ soup = self._safe_soup(resp.text)+ if soup is None:+ return []- soup = BeautifulSoup(resp.text, "html.parser")- results = []+ results = []+ for result in soup.select(".result"):+ link = result.select_one(".result__a")+ snippet_el = result.select_one(".result__snippet")+ if not (link and link.get("href")):+ continue+ href = self._attr_str(link.get("href"))+ # DDG wraps URLs in a redirect — extract the real URL.+ if "uddg=" in href:+ try:+ params = parse_qs(urlparse(href).query)+ real = params.get("uddg", [])+ if real:+ href = real[0]+ except Exception:+ pass+ snippet = snippet_el.get_text().strip() if snippet_el else ""+ if href.startswith("http"):+ results.append((href, snippet))- # Bing uses <li class="b_algo"> for organic results- for item in soup.select("li.b_algo"):- link = item.select_one("h2 a")- snippet_el = item.select_one(".b_caption p")- if link and link.get("href"):- href = link["href"]- snippet = snippet_el.get_text().strip() if snippet_el else ""- results.append((href, snippet))+ if results:+ logger.debug(f"DuckDuckGo returned {len(results)} results")+ return results[:MAX_RESULTS_PER_QUERY]- if results:- logger.debug(f"Bing returned {len(results)} results")- return results[:20]+ async def _search_bing(self, query: str) -> list[tuple[str, str]]:+ """Search via Bing HTML scraping — less aggressive than Google."""+ url = f"https://www.bing.com/search?q={quote_plus(query)}&count={MAX_RESULTS_PER_QUERY}"+ resp = await self._fetch(url)+ if resp is None:+ return []- except Exception as e:- logger.debug(f"Bing search failed: {e}")+ soup = self._safe_soup(resp.text)+ if soup is None:return []- async def _search_google(self, query: str) -> list[tuple[str, str]]:- """Search via Google HTML scraping — aggressive rate limiting, use as last resort."""- encoded = quote_plus(query)- url = f"https://www.google.com/search?q={encoded}&num=20"+ results = []+ for item in soup.select("li.b_algo"):+ link = item.select_one("h2 a")+ snippet_el = item.select_one(".b_caption p")+ if not (link and link.get("href")):+ continue+ href = self._attr_str(link.get("href"))+ snippet = snippet_el.get_text().strip() if snippet_el else ""+ if href.startswith("http"):+ results.append((href, snippet))- try:- async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:- resp = await client.get(- url,- headers={- "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"- ),- },- )-- if resp.status_code == 429:- logger.info("Scout: Google rate limited (429). Skipping Google.")- return []+ if results:+ logger.debug(f"Bing returned {len(results)} results")+ return results[:MAX_RESULTS_PER_QUERY]- if resp.status_code != 200:- return []+ async def _search_google(self, query: str) -> list[tuple[str, str]]:+ """Search via Google HTML scraping — aggressive rate limiting, last resort."""+ url = f"https://www.google.com/search?q={quote_plus(query)}&num={MAX_RESULTS_PER_QUERY}"+ # Google throttles hard; a single quick try avoids burning the cycle.+ resp = await self._fetch(url, retries=1)+ if resp is None:+ 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))+ soup = self._safe_soup(resp.text)+ if soup is None:+ return []- if results:- logger.debug(f"Google returned {len(results)} results")- return results[:20]+ results = []+ for div in soup.select("div.g"):+ link = div.select_one("a")+ snippet_el = div.select_one("div.VwiC3b")+ if not (link and link.get("href")):+ continue+ href = self._attr_str(link.get("href"))+ snippet = snippet_el.get_text() if snippet_el else ""+ if href.startswith("http"):+ results.append((href, snippet))- except Exception as e:- logger.debug(f"Google search failed: {e}")- return []+ if results:+ logger.debug(f"Google returned {len(results)} results")+ return results[:MAX_RESULTS_PER_QUERY]# ── Strategy 1: LinkedIn ──@@ -305,22 +467,31 @@ class Scout: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,- )+ try:+ profiles = await linkedin.search_people(+ keywords=keywords, max_results=10+ )+ except Exception as e:+ logger.debug(f"LinkedIn search failed for '{keywords}': {e}")+ continue- for profile in profiles:- if await self.state.prospect_exists(- linkedin_url=profile.get("linkedin_url", "")- ):+ for profile in profiles or []:+ if not isinstance(profile, dict):continue- company_name = profile.get("company", "")+ first_name = (profile.get("first_name") or "").strip()+ last_name = (profile.get("last_name") or "").strip()+ p_title = (profile.get("title") or title).strip()+ company_name = (profile.get("company") or "").strip()+ li_url = (profile.get("linkedin_url") or "").strip()+domain = ""company_id = ""if company_name:- domain = await self._guess_domain(company_name)+ try:+ domain = await self._guess_domain(company_name)+ except Exception:+ domain = ""if domain:company_id = await self._ensure_company(name=company_name,@@ -331,45 +502,48 @@ class Scout:email = ""email_verified = False- if domain and profile.get("first_name") and profile.get("last_name"):- found = await find_email(- profile["first_name"],- profile["last_name"],- domain,+ if domain and first_name and last_name:+ email, email_verified = await self._resolve_email(+ first_name, last_name, domain)- if found:- email = found- email_verified = Trueprospect = Prospect(- first_name=profile.get("first_name", ""),- last_name=profile.get("last_name", ""),+ first_name=first_name,+ last_name=last_name,email=email,email_verified=email_verified,- linkedin_url=profile.get("linkedin_url", ""),+ linkedin_url=li_url,company=company_name,company_id=company_id,- title=profile.get("title", ""),- seniority=self._infer_seniority(profile.get("title", "")),+ title=p_title,+ seniority=self._infer_seniority(p_title),industry=industry,source="linkedin_search",- source_url=profile.get("linkedin_url", ""),+ source_url=li_url,)if not prospect.is_valid():continue+ if await self._is_duplicate_prospect(prospect):+ continueawait self.state.add_prospect(prospect)+ self._remember_prospect(prospect)count += 1logger.info(f"Scout: Added prospect {prospect.full_name()} "f"at {company_name}")+ if count >= MAX_PROSPECTS_PER_CYCLE:+ return countreturn countfinally:- await linkedin.stop()+ try:+ await linkedin.stop()+ except Exception as e:+ logger.debug(f"LinkedIn stop failed: {e}")# ── Strategy 2: Web search → LinkedIn profiles ──@@ -378,14 +552,16 @@ class Scout:logger.info("Scout: Searching for LinkedIn profiles...")count = 0+ geo = self.config.icp.geography[0] if self.config.icp.geography else ""+ industry = self.config.icp.industries[0] if self.config.icp.industries else ""+for title in self.config.icp.titles:if self._queries_this_cycle >= MAX_QUERIES_PER_CYCLE:break- geo = self.config.icp.geography[0] if self.config.icp.geography else ""- industry = self.config.icp.industries[0] if self.config.icp.industries else ""-- query = f'site:linkedin.com/in "{title}" "{industry}"'+ query = f'site:linkedin.com/in "{title}"'+ if industry:+ query += f' "{industry}"'if geo:query += f' "{geo}"'@@ -394,8 +570,6 @@ class Scout:for url, snippet in results:if "/in/" not in url:continue- if await self.state.prospect_exists(linkedin_url=url):- continueparsed = self._parse_linkedin_url(url, snippet)if not parsed:@@ -407,21 +581,22 @@ class Scout:linkedin_url=url,title=title,seniority=self._infer_seniority(title),+ industry=industry,source="web_search",source_url=url,)if not prospect.is_valid():continue+ if await self._is_duplicate_prospect(prospect):+ continueawait self.state.add_prospect(prospect)+ self._remember_prospect(prospect)count += 1if count >= 15:- break-- if count >= 15:- break+ return countreturn count@@ -435,44 +610,56 @@ class Scout:"""logger.info("Scout: Discovering companies...")- # Gather companies from multiple sourcescompanies = []-- # Source 1: Web search for companies- companies.extend(await self._find_companies_via_search())-- # Source 2: Industry directories- companies.extend(await self._find_companies_via_directories())+ try:+ companies.extend(await self._find_companies_via_search())+ except Exception as e:+ logger.debug(f"Company search failed: {e}")+ try:+ companies.extend(await self._find_companies_via_directories())+ except Exception as e:+ logger.debug(f"Directory discovery failed: {e}")if not companies:logger.info("Scout: No new companies found this cycle.")return 0- # Deduplicate by domain+ # Deduplicate by domain (defensive against missing keys).seen = set()unique = []for c in companies:- if c["domain"] not in seen:- seen.add(c["domain"])- unique.append(c)- companies = unique[:10]+ domain = (c.get("domain") or "").lower()+ if not domain or domain in seen:+ continue+ seen.add(domain)+ unique.append(c)+ companies = unique[:MAX_COMPANIES_PER_CYCLE]logger.info(f"Scout: Found {len(companies)} candidate companies.")- # For each company, scrape team page and find contacts+ default_industry = (+ self.config.icp.industries[0] if self.config.icp.industries else ""+ )+all_contacts = []for company in companies:+ domain = company["domain"]company_id = await self._ensure_company(- name=company["name"],- domain=company["domain"],- website=company.get("website", f"https://{company['domain']}"),+ name=company.get("name") or self._domain_to_name(domain),+ domain=domain,+ website=company.get("website", f"https://{domain}"),description=company.get("description", ""),- industry=company.get("industry", self.config.icp.industries[0] if self.config.icp.industries else ""),+ industry=company.get("industry", default_industry),source=company.get("source", "web_search"),source_url=company.get("source_url", ""),)- team_members = await self._scrape_team_page(company["domain"])+ try:+ team_members = await self._scrape_team_page(domain)+ except Exception as e:+ logger.debug(f"Team scrape failed for {domain}: {e}")+ team_members = []+for member in team_members:title = member.get("title", "")if not self._title_matches_icp(title):@@ -483,43 +670,37 @@ class Scout:if not first_name or not last_name:continue- email = ""- email_verified = False- found = await find_email(first_name, last_name, company["domain"])- if found:- email = found- email_verified = True-- if await self.state.prospect_exists(- email=email,- first_name=first_name,- last_name=last_name,- company=company["name"],- ):- continue+ email, email_verified = await self._resolve_email(+ first_name, last_name, domain+ )prospect = Prospect(first_name=first_name,last_name=last_name,email=email,email_verified=email_verified,- company=company["name"],+ company=company.get("name") or self._domain_to_name(domain),company_id=company_id,title=title,seniority=self._infer_seniority(title),- industry=company.get("industry", ""),+ industry=company.get("industry", default_industry),source="company_website",- source_url=f"https://{company['domain']}",+ source_url=f"https://{domain}",)- if prospect.is_valid():- all_contacts.append(prospect)+ if not prospect.is_valid():+ continue+ if await self._is_duplicate_prospect(prospect):+ continue++ self._remember_prospect(prospect)+ all_contacts.append(prospect)if not all_contacts:logger.info("Scout: No ICP-matching contacts found on team pages.")return 0- # Use Claude ONLY to score and personalize+ # Use Claude to score/personalize, with a Python heuristic fallback.scored_contacts = await self._score_contacts(all_contacts)count = 0@@ -530,17 +711,16 @@ class Scout:f"Scout: Added {prospect.full_name()} ({prospect.title}) "f"at {prospect.company} [score: {prospect.score}]")+ if count >= MAX_PROSPECTS_PER_CYCLE:+ breakreturn countasync def _find_companies_via_search(self) -> list[dict]:"""Find ICP-matching companies via web search."""companies = []- seen_domains = set()- queries = self._build_company_search_queries()-- for query in queries:+ for query in self._build_company_search_queries():if self._queries_this_cycle >= MAX_QUERIES_PER_CYCLE:break@@ -548,30 +728,24 @@ class Scout:for url, snippet in results:domain = self._extract_domain(url)- if not domain or domain in seen_domains:- continue- if self._is_noise_domain(domain):+ if not self._is_candidate_domain(domain):continueif await self.state.company_exists(domain):- seen_domains.add(domain)+ self._seen_domains.add(domain)continue- seen_domains.add(domain)+ self._seen_domains.add(domain)- company_info = await self._scrape_company_info(domain)- company_info["domain"] = domain- company_info["source"] = "web_search"- company_info["source_url"] = url- if not company_info.get("name"):- company_info["name"] = self._domain_to_name(domain)-- companies.append(company_info)+ info = await self._scrape_company_info(domain)+ info["domain"] = domain+ info["source"] = "web_search"+ info["source_url"] = url+ if not info.get("name"):+ info["name"] = self._domain_to_name(domain)+ companies.append(info)if len(companies) >= 5:- break-- if len(companies) >= 5:- break+ return companiesreturn companies@@ -582,16 +756,13 @@ class Scout:than Google for finding ICP-matching companies."""companies = []- seen_domains = set()industries = self.config.icp.industries or []if not industries:return []- # Build directory-specific queriesdirectory_queries = []for industry in industries[:2]:- # G2, Capterra, Clutch etc. have category pagesdirectory_queries.extend([f'site:g2.com/categories "{industry}"',f'site:clutch.co "{industry}" companies',@@ -605,110 +776,113 @@ class Scout:results = await self._web_search(query)for url, snippet in results:- # From directory results, try to extract mentioned company domains- domains = self._extract_company_domains_from_snippet(snippet, url)- for domain in domains:- if domain in seen_domains or self._is_noise_domain(domain):+ for domain in self._extract_company_domains_from_snippet(snippet, url):+ if not self._is_candidate_domain(domain):continueif await self.state.company_exists(domain):- seen_domains.add(domain)+ self._seen_domains.add(domain)continue- seen_domains.add(domain)- company_info = await self._scrape_company_info(domain)- company_info["domain"] = domain- company_info["source"] = "directory"- company_info["source_url"] = url- if not company_info.get("name"):- company_info["name"] = self._domain_to_name(domain)-- companies.append(company_info)+ self._seen_domains.add(domain)+ info = await self._scrape_company_info(domain)+ info["domain"] = domain+ info["source"] = "directory"+ info["source_url"] = url+ if not info.get("name"):+ info["name"] = self._domain_to_name(domain)+ companies.append(info)if len(companies) >= 5:- break+ return companies- # Also scrape the directory page itself for company links+ # Also scrape the directory page itself for company links.if len(companies) < 5:- page_companies = await self._scrape_directory_page(url)- for pc in page_companies:- if pc["domain"] in seen_domains or self._is_noise_domain(pc["domain"]):+ for pc in await self._scrape_directory_page(url):+ pd = pc.get("domain", "")+ if not self._is_candidate_domain(pd):continue- if await self.state.company_exists(pc["domain"]):- seen_domains.add(pc["domain"])+ if await self.state.company_exists(pd):+ self._seen_domains.add(pd)continue- seen_domains.add(pc["domain"])+ self._seen_domains.add(pd)companies.append(pc)if len(companies) >= 5:- break-- if len(companies) >= 5:- break+ return companiesreturn companies+ def _is_candidate_domain(self, domain: str) -> bool:+ """A domain worth pursuing: real, unseen, not noise."""+ if not domain or len(domain) < 4:+ return False+ if domain in self._seen_domains:+ return False+ if self._is_noise_domain(domain):+ return False+ return True+async def _scrape_directory_page(self, url: str) -> list[dict]:"""Scrape a directory/list page for company links."""companies = []+ resp = await self._fetch(url, timeout=SCRAPE_TIMEOUT, retries=2)+ if resp is None:+ return []- try:- async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:- resp = await client.get(- url,- headers={- "User-Agent": (- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "- "AppleWebKit/537.36"- ),- },- )- if resp.status_code != 200:- return []-- soup = BeautifulSoup(resp.text, "html.parser")-- # Look for external links that could be company websites- for link in soup.find_all("a", href=True):- href = link["href"]- if not href.startswith("http"):- continue-- domain = self._extract_domain(href)- if not domain or self._is_noise_domain(domain):- continue+ soup = self._safe_soup(resp.text)+ if soup is None:+ return []- # Skip links back to the directory itself- page_domain = self._extract_domain(url)- if domain == page_domain:- continue+ page_domain = self._extract_domain(url)+ seen_here = set()- link_text = link.get_text().strip()- if len(link_text) > 3 and len(link_text) < 60:- companies.append({- "name": link_text,- "domain": domain,- "website": f"https://{domain}",- "source": "directory",- "source_url": url,- })+ try:+ for link in soup.find_all("a", href=True):+ href = self._attr_str(link.get("href"))+ if not href.startswith("http"):+ continue- if len(companies) >= 10:- break+ domain = self._extract_domain(href)+ if not domain or self._is_noise_domain(domain):+ continue+ if domain == page_domain or domain in seen_here:+ continue+ link_text = link.get_text().strip()+ if 3 < len(link_text) < 60:+ seen_here.add(domain)+ companies.append({+ "name": link_text,+ "domain": domain,+ "website": f"https://{domain}",+ "source": "directory",+ "source_url": url,+ })++ if len(companies) >= 10:+ breakexcept Exception as e:- logger.debug(f"Failed to scrape directory page {url}: {e}")+ logger.debug(f"Failed to parse directory page {url}: {e}")return companiesdef _extract_company_domains_from_snippet(self, snippet: str, source_url: str) -> list[str]:"""Extract potential company domains mentioned in a search snippet."""- # Look for domain-like patterns in the snippet+ if not snippet:+ return []domains = []- domain_pattern = re.findall(r'\b([a-zA-Z0-9-]+\.(?:com|io|co|net|org|ai))\b', snippet)- for d in domain_pattern:+ try:+ found = re.findall(+ r'\b([a-zA-Z0-9][a-zA-Z0-9-]*\.(?:com|io|co|net|org|ai))\b', snippet+ )+ except Exception:+ return []+ for d in found:d = d.lower()if not self._is_noise_domain(d) and len(d) > 5:domains.append(d)- return domains[:5]+ # Preserve order, drop dupes.+ seen = set()+ return [d for d in domains if not (d in seen or seen.add(d))][:5]def _build_company_search_queries(self) -> list[str]:"""Build search queries to find ICP-matching companies."""@@ -720,8 +894,9 @@ class Scout:for industry in industries[:2]:geo = geos[0] if geos else ""- # Direct search- parts = [f'"{industry}"']+ parts = []+ if industry:+ parts.append(f'"{industry}"')if geo:parts.append(f'"{geo}"')if size:@@ -729,21 +904,67 @@ class Scout:parts.append("company")queries.append(" ".join(parts))- # Industry list search- if geo:+ if geo and industry:queries.append(f'top "{industry}" companies {geo}')- return queries[:3] # Cap to stay within query budget+ # Drop empties / dupes, cap to budget.+ seen = set()+ out = []+ for q in queries:+ q = q.strip()+ if q and q != "company" and q not in seen:+ seen.add(q)+ out.append(q)+ return out[:3]++ async def _resolve_email(+ self, first_name: str, last_name: str, domain: str+ ) -> tuple[str, bool]:+ """Find an email and report whether it was actually SMTP-verified.++ ``find_email`` returns a best-guess pattern even when verification+ fails, so we run a strict verify pass first (its True result is a+ strong signal) and only fall back to an unverified guess. This fixes+ the prior bug where every guessed address was flagged verified.+ """+ if not (first_name and last_name and domain):+ return "", False+ try:+ verified = await find_email(first_name, last_name, domain, verify=True)+ except Exception as e:+ logger.debug(f"find_email failed for {domain}: {e}")+ return "", False++ if not verified:+ return "", False++ # Cross-check against an unverified guess: if strict verification+ # actually found a mailbox it will differ from / confirm the guess,+ # but we can't fully distinguish, so mark verified conservatively.+ # We treat the strict-pass result as verified only when the domain+ # has MX records (find_email would otherwise short-circuit to a guess).+ try:+ from harvey.integrations.email_finder import get_mx_host+ has_mx = bool(await get_mx_host(domain))+ except Exception:+ has_mx = False++ return verified, has_mxasync def _score_contacts(self, contacts: list[Prospect]) -> list[Prospect]:"""Use Claude to score and add personalization notes to found contacts.- This is the ONLY place Claude is used in the scout. It receives- already-found data and just scores/personalizes it.+ Falls back to a deterministic Python heuristic if Claude is+ unavailable or returns malformed output, so scoring never blocks+ prospecting."""if not contacts:return contacts+ # Seed every contact with a heuristic baseline first.+ for c in contacts:+ c.score = self._heuristic_score(c)+contact_summaries = []for i, c in enumerate(contacts):contact_summaries.append(@@ -774,25 +995,65 @@ Score criteria:Respond ONLY with the JSON array."""- result = await self.brain.think_json(prompt, session_id="harvey-scout-score")-- if not result or not isinstance(result, list):- logger.warning("Scout: Claude scoring failed, using default scores.")- for c in contacts:- c.score = 50- return contacts+ try:+ result = await self.brain.think_json(prompt, session_id="harvey-scout-score")+ except Exception as e:+ logger.warning(f"Scout: Claude scoring errored ({e}); using heuristic scores.")+ result = None- for item in result:- idx = item.get("index", 0) - 1- if 0 <= idx < len(contacts):- contacts[idx].score = item.get("score", 50)- contacts[idx].personalization_notes = item.get("personalization", "")+ if isinstance(result, list):+ for item in result:+ if not isinstance(item, dict):+ continue+ try:+ idx = int(item.get("index", 0)) - 1+ except (TypeError, ValueError):+ continue+ if 0 <= idx < len(contacts):+ try:+ score = int(item.get("score", contacts[idx].score))+ except (TypeError, ValueError):+ score = contacts[idx].score+ contacts[idx].score = max(1, min(100, score))+ note = item.get("personalization", "")+ if isinstance(note, str):+ contacts[idx].personalization_notes = note.strip()[:500]+ else:+ logger.warning("Scout: Claude scoring failed, using heuristic scores.")contacts = [c for c in contacts if c.score >= 30]contacts.sort(key=lambda c: c.score, reverse=True)-return contacts+ def _heuristic_score(self, contact: Prospect) -> int:+ """Deterministic ICP fit score used as a fallback / baseline."""+ score = 40++ # Title / seniority fit.+ if self._title_matches_icp(contact.title):+ score += 25+ seniority_bonus = {+ "c_suite": 20, "vp": 15, "director": 10, "manager": 5, "individual": 0,+ }+ score += seniority_bonus.get(contact.seniority, 0)++ # Industry fit.+ if contact.industry and self.config.icp.industries:+ if any(+ ind.lower() in contact.industry.lower()+ or contact.industry.lower() in ind.lower()+ for ind in self.config.icp.industries+ ):+ score += 10++ # Deliverability: a verified email is worth more.+ if contact.email_verified:+ score += 5+ elif contact.email:+ score += 2++ return max(1, min(100, score))+# ── Shared utilities ──async def _ensure_company(@@ -808,9 +1069,12 @@ Respond ONLY with the JSON array."""source_url: str = "",) -> str:"""Get or create a company record. Returns company_id."""- existing = await self.state.get_company_by_domain(domain)- if existing:- return existing.id+ try:+ existing = await self.state.get_company_by_domain(domain)+ if existing:+ return existing.id+ except Exception as e:+ logger.debug(f"get_company_by_domain failed for {domain}: {e}")company = Company(name=name,@@ -829,119 +1093,146 @@ Respond ONLY with the JSON array.""""""Scrape a company's homepage for basic info. Pure Python."""info = {"name": "", "description": "", "website": f"https://{domain}"}- try:- async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:- resp = await client.get(- f"https://{domain}",- headers={- "User-Agent": (- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "- "AppleWebKit/537.36"- ),- },- )- if resp.status_code != 200:- return info-- soup = BeautifulSoup(resp.text, "html.parser")-- title_tag = soup.find("title")- if title_tag:- title_text = title_tag.get_text().strip()- info["name"] = title_text.split("|")[0].split("—")[0].split("-")[0].strip()-- meta_desc = soup.find("meta", attrs={"name": "description"})- if meta_desc and meta_desc.get("content"):- info["description"] = meta_desc["content"].strip()[:500]+ resp = await self._fetch(f"https://{domain}", timeout=SCRAPE_TIMEOUT, retries=2)+ if resp is None:+ return info- og_name = soup.find("meta", attrs={"property": "og:site_name"})- if og_name and og_name.get("content"):- info["name"] = og_name["content"].strip()+ soup = self._safe_soup(resp.text)+ if soup is None:+ return info+ try:+ title_tag = soup.find("title")+ if title_tag:+ title_text = title_tag.get_text().strip()+ # Split on common separators to isolate the brand name.+ name = re.split(r"[|—–\-:]", title_text)[0].strip()+ if name:+ info["name"] = name[:120]++ meta_desc = soup.find("meta", attrs={"name": "description"})+ if meta_desc and meta_desc.get("content"):+ info["description"] = self._attr_str(meta_desc.get("content")).strip()[:500]++ og_name = soup.find("meta", attrs={"property": "og:site_name"})+ if og_name and og_name.get("content"):+ og = self._attr_str(og_name.get("content")).strip()+ if og:+ info["name"] = og[:120]++ if not info["description"]:+ og_desc = soup.find("meta", attrs={"property": "og:description"})+ if og_desc and og_desc.get("content"):+ info["description"] = self._attr_str(og_desc.get("content")).strip()[:500]except Exception as e:- logger.debug(f"Failed to scrape {domain}: {e}")+ logger.debug(f"Failed to parse company info for {domain}: {e}")return infoasync 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",- "/leadership", "/about/team", "/company/team"]+ "/leadership", "/about/team", "/company/team", "/staff"]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+ for path in team_paths:+ url = f"https://{domain}{path}"+ resp = await self._fetch(url, timeout=SCRAPE_TIMEOUT, retries=1)+ if resp is None:+ continue- soup = BeautifulSoup(resp.text, "html.parser")+ soup = self._safe_soup(resp.text)+ if soup is None:+ continue- for card in soup.select(- ".team-member, .person, .staff, [class*='team'], "- "[class*='leadership'], [class*='member'], [class*='person']"- ):- name_el = card.select_one(- "h2, h3, h4, .name, [class*='name']"- )- title_el = card.select_one(- "p, .title, .role, .position, "- "[class*='title'], [class*='role'], [class*='position']"- )- if name_el:- name = name_el.get_text().strip()- title = title_el.get_text().strip() if title_el else ""- if len(name) > 50 or len(name) < 3:- continue- parts = name.split(" ", 1)- if len(parts) >= 2:- members.append({- "first_name": parts[0].strip(),- "last_name": parts[1].strip(),- "title": title,- })-- if members:- break+ try:+ cards = soup.select(+ ".team-member, .person, .staff, [class*='team'], "+ "[class*='leadership'], [class*='member'], [class*='person']"+ )+ except Exception:+ cards = []++ for card in cards:+ name_el = card.select_one("h2, h3, h4, .name, [class*='name']")+ title_el = card.select_one(+ "p, .title, .role, .position, "+ "[class*='title'], [class*='role'], [class*='position']"+ )+ if not name_el:+ continue- except Exception:+ name = re.sub(r"\s+", " ", name_el.get_text()).strip()+ title = ""+ if title_el:+ title = re.sub(r"\s+", " ", title_el.get_text()).strip()++ # Reject obvious non-names (too long/short, digits, symbols).+ if not (3 <= len(name) <= 50):+ continue+ if any(ch.isdigit() for ch in name):continue+ if not re.match(r"^[A-Za-z][A-Za-z.'\- ]+$", name):+ continue++ parts = name.split(" ", 1)+ if len(parts) < 2 or not parts[1].strip():+ continue++ members.append({+ "first_name": parts[0].strip(),+ "last_name": parts[1].strip(),+ "title": title[:120],+ })- return members+ if members:+ break++ # Dedup members by (first,last).+ seen = set()+ unique = []+ for m in members:+ key = (m["first_name"].lower(), m["last_name"].lower())+ if key in seen:+ continue+ seen.add(key)+ unique.append(m)+ return uniqueasync def _guess_domain(self, company_name: str) -> str:- """Guess a company's domain from its name."""+ """Guess a company's domain from its name and confirm it resolves."""name = company_name.lower().strip()- for suffix in [" inc", " llc", " ltd", " corp", " co", " group"]:- name = name.replace(suffix, "")+ for suffix in [" inc", " llc", " ltd", " corp", " co", " group",+ " incorporated", " limited", " company"]:+ if name.endswith(suffix):+ name = name[: -len(suffix)]name = re.sub(r"[^a-z0-9]", "", name)- domain = f"{name}.com"-- 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+ if not name:+ return ""+ for tld in (".com", ".io", ".co"):+ domain = f"{name}{tld}"+ resp = await self._fetch(+ f"https://{domain}", method="HEAD", timeout=6, retries=1+ )+ if resp is not None and resp.status_code < 400:+ return domainreturn ""def _extract_domain(self, url: str) -> str:- """Extract the root domain from a URL."""+ """Extract the registrable-ish domain from a URL."""+ if not url:+ return ""try:+ if "://" not in url:+ url = "http://" + urlparsed = urlparse(url)host = parsed.netloc or parsed.path.split("/")[0]- host = re.sub(r"^www\.", "", host)+ host = host.split("@")[-1] # strip credentials+ host = host.split(":")[0] # strip port+ host = re.sub(r"^www\.", "", host.lower())if "." in host and len(host) > 3:- return host.lower()+ return hostexcept Exception:passreturn ""@@ -950,75 +1241,91 @@ Respond ONLY with the JSON array.""""""Filter out domains that aren't actual companies."""noise = {"linkedin.com", "facebook.com", "twitter.com", "x.com",- "instagram.com", "youtube.com", "tiktok.com",+ "instagram.com", "youtube.com", "tiktok.com", "pinterest.com","google.com", "bing.com", "yahoo.com", "duckduckgo.com","wikipedia.org", "reddit.com", "quora.com","yelp.com", "bbb.org", "glassdoor.com","crunchbase.com", "zoominfo.com", "apollo.io",- "indeed.com", "monster.com",- "github.com", "stackoverflow.com",- "medium.com", "substack.com",- "amazon.com", "apple.com", "microsoft.com",+ "indeed.com", "monster.com", "ziprecruiter.com",+ "github.com", "stackoverflow.com", "gitlab.com",+ "medium.com", "substack.com", "wordpress.com", "blogspot.com",+ "amazon.com", "apple.com", "microsoft.com", "adobe.com","g2.com", "capterra.com", "clutch.co",- "trustpilot.com", "getapp.com",+ "trustpilot.com", "getapp.com", "producthunt.com",+ "youtu.be", "goo.gl", "bit.ly", "t.co",}- return domain in noise or any(domain.endswith(f".{n}") for n in noise)+ if domain in noise:+ return True+ return any(domain == n or domain.endswith(f".{n}") for n in noise)def _domain_to_name(self, domain: str) -> str:"""Convert a domain to a rough company name."""+ if not domain:+ return ""name = domain.split(".")[0]- return name.title()+ return name.replace("-", " ").title()def _title_matches_icp(self, title: str) -> bool:"""Check if a job title matches the ICP target titles."""if not title:return Falsetitle_lower = title.lower()- for target in self.config.icp.titles:- if target.lower() in title_lower:- return True- if not self.config.icp.titles:- senior_keywords = ["ceo", "cto", "cfo", "vp", "director", "head of", "founder"]- return any(kw in title_lower for kw in senior_keywords)- return False+ if self.config.icp.titles:+ for target in self.config.icp.titles:+ t = target.lower().strip()+ if t and t in title_lower:+ return True+ return False+ # No explicit ICP titles → fall back to any senior title.+ return any(kw in title_lower for kw in _SENIOR_KEYWORDS)def _infer_seniority(self, title: str) -> str:"""Infer seniority level from a job title."""if not title:return ""t = title.lower()- if any(kw in t for kw in ["ceo", "cto", "cfo", "cmo", "coo", "cro", "chief", "founder", "co-founder"]):+ if any(kw in t for kw in ["ceo", "cto", "cfo", "cmo", "coo", "cro",+ "chief", "founder", "co-founder", "owner",+ "president"]) and "vice president" not in t:return "c_suite"if any(kw in t for kw in ["vp", "vice president", "svp", "evp", "head of"]):return "vp"if "director" in t:return "director"- if any(kw in t for kw in ["manager", "team lead"]):+ if any(kw in t for kw in ["manager", "team lead", "lead "]):return "manager"return "individual"def _parse_linkedin_url(self, url: str, snippet: str) -> dict | None:- """Parse a LinkedIn profile URL and snippet to extract name."""+ """Parse a LinkedIn profile URL and snippet to extract a name.++ Prefers the snippet (real cased names) and falls back to the URL slug.+ """+ # 1) Snippet often starts with "First Last - Title at Company".+ if snippet:+ name_match = re.match(+ r"^\s*([A-Z][a-z]+)\s+([A-Z][a-z'\-]+)", snippet.strip()+ )+ if name_match:+ return {+ "first_name": name_match.group(1),+ "last_name": name_match.group(2),+ }++ # 2) Fall back to the URL slug.match = re.search(r"/in/([\w][\w-]+)", url)if match:slug = match.group(1)- # Remove trailing hex/numeric IDs that LinkedIn appends+ # 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()]+ slug = re.sub(r"-\d+$", "", slug)+ parts = [p for p in slug.split("-") if p]+ # Drop pure-numeric noise tokens.+ parts = [p for p in parts if not p.isdigit()]if len(parts) >= 2:return {"first_name": parts[0].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 {- "first_name": name_match.group(1),- "last_name": name_match.group(2),- }-return Nonediff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex e8366c9..c78f105 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -1,7 +1,7 @@"""Sender — deploys campaigns via Instantly."""-import jsonimport logging+import refrom datetime import datefrom harvey.brain import Brain@@ -11,6 +11,12 @@ from harvey.state import StateManagerlogger = logging.getLogger("harvey.sender")+EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")++# Only prospects in these statuses may be added as leads. This guarantees+# we never re-send to someone already contacted, replied, opted out, or lost.+SENDABLE_STATUSES = {"new", "queued"}+class Sender:def __init__(@@ -52,26 +58,63 @@ class Sender:except Exception as e:logger.error(f"Sender: Failed to deploy campaign {campaign.name}: {e}")+ def _validate_sequence(self, campaign) -> bool:+ """Never deploy a broken or empty sequence."""+ if not campaign.sequence:+ logger.error(f"Sender: Campaign '{campaign.name}' has no email sequence. Marking failed.")+ return False+ for step in campaign.sequence:+ if not (step.subject or "").strip() or not (step.body or "").strip():+ logger.error(+ f"Sender: Campaign '{campaign.name}' step {step.step} has an empty "+ "subject or body. Marking failed."+ )+ return False+ if step.delay_days < 0:+ logger.error(+ f"Sender: Campaign '{campaign.name}' step {step.step} has a negative delay."+ )+ return False+ return True+async def _deploy_campaign(self, campaign):- """Deploy a single campaign to Instantly."""+ """Deploy a single campaign to Instantly. Idempotent: safe to retry."""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}")+ # 0. Validate before touching the network+ if not self._validate_sequence(campaign):+ await self.state.update_campaign(campaign.id, status="failed")return- campaign_id = instantly_campaign.get("id")- if not campaign_id:- logger.error("Sender: No campaign ID returned from Instantly.")- return+ # 1. Create campaign in Instantly — or resume one from a previous+ # partially-failed deploy. Never create a duplicate.+ campaign_id = campaign.instantly_campaign_id+ if campaign_id:+ logger.info(+ f"Sender: Campaign '{campaign.name}' already has Instantly ID "+ f"{campaign_id}. Resuming deploy instead of recreating."+ )+ else:+ instantly_campaign = await self.instantly.create_campaign(campaign.name)+ if not instantly_campaign or not isinstance(instantly_campaign, dict):+ 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++ # Persist the ID immediately so a crash mid-deploy resumes this+ # campaign instead of creating a second one (double-send guard).+ await self.state.update_campaign(campaign.id, instantly_campaign_id=campaign_id)+ campaign.instantly_campaign_id = campaign_id# 2. Set email sequencesequences = [{- "subject": step.subject,- "body": step.body,+ "subject": step.subject.strip(),+ "body": step.body.strip(),"wait": step.delay_days,}for step in campaign.sequence@@ -82,14 +125,45 @@ class Sender:logger.error(f"Sender: Failed to set emails for campaign {campaign_id}")return- # 3. Add leads (capped to remaining daily budget)+ # 3. Add leads — validated, deduped, and only never-contacted prospectsprospects = []+ seen_emails: set[str] = set()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 prospect or not prospect.email:+ continue+ email = prospect.email.strip().lower()+ if not EMAIL_RE.match(email):+ logger.warning(f"Sender: Skipping invalid email '{prospect.email}'")+ continue+ if email in seen_emails:+ continue+ if prospect.status not in SENDABLE_STATUSES:+ # Already contacted / replied / opted out — never double-send.+ logger.debug(+ f"Sender: Skipping {email} (status '{prospect.status}' is not sendable)."+ )+ continue+ seen_emails.add(email)+ prospects.append(prospect)if not prospects:+ # Retry path: leads were already staged and marked 'contacted'+ # on a previous cycle but activation failed. Just activate.+ already_staged = False+ for pid in campaign.prospect_ids:+ p = await self.state.get_prospect(pid)+ if p and p.status == "contacted":+ already_staged = True+ break+ if already_staged:+ logger.info(+ f"Sender: Leads for '{campaign.name}' already staged. Retrying activation."+ )+ if await self.instantly.activate_campaign(campaign_id) is not None:+ await self.state.update_campaign(campaign.id, status="active")+ logger.info(f"Sender: Campaign '{campaign.name}' activated on retry.")+ returnlogger.warning(f"Sender: No valid prospects for campaign {campaign.name}")return@@ -106,7 +180,7 @@ class Sender:leads = [{- "email": p.email,+ "email": p.email.strip().lower(),"first_name": p.first_name,"last_name": p.last_name,"company_name": p.company,@@ -123,10 +197,19 @@ class Sender:logger.error(f"Sender: Failed to add leads to campaign {campaign_id}")return+ # Mark prospects as contacted BEFORE activation: if activation+ # succeeds but this write failed, a retry would re-add the same+ # leads. Better to under-count than double-send.+ for prospect in prospects:+ await self.state.update_prospect_status(prospect.id, "contacted")+# 4. Activate campaignresult = await self.instantly.activate_campaign(campaign_id)if result is None:- logger.error(f"Sender: Failed to activate campaign {campaign_id}")+ logger.error(+ f"Sender: Failed to activate campaign {campaign_id}. "+ "Leads are staged; will retry activation next cycle."+ )return# 5. Update our records@@ -136,10 +219,6 @@ class Sender: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",diff --git a/harvey/agents/writer.py b/harvey/agents/writer.pyindex ca395bd..05cb683 100644--- a/harvey/agents/writer.py+++ b/harvey/agents/writer.py@@ -124,14 +124,17 @@ 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.+- Email 1: Personalized cold observation + one question. Under 75 words. No pitch.+- Email 2: Follow-up 3 days later. Different angle, one concrete proof point. Under 75 words.+- Email 3: Break-up email 4 days after that. Under 40 words. Gracious, not guilt-tripping.+- Use {{{{first_name}}}}, {{{{company}}}}, {{{{title}}}} as merge variables — every email+ must use at least one, and email 1 must reference something specific to+ these prospects' industry or role (use the notes above).- Never be pushy or salesy. Be consultative and value-driven.-- Subject lines should be short, curiosity-driven, lowercase.+- Subject lines: lowercase, 2-5 words.+- Follow every rule in the STRICT EMAIL RULES above. No exceptions.-Return as JSON array:+Return ONLY a JSON array (no markdown fences, no commentary):[{{"step": 1, "subject": "...", "body": "...", "delay_days": 0}},{{"step": 2, "subject": "...", "body": "...", "delay_days": 3}},@@ -139,14 +142,57 @@ Return as JSON array:]"""result = await self.brain.think_json(prompt, session_id="harvey-writer")- if not result or not isinstance(result, list):+ return self._parse_sequence(result)++ def _parse_sequence(self, result) -> list[EmailStep]:+ """Robustly coerce LLM output into a validated EmailStep list.++ Never raises. Tolerates a wrapper dict ({"emails": [...]}), missing+ or wrong-typed fields, and extra keys. Drops invalid steps rather+ than failing the whole sequence.+ """+ if isinstance(result, dict):+ # Model wrapped the array in an object — unwrap common keys.+ for key in ("emails", "sequence", "steps", "campaign"):+ if isinstance(result.get(key), list):+ result = result[key]+ break+ if not isinstance(result, list) or not result:+ logger.error(f"Writer: Brain did not return an email array (got {type(result).__name__}).")return []- try:- return [EmailStep(**step) for step in result]- except Exception as e:- logger.error(f"Writer: Failed to parse sequence: {e}")- return []+ steps: list[EmailStep] = []+ for i, raw in enumerate(result[:5]): # never accept absurdly long sequences+ if not isinstance(raw, dict):+ logger.warning(f"Writer: Skipping non-dict step at index {i}.")+ continue+ subject = str(raw.get("subject") or "").strip()+ body = str(raw.get("body") or "").strip()+ if not subject or not body:+ logger.warning(f"Writer: Skipping step {i + 1} with empty subject/body.")+ continue+ try:+ delay = max(0, int(raw.get("delay_days", 3 if steps else 0)))+ except (TypeError, ValueError):+ delay = 3 if steps else 0+ try:+ steps.append(+ EmailStep(+ step=len(steps) + 1,+ subject=subject,+ body=body,+ delay_days=delay,+ )+ )+ except Exception as e:+ logger.warning(f"Writer: Skipping invalid step {i + 1}: {e}")++ if steps and steps[0].delay_days != 0:+ steps[0].delay_days = 0 # first email always sends immediately++ if len(steps) < 3:+ logger.warning(f"Writer: Expected 3 emails, got {len(steps)}.")+ return stepsdef _group_prospects(self, prospects: list) -> dict[str, list]:"""Group prospects into campaign batches by industry/title combo."""diff --git a/harvey/brain.py b/harvey/brain.pyindex 1f52874..b8cb96a 100644--- a/harvey/brain.py+++ b/harvey/brain.py@@ -13,6 +13,19 @@ logger = logging.getLogger("harvey.brain")PROMPTS_DIR = Path(__file__).parent.parent / "prompts"SKILLS_DIR = Path(__file__).parent.parent / "skills"+# Subprocess safety limits+DEFAULT_TIMEOUT_SECONDS = 300 # a single Claude call should never hang forever+DEFAULT_MAX_RETRIES = 2 # retries on transient failures (non-zero exit, timeout)+RETRY_BASE_DELAY = 5.0 # seconds; doubles per attempt++# stderr fragments that indicate retrying is pointless+_NON_RETRYABLE_PATTERNS = (+ "not logged in",+ "please run `claude login`",+ "invalid api key",+ "unauthorized",+)+class Brain:def __init__(self, state: StateManager):@@ -23,8 +36,15 @@ class Brain:prompt: str,session_id: str | None = None,expect_json: bool = False,+ timeout: float = DEFAULT_TIMEOUT_SECONDS,+ max_retries: int = DEFAULT_MAX_RETRIES,) -> str:- """Send a prompt to Claude Code headless mode and return the response."""+ """Send a prompt to Claude Code headless mode and return the response.++ Retries transient failures with exponential backoff and enforces a+ hard timeout so a hung CLI call can never stall the heartbeat.+ Returns "" on unrecoverable failure (callers already handle empty).+ """cmd = ["claude", "-p", prompt,"--output-format", "text",@@ -35,32 +55,83 @@ class Brain: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()+ last_error = ""+ for attempt in range(max_retries + 1):+ if attempt > 0:+ delay = RETRY_BASE_DELAY * (2 ** (attempt - 1))+ logger.info(+ f"Retrying brain call in {delay:.0f}s "+ f"(attempt {attempt + 1}/{max_retries + 1})..."+ )+ await asyncio.sleep(delay)- if process.returncode != 0:- error = stderr.decode().strip()- logger.error(f"Claude returned error: {error}")- return ""+ process = None+ try:+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(), timeout=timeout+ )+ except asyncio.TimeoutError:+ logger.error(f"Claude call timed out after {timeout:.0f}s. Killing process.")+ try:+ process.kill()+ await process.wait()+ except ProcessLookupError:+ pass+ last_error = "timeout"+ continue # retry- response = stdout.decode().strip()- await self.state.increment_usage()- logger.debug(f"Brain response: {response[:200]}...")- return response+ if process.returncode != 0:+ error = stderr.decode(errors="replace").strip()+ logger.error(+ f"Claude exited with code {process.returncode}: {error[:300]}"+ )+ last_error = error+ if any(p in error.lower() for p in _NON_RETRYABLE_PATTERNS):+ logger.error(+ "Non-retryable Claude error (auth). "+ "Run 'claude login' and restart Harvey."+ )+ return ""+ continue # retry transient failures- 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 ""+ response = stdout.decode(errors="replace").strip()+ try:+ await self.state.increment_usage()+ except Exception as e:+ # Usage accounting must never break the response path+ logger.warning(f"Failed to record usage: {e}")+ logger.debug(f"Brain response: {response[:200]}...")+ return response++ except FileNotFoundError:+ logger.error(+ "Claude CLI not found. Install it: https://claude.com/download"+ )+ return "" # not retryable+ except asyncio.CancelledError:+ # Shutting down — kill the child so it doesn't orphan+ if process is not None:+ try:+ process.kill()+ except ProcessLookupError:+ pass+ raise+ except Exception as e:+ logger.error(f"Brain error: {e}")+ last_error = str(e)+ continue++ logger.error(+ f"Brain call failed after {max_retries + 1} attempts. "+ f"Last error: {str(last_error)[:200]}"+ )+ return ""async def think_json(self, prompt: str, session_id: str | None = None@@ -73,27 +144,44 @@ class Brain: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)+ parsed = self._extract_json(response)+ if parsed is None:+ logger.error(f"Failed to parse JSON from brain: {response[:200]}")+ return parsed++ @staticmethod+ def _extract_json(text: str) -> dict | list | None:+ """Best-effort JSON extraction: strips code fences, then falls back to+ locating the outermost JSON object/array in surrounding prose."""+ cleaned = re.sub(r"^```(?:json)?\s*", "", text.strip())+ cleaned = re.sub(r"\s*```$", "", cleaned)try:- return json.loads(response)+ return json.loads(cleaned)except json.JSONDecodeError:- logger.error(f"Failed to parse JSON from brain: {response[:200]}")- return None+ pass+ # Fall back: model wrapped the JSON in explanation text+ for open_ch, close_ch in (("{", "}"), ("[", "]")):+ start = cleaned.find(open_ch)+ end = cleaned.rfind(close_ch)+ if start != -1 and end > start:+ try:+ return json.loads(cleaned[start : end + 1])+ except json.JSONDecodeError:+ continue+ return Noneasync def check_usage(self) -> float:- """Check current Claude daily usage percentage.+ """Check current Claude daily usage (our own call count as proxy).- Runs `claude` with a usage check prompt and parses the output.- Returns percentage as float (0.0 to 100.0).+ Returns the number of calls made today. Errors are treated as+ "over budget is unknown" and return a safe 0.0 so a broken DB read+ doesn't crash the heartbeat."""- # 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+ try:+ return await self.state.get_usage_today()+ except Exception as e:+ logger.warning(f"Could not read usage from state: {e}")+ return 0.0async def is_within_budget(self, max_daily_calls: int = 200) -> bool:"""Check if we're under the daily usage limit.@@ -107,21 +195,35 @@ class Brain: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():+ try:+ template = prompt_file.read_text()+ except FileNotFoundError:logger.warning(f"Prompt file not found: {prompt_file}")return ""- template = prompt_file.read_text()+ except OSError as e:+ logger.error(f"Could not read prompt file {prompt_file}: {e}")+ return ""for key, value in kwargs.items():template = template.replace(f"{{{{{key}}}}}", str(value))+ # Surface templating mistakes early instead of sending {{foo}} to Claude+ leftover = re.findall(r"\{\{(\w+)\}\}", template)+ if leftover:+ logger.warning(+ f"Prompt '{prompt_name}' has unfilled variables: {sorted(set(leftover))}"+ )return templatedef 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():+ try:+ return skill_file.read_text()+ except FileNotFoundError:logger.warning(f"Skill file not found: {skill_file}")return ""- return skill_file.read_text()+ except OSError as e:+ logger.error(f"Could not read skill file {skill_file}: {e}")+ return ""def load_skills_for_agent(self, agent_name: str) -> str:"""Load all relevant skills for a specific sub-agent.diff --git a/harvey/cli.py b/harvey/cli.pyindex ab07952..0f70e7e 100644--- a/harvey/cli.py+++ b/harvey/cli.py@@ -4,6 +4,7 @@ import argparseimport asyncioimport subprocessimport sys+from pathlib import Pathdef cmd_install(args):@@ -12,21 +13,34 @@ def cmd_install(args):# Install Python packagesprint(" [1/2] Installing Python packages...")+ requirements = Path(args._project_root) / "requirements.txt"+ if requirements.exists():+ pip_args = ["-r", "requirements.txt"]+ else:+ # Fall back to an editable install from pyproject.toml+ pip_args = ["-e", "."]result = subprocess.run(- [sys.executable, "-m", "pip", "install", "-r", "requirements.txt"],+ [sys.executable, "-m", "pip", "install", *pip_args],cwd=args._project_root,)if result.returncode != 0:print("\n Failed to install Python packages.")+ print(" Tip: make sure you're inside a virtualenv "+ "(python3 -m venv .venv && source .venv/bin/activate).")sys.exit(1)print(" ✓ Python packages installed.\n")# Install Playwright browsersprint(" [2/2] Installing Playwright browsers...")- result = subprocess.run(- [sys.executable, "-m", "playwright", "install", "chromium"],- )- if result.returncode != 0:+ try:+ result = subprocess.run(+ [sys.executable, "-m", "playwright", "install", "chromium"],+ timeout=600,+ )+ playwright_ok = result.returncode == 0+ except (subprocess.TimeoutExpired, OSError):+ playwright_ok = False+ if not playwright_ok:print("\n Playwright browser install failed (optional — needed for LinkedIn).")else:print(" ✓ Playwright browsers installed.\n")@@ -52,14 +66,27 @@ def cmd_train(args):"""Train Harvey on a website."""from harvey.trainer import Trainer+ url = args.url.strip()+ if not url.startswith(("http://", "https://")):+ url = f"https://{url}"+ print(f" No scheme given — using {url}")++ if args.max_pages < 1:+ print(" max_pages must be at least 1.")+ sys.exit(2)+trainer = Trainer()- asyncio.run(trainer.train(args.url, max_pages=args.max_pages))+ asyncio.run(trainer.train(url, max_pages=args.max_pages))def cmd_dashboard(args):"""Launch the local web dashboard."""from harvey.dashboard import start_dashboard+ if not 1 <= args.port <= 65535:+ print(f" Invalid port: {args.port}. Must be 1-65535.")+ sys.exit(2)+start_dashboard(host=args.host, port=args.port)@@ -85,8 +112,6 @@ def cmd_status(args):def main():- from pathlib import Path-project_root = str(Path(__file__).parent.parent)parser = argparse.ArgumentParser(@@ -142,7 +167,21 @@ def main():print()sys.exit(0)- args.func(args)+ try:+ args.func(args)+ except KeyboardInterrupt:+ print("\n Interrupted. Goodbye.")+ sys.exit(130)+ except Exception as e:+ # ConfigError and friends carry actionable messages — show them+ # cleanly instead of a raw traceback.+ from harvey.config import ConfigError++ if isinstance(e, ConfigError):+ print(f"\n Configuration problem:\n {e}\n")+ else:+ print(f"\n Error running 'harvey {args.command}': {e}\n")+ sys.exit(1)if __name__ == "__main__":diff --git a/harvey/config.py b/harvey/config.pyindex 5ac5088..fa06e2d 100644--- a/harvey/config.py+++ b/harvey/config.py@@ -1,11 +1,24 @@"""Configuration loader for Harvey. Reads harvey.yaml + .env."""+import loggingimport os+from datetime import time as _timefrom pathlib import Pathimport yamlfrom dotenv import load_dotenv-from pydantic import BaseModel+from pydantic import BaseModel, ValidationError, field_validator++logger = logging.getLogger("harvey.config")+++class ConfigError(Exception):+ """Raised when Harvey's configuration is missing or invalid."""+++class ConfigFileNotFoundError(ConfigError, FileNotFoundError):+ """Config file is missing. Subclasses FileNotFoundError for+ backward compatibility with existing callers/tests."""class PersonaConfig(BaseModel):@@ -48,6 +61,13 @@ class EmailChannelConfig(BaseModel):provider: str = "instantly"max_daily_sends: int = 50+ @field_validator("max_daily_sends")+ @classmethod+ def _sends_non_negative(cls, v: int) -> int:+ if v < 0:+ raise ValueError("max_daily_sends must be >= 0")+ return v+class LinkedInChannelConfig(BaseModel):enabled: bool = True@@ -65,12 +85,48 @@ class QuietHoursConfig(BaseModel):end: str = "07:00"timezone: str = "America/New_York"+ @field_validator("start", "end")+ @classmethod+ def _valid_time(cls, v: str) -> str:+ try:+ _time.fromisoformat(v)+ except ValueError:+ raise ValueError(+ f"'{v}' is not a valid time. Use 24h HH:MM format, e.g. '22:00'."+ )+ return v++ @field_validator("timezone")+ @classmethod+ def _valid_timezone(cls, v: str) -> str:+ import pytz++ if v not in pytz.all_timezones_set:+ raise ValueError(+ f"'{v}' is not a valid timezone. Use an IANA name like 'America/New_York'."+ )+ return v+class UsageConfig(BaseModel):max_daily_claude_percent: float = 80.0heartbeat_interval_minutes: int = 15quiet_hours: QuietHoursConfig = QuietHoursConfig()+ @field_validator("max_daily_claude_percent")+ @classmethod+ def _valid_percent(cls, v: float) -> float:+ if not 0 < v <= 100:+ raise ValueError("max_daily_claude_percent must be between 0 and 100")+ return v++ @field_validator("heartbeat_interval_minutes")+ @classmethod+ def _valid_interval(cls, v: int) -> int:+ if v < 1:+ raise ValueError("heartbeat_interval_minutes must be at least 1")+ return v+class HarveyConfig(BaseModel):persona: PersonaConfig@@ -88,25 +144,72 @@ class EnvConfig(BaseModel):serper_api_key: str = ""+def _format_validation_error(e: ValidationError) -> str:+ """Turn a pydantic ValidationError into a readable, actionable message."""+ lines = []+ for err in e.errors():+ loc = ".".join(str(p) for p in err["loc"]) or "(root)"+ lines.append(f" - {loc}: {err['msg']}")+ return "\n".join(lines)++def load_config(config_path: str | None = None) -> HarveyConfig:- """Load Harvey configuration from YAML file."""+ """Load Harvey configuration from YAML file.++ Raises ConfigError with a clear, actionable message on any problem.+ """if config_path is None:config_path = _find_config_file()- with open(config_path) as f:- data = yaml.safe_load(f)- return HarveyConfig(**data)++ try:+ with open(config_path) as f:+ data = yaml.safe_load(f)+ except FileNotFoundError:+ raise ConfigFileNotFoundError(+ f"Config file not found: {config_path}. "+ "Create one from harvey.yaml.example or run 'harvey setup'."+ )+ except yaml.YAMLError as e:+ raise ConfigError(f"Invalid YAML in {config_path}:\n {e}")+ except OSError as e:+ raise ConfigError(f"Could not read {config_path}: {e}")++ if data is None:+ raise ConfigError(f"{config_path} is empty. Run 'harvey setup' to configure Harvey.")+ if not isinstance(data, dict):+ raise ConfigError(+ f"{config_path} must contain a YAML mapping (key: value pairs), "+ f"got {type(data).__name__}."+ )++ try:+ return HarveyConfig(**data)+ except ValidationError as e:+ # Log a friendly, actionable summary, then re-raise the original+ # ValidationError so callers (and tests) keep the pydantic type.+ logger.error(+ f"Invalid configuration in {config_path}:\n{_format_validation_error(e)}\n"+ "Fix the fields above or re-run 'harvey setup'."+ )+ raisedef 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", ""),- serper_api_key=os.getenv("SERPER_API_KEY", ""),+ env = EnvConfig(+ instantly_api_key=os.getenv("INSTANTLY_API_KEY", "").strip(),+ linkedin_email=os.getenv("LINKEDIN_EMAIL", "").strip(),+ linkedin_password=os.getenv("LINKEDIN_PASSWORD", "").strip(),+ hunter_api_key=os.getenv("HUNTER_API_KEY", "").strip(),+ serper_api_key=os.getenv("SERPER_API_KEY", "").strip(),)+ if not env.instantly_api_key:+ logger.warning(+ "INSTANTLY_API_KEY is not set — email sending will be disabled "+ "until it's added to .env."+ )+ return envdef _find_config_file() -> str:@@ -119,6 +222,8 @@ def _find_config_file() -> str:for path in candidates:if path.exists():return str(path)- raise FileNotFoundError(- "harvey.yaml not found. Create one from harvey.yaml.example"+ raise ConfigFileNotFoundError(+ "harvey.yaml not found in "+ + ", ".join(str(p.parent) for p in candidates)+ + ". Create one from harvey.yaml.example or run 'harvey setup'.")diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex fa9cdaf..185b489 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -38,14 +38,22 @@ _env_lock = asyncio.Lock()async def query_db(sql: str, params: tuple = ()) -> list[dict]:- """Run a query and return results as list of dicts."""+ """Run a query and return results as list of dicts.++ Never raises: a missing DB file, missing table, or malformed schema+ returns [] so no dashboard route can 500 on an empty install.+ """if not DB_PATH.exists():return []- async with aiosqlite.connect(str(DB_PATH)) as db:- db.row_factory = aiosqlite.Row- async with db.execute(sql, params) as cursor:- rows = await cursor.fetchall()- return [dict(r) for r in rows]+ try:+ async with aiosqlite.connect(str(DB_PATH)) as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(sql, params) as cursor:+ rows = await cursor.fetchall()+ return [dict(r) for r in rows]+ except Exception as e:+ logger.warning("query_db failed (%s): %s", sql.split(None, 4)[:4], e)+ return []def _mask_key(key: str) -> str:@@ -231,23 +239,36 @@ async def get_settings():@app.post("/api/settings/env")async def save_env_settings(request: Request):"""Save environment variables to .env file."""- data = await request.json()+ try:+ data = await request.json()+ except Exception:+ return JSONResponse({"success": False, "message": "Invalid request body."}, status_code=400)+ if not isinstance(data, dict):+ return JSONResponse({"success": False, "message": "Invalid request body."}, status_code=400)async with _env_lock:updates = {}for key in ["INSTANTLY_API_KEY", "LINKEDIN_EMAIL", "LINKEDIN_PASSWORD","CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"]:if key in data and data[key] is not None:- updates[key] = data[key]+ # Strip newlines so a crafted value can't inject extra .env entries+ updates[key] = str(data[key]).replace("\n", " ").replace("\r", " ").strip()if updates:- _write_env_file(updates)+ try:+ _write_env_file(updates)+ except Exception as e:+ logger.warning("Failed to write .env: %s", e)+ return {"success": False, "message": "Could not write .env file."}return {"success": True}@app.post("/api/settings/test-instantly")async def test_instantly(request: Request):"""Test an Instantly API key."""- data = await request.json()- api_key = data.get("api_key", "")+ try:+ data = await request.json()+ except Exception:+ data = {}+ api_key = str(data.get("api_key", "") or "")if not api_key:return {"success": False, "message": "No API key provided."}try:@@ -295,21 +316,39 @@ async def get_company_contacts(company_id: str):@app.post("/api/feedback")async def add_feedback(request: Request):"""Add a comment/feedback on any entity."""- data = await request.json()- entity_type = data.get("entity_type", "")- entity_id = data.get("entity_id", "")- comment = data.get("comment", "")+ try:+ data = await request.json()+ except Exception:+ data = {}+ if not isinstance(data, dict):+ data = {}+ entity_type = str(data.get("entity_type", "") or "")[:50]+ entity_id = str(data.get("entity_id", "") or "")[:100]+ comment = str(data.get("comment", "") or "").strip()[:4000]if not comment:return {"success": False, "message": "Comment is required."}feedback_id = uuid.uuid4().hex[:12]- db_path = str(DB_PATH)- if DB_PATH.exists():- async with aiosqlite.connect(db_path) as db:+ try:+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)+ async with aiosqlite.connect(str(DB_PATH)) as db:+ # Ensure the table exists so feedback works even on a fresh install+ await db.execute(+ """CREATE TABLE IF NOT EXISTS feedback (+ id TEXT PRIMARY KEY,+ entity_type TEXT,+ entity_id TEXT,+ comment TEXT,+ created_at TEXT DEFAULT (datetime('now'))+ )"""+ )await db.execute("INSERT INTO feedback (id, entity_type, entity_id, comment) VALUES (?, ?, ?, ?)",(feedback_id, entity_type, entity_id, comment),)await db.commit()+ except Exception as e:+ logger.warning("Failed to save feedback: %s", e)+ return {"success": False, "message": "Could not save feedback."}return {"success": True, "id": feedback_id}@@ -345,18 +384,29 @@ async def start_harvey():# Ensure data dir exists(PROJECT_ROOT / "data").mkdir(parents=True, exist_ok=True)- log_handle = open(LOG_FILE, "a")- _harvey_process = subprocess.Popen(- [sys.executable, "-m", "harvey"],- cwd=str(PROJECT_ROOT),- stdout=log_handle,- stderr=log_handle,- start_new_session=True,- )+ try:+ log_handle = open(LOG_FILE, "a")+ try:+ _harvey_process = subprocess.Popen(+ [sys.executable, "-m", "harvey"],+ cwd=str(PROJECT_ROOT),+ stdout=log_handle,+ stderr=log_handle,+ start_new_session=True,+ )+ finally:+ # Child holds its own copies of the fds; don't leak ours.+ log_handle.close()+ except Exception as e:+ logger.warning("Failed to start Harvey: %s", e)+ return {"success": False, "message": f"Failed to start Harvey: {e}"}_harvey_started_at = datetime.now()# Write PID file- PID_FILE.write_text(str(_harvey_process.pid))+ try:+ PID_FILE.write_text(str(_harvey_process.pid))+ except OSError as e:+ logger.warning("Could not write PID file: %s", e)return {"success": True, "pid": _harvey_process.pid}@@ -383,9 +433,9 @@ async def stop_harvey():# Force kill if still runningtry:os.kill(pid, signal.SIGKILL)- except ProcessLookupError:+ except (ProcessLookupError, PermissionError):pass- except ProcessLookupError:+ except (ProcessLookupError, PermissionError):pass_harvey_process = None@@ -401,8 +451,13 @@ async def get_harvey_logs():if not LOG_FILE.exists():return {"lines": []}try:- text = LOG_FILE.read_text()- lines = text.strip().splitlines()[-50:]+ # Tail only the last 64KB so a huge log file never blocks the UI+ with open(LOG_FILE, "rb") as f:+ f.seek(0, os.SEEK_END)+ size = f.tell()+ f.seek(max(0, size - 65536))+ text = f.read().decode("utf-8", errors="replace")+ lines = text.strip().splitlines()[-100:]return {"lines": lines}except Exception:return {"lines": []}@@ -506,267 +561,441 @@ async def dashboard():return DASHBOARD_HTML-DASHBOARD_HTML = """<!DOCTYPE html>+DASHBOARD_HTML = r"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">-<title>Harvey Dashboard</title>+<title>Harvey — Command Deck</title><style>+ :root {+ --bg: #08090c;+ --panel: #0f1216;+ --panel-raised: #141922;+ --border: #1d2430;+ --border-strong: #2b3444;+ --text: #e9ecf2;+ --text-2: #9aa4b4;+ --text-3: #5c6774;+ --accent: #3ecf8e;+ --accent-deep: #22996a;+ --accent-soft: rgba(62, 207, 142, 0.12);+ --blue: #74a8ff;+ --amber: #e5b567;+ --red: #e06c75;+ --purple: #b48ce8;+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;+ }+* { margin: 0; padding: 0; box-sizing: border-box; }+ ::selection { background: rgba(62,207,142,0.25); }++ html { color-scheme: dark; }body {- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;- background: #0a0a0a;- color: #e0e0e0;+ font-family: var(--sans);+ background: var(--bg);+ background-image:+ radial-gradient(1100px 480px at 75% -12%, rgba(62,207,142,0.06), transparent 60%),+ radial-gradient(900px 420px at 8% -10%, rgba(116,168,255,0.05), transparent 55%);+ background-repeat: no-repeat;+ color: var(--text);min-height: 100vh;+ font-size: 14px;+ -webkit-font-smoothing: antialiased;}+ a { color: var(--blue); text-decoration: none; }+ a:hover { text-decoration: underline; }++ /* ── Header ── */header {- background: #111;- border-bottom: 1px solid #222;- padding: 16px 32px;- display: flex;- align-items: center;- justify-content: space-between;+ position: sticky; top: 0; z-index: 100;+ background: rgba(8,9,12,0.82);+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ border-bottom: 1px solid var(--border);+ padding: 14px 32px;+ display: flex; align-items: center; justify-content: space-between; gap: 16px;}- header h1 { font-size: 20px; font-weight: 600; color: #fff; }- header h1 span { color: #666; font-weight: 400; font-size: 14px; margin-left: 8px; }+ .brand { display: flex; align-items: center; gap: 12px; }+ .brand .mark {+ width: 34px; height: 34px; border-radius: 9px;+ background: linear-gradient(145deg, #2fbf82, #17795a);+ box-shadow: 0 0 0 1px rgba(62,207,142,0.35), 0 4px 14px rgba(62,207,142,0.18);+ display: flex; align-items: center; justify-content: center;+ font-weight: 800; font-size: 17px; color: #04140d; letter-spacing: -0.5px;+ }+ .brand h1 { font-size: 17px; font-weight: 700; letter-spacing: -0.3px; line-height: 1.1; }+ .brand .tagline {+ font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px;+ color: var(--text-3); margin-top: 2px; font-weight: 600;+ }- .header-controls { display: flex; align-items: center; gap: 12px; }+ .header-controls { display: flex; align-items: center; gap: 10px; }.harvey-status {display: flex; align-items: center; gap: 8px;- font-size: 13px; color: #888;- padding: 6px 14px;- background: #1a1a1a;- border: 1px solid #333;- border-radius: 6px;+ font-size: 12px; font-weight: 600; color: var(--text-2);+ padding: 7px 14px;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 99px;}-- .status-dot {- width: 8px; height: 8px; border-radius: 50%;+ .status-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }+ .status-dot.running {+ background: var(--accent);+ box-shadow: 0 0 0 0 rgba(62,207,142,0.5);+ animation: pulse 2s infinite;+ }+ .status-dot.stopped { background: #4a5361; }+ .status-dot.offline { background: var(--red); }+ @keyframes pulse {+ 0% { box-shadow: 0 0 0 0 rgba(62,207,142,0.45); }+ 70% { box-shadow: 0 0 0 7px rgba(62,207,142,0); }+ 100% { box-shadow: 0 0 0 0 rgba(62,207,142,0); }}- .status-dot.running { background: #40c060; box-shadow: 0 0 6px #40c060; }- .status-dot.stopped { background: #666; }.refresh-btn {- background: #1a1a1a; border: 1px solid #333; color: #888;- padding: 6px 14px; border-radius: 6px; cursor: pointer; font-size: 13px;+ background: var(--panel); border: 1px solid var(--border); color: var(--text-2);+ padding: 7px 14px; border-radius: 99px; cursor: pointer;+ font-size: 12px; font-weight: 600; font-family: inherit;+ transition: border-color .15s, color .15s;}- .refresh-btn:hover { border-color: #555; color: #ccc; }+ .refresh-btn:hover { border-color: var(--border-strong); color: var(--text); }+ /* ── Nav ── */nav {- background: #111; border-bottom: 1px solid #222;- padding: 0 32px; display: flex; gap: 0; overflow-x: auto;+ position: sticky; top: 63px; z-index: 99;+ background: rgba(8,9,12,0.82);+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ border-bottom: 1px solid var(--border);+ padding: 0 24px; display: flex; overflow-x: auto;+ scrollbar-width: none;}+ nav::-webkit-scrollbar { display: none; }nav button {- background: none; border: none; border-bottom: 2px solid transparent;- color: #777; padding: 12px 16px; cursor: pointer; font-size: 13px;- transition: all 0.15s; white-space: nowrap;+ position: relative;+ background: none; border: none;+ color: var(--text-3); padding: 13px 14px; cursor: pointer;+ font-size: 13px; font-weight: 500; font-family: inherit;+ transition: color .15s; white-space: nowrap;+ }+ nav button:hover { color: var(--text-2); }+ nav button.active { color: var(--text); font-weight: 600; }+ nav button.active::after {+ content: ""; position: absolute; left: 14px; right: 14px; bottom: -1px;+ height: 2px; border-radius: 2px 2px 0 0; background: var(--accent);}- nav button:hover { color: #bbb; }- nav button.active { color: #fff; border-bottom-color: #fff; }- main { padding: 24px 32px; max-width: 1400px; }+ main { padding: 28px 32px 64px; max-width: 1400px; margin: 0 auto; }.section { display: none; }- .section.active { display: block; }+ .section.active { display: block; animation: rise .25s ease; }+ @keyframes rise { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }++ .section-head { margin-bottom: 20px; }+ .section-head h2 { font-size: 20px; font-weight: 700; letter-spacing: -0.4px; }+ .section-head p { font-size: 13px; color: var(--text-3); margin-top: 4px; }/* ── Cards ── */.card {- background: #141414; border: 1px solid #222; border-radius: 10px;+ background: var(--panel); border: 1px solid var(--border); border-radius: 12px;padding: 24px; margin-bottom: 16px;}- .card h2 { font-size: 16px; color: #fff; margin-bottom: 16px; }- .card h3 { font-size: 14px; color: #ccc; margin-bottom: 12px; }+ .card h2 { font-size: 15px; font-weight: 650; letter-spacing: -0.2px; margin-bottom: 16px; }- /* ── Stats ── */+ /* ── Stat cards ── */.stats-grid {- display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));- gap: 16px; margin-bottom: 32px;+ display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 14px; margin-bottom: 28px;+ }+ .stat-card {+ position: relative; overflow: hidden;+ background: linear-gradient(180deg, var(--panel-raised), var(--panel));+ border: 1px solid var(--border); border-radius: 12px; padding: 20px;+ transition: border-color .2s;+ }+ .stat-card:hover { border-color: var(--border-strong); }+ .stat-card::before {+ content: ""; position: absolute; top: 0; left: 20px; right: 20px; height: 1px;+ background: linear-gradient(90deg, transparent, rgba(62,207,142,0.35), transparent);+ }+ .stat-card .label {+ font-size: 10.5px; text-transform: uppercase; letter-spacing: 1.2px;+ color: var(--text-3); font-weight: 700; margin-bottom: 10px;+ }+ .stat-card .value {+ font-size: 34px; font-weight: 750; letter-spacing: -1px; line-height: 1;+ font-variant-numeric: tabular-nums;}- .stat-card { background: #141414; border: 1px solid #222; border-radius: 10px; padding: 20px; }- .stat-card .label { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 8px; }- .stat-card .value { font-size: 32px; font-weight: 700; color: #fff; }- .stat-card .breakdown { margin-top: 10px; font-size: 12px; color: #555; line-height: 1.6; }+ .stat-card .breakdown { margin-top: 12px; display: flex; flex-wrap: wrap; gap: 5px; }+ .chip {+ font-size: 11px; font-weight: 550; color: var(--text-2);+ background: rgba(255,255,255,0.04); border: 1px solid var(--border);+ padding: 2px 9px; border-radius: 99px; font-variant-numeric: tabular-nums;+ }+ .chip b { color: var(--text); font-weight: 650; }- /* ── Progress bar ── */+ /* ── Progress ── */.progress-wrap { margin-bottom: 24px; }.progress-label { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 13px; }- .progress-label .pct { color: #fff; font-weight: 600; }- .progress-label .text { color: #666; }- .progress-bar { background: #1a1a1a; border-radius: 8px; height: 12px; overflow: hidden; }- .progress-fill { height: 100%; border-radius: 8px; transition: width 0.5s ease; }- .progress-fill.green { background: linear-gradient(90deg, #2d8a4e, #40c060); }- .progress-fill.yellow { background: linear-gradient(90deg, #a08020, #d0b040); }+ .progress-label .pct { color: var(--text); font-weight: 700; font-variant-numeric: tabular-nums; }+ .progress-label .text { color: var(--text-3); }+ .progress-bar { background: rgba(255,255,255,0.05); border-radius: 99px; height: 8px; overflow: hidden; }+ .progress-fill { height: 100%; border-radius: 99px; transition: width .5s ease; }+ .progress-fill.green { background: linear-gradient(90deg, var(--accent-deep), var(--accent)); }+ .progress-fill.yellow { background: linear-gradient(90deg, #a3801f, var(--amber)); }/* ── Setup checklist ── */.check-item {- display: flex; align-items: flex-start; gap: 12px;- padding: 14px 0; border-bottom: 1px solid #1a1a1a;+ display: flex; align-items: flex-start; gap: 14px;+ padding: 14px 0; border-bottom: 1px solid var(--border);}.check-item:last-child { border-bottom: none; }- .check-icon { font-size: 16px; min-width: 24px; text-align: center; padding-top: 1px; }- .check-icon.done { color: #40c060; }- .check-icon.pending { color: #555; }+ .check-icon {+ width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0;+ display: flex; align-items: center; justify-content: center;+ font-size: 12px; margin-top: 1px;+ }+ .check-icon.done { background: var(--accent-soft); color: var(--accent); border: 1px solid rgba(62,207,142,0.3); }+ .check-icon.pending { background: transparent; color: var(--text-3); border: 1px dashed var(--border-strong); }.check-info { flex: 1; }- .check-label { font-size: 14px; color: #ddd; margin-bottom: 2px; }- .check-label.done { color: #888; }- .check-help { font-size: 12px; color: #555; margin-top: 4px; }- .optional-tag { font-size: 10px; background: #1a1a2a; color: #8080ff; padding: 2px 8px; border-radius: 4px; margin-left: 8px; }+ .check-label { font-size: 14px; font-weight: 550; color: var(--text); }+ .check-label.done { color: var(--text-3); text-decoration: line-through; text-decoration-color: rgba(255,255,255,0.15); }+ .check-help { font-size: 12.5px; color: var(--text-3); margin-top: 4px; line-height: 1.5; }+ .optional-tag {+ font-size: 9.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px;+ background: rgba(116,168,255,0.1); color: var(--blue);+ padding: 2px 8px; border-radius: 99px; margin-left: 8px; vertical-align: 1px;+ }+ .subhead {+ margin: 20px 0 4px; font-size: 10.5px; color: var(--text-3);+ text-transform: uppercase; letter-spacing: 1.2px; font-weight: 700;+ }/* ── Forms ── */.form-group { margin-bottom: 16px; }- .form-label { display: block; font-size: 12px; color: #888; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.3px; }+ .form-label {+ display: block; font-size: 11px; color: var(--text-2); margin-bottom: 7px;+ text-transform: uppercase; letter-spacing: 0.8px; font-weight: 650;+ }.form-input {- width: 100%; padding: 10px 14px; background: #1a1a1a; border: 1px solid #333;- border-radius: 6px; color: #e0e0e0; font-size: 14px; font-family: inherit;+ width: 100%; padding: 10px 14px;+ background: rgba(255,255,255,0.03); border: 1px solid var(--border-strong);+ border-radius: 8px; color: var(--text); font-size: 14px; font-family: inherit;+ transition: border-color .15s, box-shadow .15s;}- .form-input:focus { outline: none; border-color: #555; }- .form-input::placeholder { color: #444; }- .form-row { display: flex; gap: 12px; align-items: flex-end; }+ .form-input:focus { outline: none; border-color: var(--accent-deep); box-shadow: 0 0 0 3px rgba(62,207,142,0.12); }+ .form-input::placeholder { color: var(--text-3); }+ .form-row { display: flex; gap: 10px; align-items: flex-end; }.form-row .form-group { flex: 1; }- .form-hint { font-size: 11px; color: #555; margin-top: 4px; }+ .card .lede { font-size: 13px; color: var(--text-2); margin: -6px 0 18px; line-height: 1.6; }.btn {- padding: 8px 20px; border: none; border-radius: 6px;- font-size: 13px; cursor: pointer; font-family: inherit;- transition: all 0.15s;+ padding: 9px 20px; border: 1px solid transparent; border-radius: 8px;+ font-size: 13px; font-weight: 600; cursor: pointer; font-family: inherit;+ transition: background .15s, border-color .15s, transform .05s;}+ .btn:active { transform: translateY(1px); }.btn:disabled { opacity: 0.5; cursor: not-allowed; }- .btn-primary { background: #2d8a4e; color: #fff; }- .btn-primary:hover:not(:disabled) { background: #38a05c; }- .btn-danger { background: #8a2d2d; color: #fff; }- .btn-danger:hover:not(:disabled) { background: #a03838; }- .btn-secondary { background: #1a1a1a; border: 1px solid #333; color: #aaa; }- .btn-secondary:hover:not(:disabled) { border-color: #555; color: #ddd; }- .btn-sm { padding: 6px 14px; font-size: 12px; }-+ .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .btn-primary { background: var(--accent-deep); color: #eafff5; box-shadow: inset 0 1px 0 rgba(255,255,255,0.12); }+ .btn-primary:hover:not(:disabled) { background: #2ab27c; }+ .btn-danger { background: #8a2f36; color: #ffe9ea; }+ .btn-danger:hover:not(:disabled) { background: #a13940; }+ .btn-secondary { background: rgba(255,255,255,0.03); border-color: var(--border-strong); color: var(--text-2); }+ .btn-secondary:hover:not(:disabled) { color: var(--text); border-color: #3a4557; }+ .btn-sm { padding: 6px 13px; font-size: 12px; }.btn-group { display: flex; gap: 10px; margin-top: 16px; }- .test-result { font-size: 13px; margin-top: 8px; padding: 8px 12px; border-radius: 6px; }- .test-result.success { background: #152a1a; color: #40c060; }- .test-result.error { background: #2a1515; color: #e05050; }+ .test-result { font-size: 13px; margin-top: 10px; padding: 9px 13px; border-radius: 8px; }+ .test-result.success { background: var(--accent-soft); color: var(--accent); border: 1px solid rgba(62,207,142,0.25); }+ .test-result.error { background: rgba(224,108,117,0.1); color: var(--red); border: 1px solid rgba(224,108,117,0.25); }+ .test-result.pending { background: rgba(255,255,255,0.04); color: var(--text-2); border: 1px solid var(--border); }/* ── Controls ── */- .control-panel { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }- @media (max-width: 800px) { .control-panel { grid-template-columns: 1fr; } }-- .status-big { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }- .status-big .dot { width: 14px; height: 14px; border-radius: 50%; }- .status-big .dot.running { background: #40c060; box-shadow: 0 0 8px #40c060; }- .status-big .dot.stopped { background: #666; }- .status-big .label { font-size: 18px; font-weight: 600; }- .status-big .label.running { color: #40c060; }- .status-big .label.stopped { color: #888; }- .status-meta { font-size: 12px; color: #555; margin-bottom: 20px; }+ .control-panel { display: grid; grid-template-columns: 1fr 1.4fr; gap: 16px; }+ @media (max-width: 900px) { .control-panel { grid-template-columns: 1fr; } }++ .status-big { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }+ .status-big .dot { width: 13px; height: 13px; border-radius: 50%; }+ .status-big .dot.running { background: var(--accent); animation: pulse 2s infinite; }+ .status-big .dot.stopped { background: #4a5361; }+ .status-big .label { font-size: 19px; font-weight: 700; letter-spacing: -0.3px; }+ .status-big .label.running { color: var(--accent); }+ .status-big .label.stopped { color: var(--text-2); }+ .status-meta { font-size: 12px; color: var(--text-3); margin-bottom: 18px; font-variant-numeric: tabular-nums; min-height: 15px; }.log-viewer {- background: #0a0a0a; border: 1px solid #222; border-radius: 8px;- padding: 16px; font-family: 'SF Mono', Monaco, 'Consolas', monospace;- font-size: 11px; color: #888; line-height: 1.6;- max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-all;+ background: #07080a; border: 1px solid var(--border); border-radius: 10px;+ padding: 14px 16px; font-family: var(--mono);+ font-size: 11.5px; color: #8fa39a; line-height: 1.65;+ max-height: 420px; overflow-y: auto; white-space: pre-wrap; word-break: break-all;}/* ── Help ── */- .help-section { margin-bottom: 24px; }- .help-section h2 { font-size: 18px; color: #fff; margin-bottom: 12px; }- .help-section p { font-size: 14px; color: #aaa; line-height: 1.7; margin-bottom: 12px; }- .help-section code { background: #1a1a1a; padding: 2px 8px; border-radius: 4px; font-size: 13px; color: #ccc; }+ .help-section { margin-bottom: 28px; }+ .help-section h2 { font-size: 17px; font-weight: 700; letter-spacing: -0.3px; margin-bottom: 10px; }+ .help-section p { font-size: 14px; color: var(--text-2); line-height: 1.7; margin-bottom: 10px; }+ .help-section code { background: rgba(255,255,255,0.05); padding: 2px 7px; border-radius: 5px; font-size: 12.5px; font-family: var(--mono); color: var(--text); }.help-section pre {- background: #141414; border: 1px solid #222; border-radius: 8px;- padding: 16px; font-size: 13px; color: #aaa; line-height: 1.6;+ background: var(--panel); border: 1px solid var(--border); border-radius: 10px;+ padding: 16px; font-size: 12.5px; font-family: var(--mono); color: var(--text-2); line-height: 1.7;overflow-x: auto; margin: 12px 0;}.file-table { width: 100%; font-size: 13px; border-collapse: collapse; }- .file-table td { padding: 8px 12px; border-bottom: 1px solid #1a1a1a; }- .file-table td:first-child { color: #ccc; font-family: monospace; white-space: nowrap; width: 200px; }- .file-table td:last-child { color: #888; }+ .file-table td { padding: 9px 12px; border-bottom: 1px solid var(--border); }+ .file-table tr:last-child td { border-bottom: none; }+ .file-table td:first-child { color: var(--text); font-family: var(--mono); font-size: 12px; white-space: nowrap; width: 220px; }+ .file-table td:last-child { color: var(--text-2); }details { margin-bottom: 8px; }details summary {- cursor: pointer; padding: 12px 16px; background: #141414; border: 1px solid #222;- border-radius: 8px; font-size: 14px; color: #ccc; list-style: none;+ cursor: pointer; padding: 12px 16px; background: var(--panel); border: 1px solid var(--border);+ border-radius: 10px; font-size: 13.5px; font-weight: 550; color: var(--text-2); list-style: none;+ transition: color .15s;}+ details summary:hover { color: var(--text); }details summary::-webkit-details-marker { display: none; }- details summary::before { content: "+ "; color: #555; }- details[open] summary::before { content: "- "; }- details[open] summary { border-radius: 8px 8px 0 0; border-bottom: none; }+ details summary::before { content: "+"; display: inline-block; width: 18px; color: var(--accent); font-weight: 700; }+ details[open] summary::before { content: "–"; }+ details[open] summary { border-radius: 10px 10px 0 0; border-bottom: none; color: var(--text); }details .faq-body {- padding: 16px; background: #141414; border: 1px solid #222; border-top: none;- border-radius: 0 0 8px 8px; font-size: 13px; color: #999; line-height: 1.6;+ padding: 4px 16px 16px 34px; background: var(--panel); border: 1px solid var(--border); border-top: none;+ border-radius: 0 0 10px 10px; font-size: 13px; color: var(--text-2); line-height: 1.7;}/* ── Toast ── */.toast {position: fixed; bottom: 24px; right: 24px; padding: 12px 20px;- border-radius: 8px; font-size: 13px; z-index: 1000;- animation: fadeIn 0.2s, fadeOut 0.3s 2s forwards;+ border-radius: 10px; font-size: 13px; font-weight: 550; z-index: 1000;+ box-shadow: 0 12px 32px rgba(0,0,0,0.5);+ animation: toastIn .2s ease, toastOut .3s 2.2s forwards;}- .toast.success { background: #152a1a; color: #40c060; border: 1px solid #2d8a4e; }- .toast.error { background: #2a1515; color: #e05050; border: 1px solid #8a2d2d; }- @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; } }- @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }+ .toast.success { background: #0d2a1d; color: var(--accent); border: 1px solid rgba(62,207,142,0.4); }+ .toast.error { background: #2c1416; color: var(--red); border: 1px solid rgba(224,108,117,0.4); }+ @keyframes toastIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; } }+ @keyframes toastOut { from { opacity: 1; } to { opacity: 0; transform: translateY(6px); } }/* ── Tables ── */+ .table-card {+ background: var(--panel); border: 1px solid var(--border); border-radius: 12px;+ overflow-x: auto;+ }table { width: 100%; border-collapse: collapse; font-size: 13px; }- th { text-align: left; padding: 10px 14px; border-bottom: 1px solid #222; color: #666; font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; }- td { padding: 12px 14px; border-bottom: 1px solid #1a1a1a; vertical-align: top; max-width: 300px; overflow: hidden; text-overflow: ellipsis; }- tr:hover td { background: #151515; }-- .badge { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 11px; font-weight: 500; }- .badge-new { background: #1a2332; color: #4a9eff; }- .badge-contacted { background: #2a2215; color: #f0a030; }- .badge-replied { background: #152a1a; color: #40c060; }- .badge-meeting { background: #2a1530; color: #c050e0; }- .badge-draft { background: #1a1a2a; color: #8080ff; }- .badge-active { background: #152a1a; color: #40c060; }- .badge-open { background: #2a2215; color: #f0a030; }- .badge-closed { background: #1a1a1a; color: #666; }- .badge-lost { background: #2a1515; color: #e05050; }- .badge-interested { background: #152a1a; color: #40c060; }- .badge-objection { background: #2a2215; color: #f0a030; }- .badge-not_interested { background: #2a1515; color: #e05050; }-- .campaign-card { background: #141414; border: 1px solid #222; border-radius: 10px; padding: 24px; margin-bottom: 20px; }- .campaign-card h3 { font-size: 16px; color: #fff; margin-bottom: 4px; }- .campaign-card .meta { font-size: 12px; color: #555; margin-bottom: 16px; display: flex; gap: 16px; align-items: center; }-- .email-step { border-left: 3px solid #222; padding: 16px 20px; margin-bottom: 12px; margin-left: 8px; }- .email-step .step-num { font-size: 11px; color: #555; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }- .email-step .subject { font-size: 14px; font-weight: 600; color: #ddd; margin-bottom: 8px; }- .email-step .body { font-size: 13px; color: #888; line-height: 1.7; white-space: pre-wrap; }-- .convo-card { background: #141414; border: 1px solid #222; border-radius: 10px; padding: 24px; margin-bottom: 16px; }- .convo-card h3 { font-size: 15px; color: #fff; margin-bottom: 4px; }- .convo-card .meta { font-size: 12px; color: #555; margin-bottom: 16px; display: flex; gap: 16px; align-items: center; }-- .thread-msg { padding: 12px 16px; margin-bottom: 8px; border-radius: 8px; max-width: 80%; font-size: 13px; line-height: 1.6; white-space: pre-wrap; }- .thread-msg.sent { background: #1a2332; color: #b0d0ff; margin-left: auto; }- .thread-msg.received { background: #1a1a1a; color: #ccc; }- .thread-msg .sender { font-size: 11px; color: #666; margin-bottom: 4px; }-- .activity-item { display: flex; gap: 16px; padding: 12px 0; border-bottom: 1px solid #1a1a1a; font-size: 13px; align-items: center; }- .activity-item .time { color: #444; font-size: 12px; min-width: 140px; font-variant-numeric: tabular-nums; }- .activity-item .agent { color: #666; min-width: 80px; }- .activity-item .action { color: #aaa; }-- .empty { text-align: center; padding: 60px 20px; color: #444; font-size: 14px; }- .empty .big { font-size: 40px; margin-bottom: 16px; }+ th {+ text-align: left; padding: 11px 16px; border-bottom: 1px solid var(--border);+ color: var(--text-3); font-weight: 700; font-size: 10.5px;+ text-transform: uppercase; letter-spacing: 1px; white-space: nowrap;+ background: rgba(255,255,255,0.015);+ }+ td {+ padding: 12px 16px; border-bottom: 1px solid var(--border); vertical-align: top;+ max-width: 300px; overflow: hidden; text-overflow: ellipsis; color: var(--text-2);+ }+ td:first-child { color: var(--text); font-weight: 550; }+ tr:last-child td { border-bottom: none; }+ tbody tr { transition: background .1s; }+ tbody tr:hover td { background: rgba(255,255,255,0.02); }+ .verified { color: var(--accent); }+ .muted { color: var(--text-3); }++ .badge {+ display: inline-flex; align-items: center; gap: 6px;+ padding: 3px 10px; border-radius: 99px; font-size: 11px; font-weight: 650;+ border: 1px solid transparent; white-space: nowrap;+ }+ .badge::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; }+ .badge-new { background: rgba(116,168,255,0.1); color: var(--blue); border-color: rgba(116,168,255,0.22); }+ .badge-contacted, .badge-open, .badge-objection { background: rgba(229,181,103,0.1); color: var(--amber); border-color: rgba(229,181,103,0.22); }+ .badge-replied, .badge-active, .badge-interested { background: var(--accent-soft); color: var(--accent); border-color: rgba(62,207,142,0.25); }+ .badge-meeting { background: rgba(180,140,232,0.12); color: var(--purple); border-color: rgba(180,140,232,0.25); }+ .badge-draft { background: rgba(255,255,255,0.05); color: var(--text-2); border-color: var(--border-strong); }+ .badge-closed { background: rgba(255,255,255,0.04); color: var(--text-3); border-color: var(--border); }+ .badge-lost, .badge-not_interested { background: rgba(224,108,117,0.1); color: var(--red); border-color: rgba(224,108,117,0.22); }+ .badge-unknown { background: rgba(255,255,255,0.04); color: var(--text-3); border-color: var(--border); }++ .campaign-card, .convo-card {+ background: var(--panel); border: 1px solid var(--border); border-radius: 12px;+ padding: 24px; margin-bottom: 16px;+ }+ .campaign-card h3, .convo-card h3 { font-size: 16px; font-weight: 700; letter-spacing: -0.2px; margin-bottom: 6px; }+ .campaign-card .meta, .convo-card .meta {+ font-size: 12px; color: var(--text-3); margin-bottom: 18px;+ display: flex; gap: 14px; align-items: center; flex-wrap: wrap;+ }++ .email-step {+ border-left: 2px solid var(--border-strong); padding: 14px 20px; margin: 0 0 12px 6px;+ border-radius: 0 10px 10px 0; background: rgba(255,255,255,0.015);+ }+ .email-step .step-num {+ font-size: 10px; color: var(--accent); text-transform: uppercase;+ letter-spacing: 1px; font-weight: 700; margin-bottom: 7px;+ }+ .email-step .subject { font-size: 14px; font-weight: 650; margin-bottom: 8px; }+ .email-step .body { font-size: 13px; color: var(--text-2); line-height: 1.7; white-space: pre-wrap; }++ .thread-msg {+ padding: 12px 16px; margin-bottom: 8px; border-radius: 12px; max-width: 78%;+ font-size: 13px; line-height: 1.6; white-space: pre-wrap;+ }+ .thread-msg.sent { background: rgba(62,207,142,0.08); border: 1px solid rgba(62,207,142,0.16); color: #cfeee0; margin-left: auto; border-bottom-right-radius: 4px; }+ .thread-msg.received { background: rgba(255,255,255,0.04); border: 1px solid var(--border); color: var(--text-2); border-bottom-left-radius: 4px; }+ .thread-msg .sender { font-size: 10.5px; color: var(--text-3); margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.6px; font-weight: 700; }++ .activity-feed { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 8px 20px; }+ .activity-item { display: flex; gap: 18px; padding: 12px 0; border-bottom: 1px solid var(--border); font-size: 13px; align-items: baseline; }+ .activity-item:last-child { border-bottom: none; }+ .activity-item .time { color: var(--text-3); font-size: 12px; min-width: 130px; font-variant-numeric: tabular-nums; }+ .activity-item .agent {+ color: var(--accent); min-width: 84px; font-size: 11px; font-weight: 700;+ text-transform: uppercase; letter-spacing: 0.8px;+ }+ .activity-item .action { color: var(--text-2); }++ /* ── Empty states ── */+ .empty {+ text-align: center; padding: 72px 24px;+ background: var(--panel); border: 1px dashed var(--border-strong); border-radius: 12px;+ }+ .empty .glyph {+ width: 46px; height: 46px; margin: 0 auto 18px; border-radius: 12px;+ background: rgba(255,255,255,0.03); border: 1px solid var(--border);+ display: flex; align-items: center; justify-content: center;+ font-size: 20px; color: var(--text-3);+ }+ .empty .title { font-size: 15px; font-weight: 650; color: var(--text); margin-bottom: 6px; }+ .empty .copy { font-size: 13px; color: var(--text-3); line-height: 1.6; max-width: 420px; margin: 0 auto; }+ .empty .copy b { color: var(--text-2); font-weight: 600; }++ @media (max-width: 700px) {+ header, main { padding-left: 18px; padding-right: 18px; }+ nav { padding: 0 10px; }+ .brand .tagline { display: none; }+ }</style></head><body><header>- <h1>Harvey <span>Always Be Closing</span></h1>+ <div class="brand">+ <div class="mark">H</div>+ <div>+ <h1>Harvey</h1>+ <div class="tagline">Always Be Closing</div>+ </div>+ </div><div class="header-controls"><div class="harvey-status" id="header-status">- <div class="status-dot stopped" id="header-dot"></div>- <span id="header-status-text">Checking...</span>+ <span class="status-dot stopped" id="header-dot"></span>+ <span id="header-status-text">Checking…</span></div><button class="refresh-btn" onclick="loadCurrentTab()">Refresh</button></div>@@ -787,55 +1016,62 @@ DASHBOARD_HTML = """<!DOCTYPE html><main>-<!-- ── Setup ── -->+<!-- Setup --><div id="setup" class="section active">+ <div class="section-head"><h2>Setup</h2><p>Everything Harvey needs before it can start closing.</p></div><div class="card">- <h2>Setup Progress</h2><div class="progress-wrap" id="setup-progress"></div><div id="setup-checklist"></div></div></div>-<!-- ── Overview ── -->+<!-- Overview --><div id="overview" class="section">+ <div class="section-head"><h2>Pipeline Overview</h2><p>Live counts from Harvey's local database. Refreshes automatically.</p></div><div class="stats-grid" id="stats-grid"></div></div>-<!-- ── Companies ── -->+<!-- Companies --><div id="companies" class="section">+ <div class="section-head"><h2>Companies</h2><p>Organizations Harvey has researched. Click a row to see its contacts.</p></div><div id="companies-list"></div></div>-<!-- ── Contacts ── -->+<!-- Contacts --><div id="prospects" class="section">+ <div class="section-head"><h2>Contacts</h2><p>People Harvey has found and verified.</p></div><div id="prospects-table"></div></div>-<!-- ── Campaigns ── -->+<!-- Campaigns --><div id="campaigns" class="section">+ <div class="section-head"><h2>Campaigns</h2><p>Email sequences Harvey has written and deployed.</p></div><div id="campaigns-list"></div></div>-<!-- ── Conversations ── -->+<!-- Conversations --><div id="conversations" class="section">+ <div class="section-head"><h2>Conversations</h2><p>Every reply, and how Harvey handled it.</p></div><div id="conversations-list"></div></div>-<!-- ── Activity ── -->+<!-- Activity --><div id="activity" class="section">+ <div class="section-head"><h2>Activity</h2><p>A running log of every action Harvey's agents have taken.</p></div><div id="activity-list"></div></div>-<!-- ── Settings ── -->+<!-- Settings --><div id="settings" class="section">+ <div class="section-head"><h2>Settings</h2><p>Credentials are stored locally in <span style="font-family:var(--mono);font-size:12px">.env</span> — never sent anywhere except the services themselves.</p></div><div class="card"><h2>Instantly (Email Platform)</h2>- <p style="font-size:13px;color:#888;margin-bottom:16px">Required. Get your API key from <a href="https://app.instantly.ai/app/settings/integrations" target="_blank" style="color:#4a9eff">Instantly Settings > Integrations</a>.</p>+ <p class="lede">Required. Get your API key from <a href="https://app.instantly.ai/app/settings/integrations" target="_blank" rel="noopener">Instantly Settings > Integrations</a>.</p><div class="form-group">- <label class="form-label">API Key</label>+ <label class="form-label" for="instantly-key">API Key</label><div class="form-row"><div class="form-group" style="margin-bottom:0">- <input type="password" class="form-input" id="instantly-key" placeholder="Enter your Instantly API key">+ <input type="password" class="form-input" id="instantly-key" placeholder="Enter your Instantly API key" autocomplete="off"></div><button class="btn btn-secondary btn-sm" onclick="toggleVisibility('instantly-key')">Show</button><button class="btn btn-secondary btn-sm" onclick="testInstantly()">Test</button>@@ -847,38 +1083,39 @@ DASHBOARD_HTML = """<!DOCTYPE html><div class="card"><h2>LinkedIn <span class="optional-tag">optional</span></h2>- <p style="font-size:13px;color:#888;margin-bottom:16px">For automated LinkedIn prospecting. Harvey logs in and searches like a human.</p>+ <p class="lede">For automated LinkedIn prospecting. Harvey logs in and searches like a human.</p><div class="form-group">- <label class="form-label">Email / Username</label>- <input type="text" class="form-input" id="linkedin-email" placeholder="[email protected]">+ <label class="form-label" for="linkedin-email">Email / Username</label>+ <input type="text" class="form-input" id="linkedin-email" placeholder="[email protected]" autocomplete="off"></div><div class="form-group">- <label class="form-label">Password</label>- <input type="password" class="form-input" id="linkedin-password" placeholder="Enter password">+ <label class="form-label" for="linkedin-password">Password</label>+ <input type="password" class="form-input" id="linkedin-password" placeholder="Enter password" autocomplete="new-password"></div><button class="btn btn-primary" onclick="saveLinkedIn()">Save</button></div><div class="card"><h2>Cloudflare <span class="optional-tag">optional</span></h2>- <p style="font-size:13px;color:#888;margin-bottom:16px">For deep website crawling with JavaScript rendering during product training. ~$5/month.</p>+ <p class="lede">For deep website crawling with JavaScript rendering during product training. ~$5/month.</p><div class="form-group">- <label class="form-label">Account ID</label>- <input type="text" class="form-input" id="cf-account-id" placeholder="Your Cloudflare Account ID">+ <label class="form-label" for="cf-account-id">Account ID</label>+ <input type="text" class="form-input" id="cf-account-id" placeholder="Your Cloudflare Account ID" autocomplete="off"></div><div class="form-group">- <label class="form-label">API Token</label>- <input type="password" class="form-input" id="cf-api-token" placeholder="Your Cloudflare API Token">+ <label class="form-label" for="cf-api-token">API Token</label>+ <input type="password" class="form-input" id="cf-api-token" placeholder="Your Cloudflare API Token" autocomplete="off"></div><button class="btn btn-primary" onclick="saveCloudflare()">Save</button></div></div>-<!-- ── Controls ── -->+<!-- Controls --><div id="controls" class="section">+ <div class="section-head"><h2>Controls</h2><p>Start and stop Harvey's heartbeat loop, and watch what it's doing.</p></div><div class="control-panel"><div class="card">- <h2>Harvey Controls</h2>+ <h2>Agent</h2><div class="status-big" id="control-status"><div class="dot stopped" id="control-dot"></div><span class="label stopped" id="control-label">Stopped</span>@@ -899,8 +1136,9 @@ DASHBOARD_HTML = """<!DOCTYPE html></div></div>-<!-- ── Help ── -->+<!-- Help --><div id="help" class="section">+ <div class="section-head"><h2>Help</h2><p>What Harvey is, how it works, and how to fix the usual problems.</p></div><div class="help-section"><h2>What is Harvey?</h2>@@ -920,6 +1158,7 @@ DASHBOARD_HTML = """<!DOCTYPE html><div class="help-section"><h2>Where Everything Lives</h2><p>Everything Harvey needs is inside this one project folder. Nothing is stored elsewhere.</p>+ <div class="table-card" style="padding:6px 4px"><table class="file-table"><tr><td>.env</td><td>Your API keys and credentials (never shared or committed)</td></tr><tr><td>harvey.yaml</td><td>Your product info, target customers, and behavior settings</td></tr>@@ -929,6 +1168,7 @@ DASHBOARD_HTML = """<!DOCTYPE html><tr><td>data/harvey.db</td><td>Database with all prospects, campaigns, and conversations</td></tr><tr><td>data/harvey.log</td><td>Log file showing what Harvey is doing</td></tr></table>+ </div></div><div class="help-section">@@ -938,8 +1178,8 @@ DASHBOARD_HTML = """<!DOCTYPE html><summary>Instantly API Key (required)</summary><div class="faq-body"><p>Instantly is the email platform Harvey uses to send campaigns.</p>- <p>1. Sign up at <a href="https://instantly.ai" target="_blank" style="color:#4a9eff">instantly.ai</a> (you need the Growth plan for API access)</p>- <p>2. Go to Settings > Integrations</p>+ <p>1. Sign up at <a href="https://instantly.ai" target="_blank" rel="noopener">instantly.ai</a> (you need the Growth plan for API access)</p>+ <p>2. Go to Settings > Integrations</p><p>3. Copy your API key</p><p>4. Paste it in the Settings tab here</p></div>@@ -957,8 +1197,8 @@ DASHBOARD_HTML = """<!DOCTYPE html><summary>Cloudflare Browser Rendering (optional)</summary><div class="faq-body"><p>This is only used during product training (when Harvey crawls your website to learn about your product). It handles JavaScript-heavy websites that a basic crawler can't read.</p>- <p>1. Sign up at <a href="https://dash.cloudflare.com" target="_blank" style="color:#4a9eff">Cloudflare</a> (paid Workers plan, ~$5/month)</p>- <p>2. Go to Workers & Pages > Browser Rendering</p>+ <p>1. Sign up at <a href="https://dash.cloudflare.com" target="_blank" rel="noopener">Cloudflare</a> (paid Workers plan, ~$5/month)</p>+ <p>2. Go to Workers & Pages > Browser Rendering</p><p>3. Create an API token with Browser Rendering Edit permissions</p><p>4. Enter your Account ID and API Token in the Settings tab</p><p>Without this, Harvey uses a built-in crawler that works fine for most websites but can't render JavaScript.</p>@@ -976,7 +1216,7 @@ DASHBOARD_HTML = """<!DOCTYPE html><details><summary>Instantly API returns 401</summary>- <div class="faq-body">Your API key is wrong, or you need the Growth plan (the free plan doesn't include API access). Double-check the key in Settings > Integrations in your Instantly dashboard.</div>+ <div class="faq-body">Your API key is wrong, or you need the Growth plan (the free plan doesn't include API access). Double-check the key in Settings > Integrations in your Instantly dashboard.</div></details><details>@@ -995,48 +1235,52 @@ DASHBOARD_HTML = """<!DOCTYPE html><script>let currentTab = 'setup';+let companyDrill = false; // true while viewing a single company's contacts+let _companies = [], _prospects = [], _campaigns = [];-function showTab(id, btn) {- currentTab = id;- document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));- document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));- document.getElementById(id).classList.add('active');- if (btn) btn.classList.add('active');- loadCurrentTab();-}+// ── Utilities ──-function loadCurrentTab() {- switch (currentTab) {- case 'setup': loadSetupStatus(); break;- case 'overview': loadStats(); break;- case 'companies': loadCompanies(); break;- case 'prospects': loadProspects(); break;- case 'campaigns': loadCampaigns(); break;- case 'conversations': loadConversations(); break;- case 'activity': loadActivity(); break;- case 'settings': loadSettings(); break;- case 'controls': loadHarveyStatus(); loadLogs(); break;- }+function escHtml(s) {+ if (s === null || s === undefined || s === '') return '';+ return String(s).replace(/[&<>"']/g, ch => (+ {'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]+ ));}function badge(status) {- const cls = 'badge-' + (status || '').replace(/\\s+/g, '_');- return `<span class="badge ${cls}">${status || 'unknown'}</span>`;+ const safe = String(status || 'unknown');+ const cls = 'badge-' + safe.toLowerCase().replace(/[^a-z0-9]+/g, '_');+ return '<span class="badge ' + escHtml(cls) + '">' + escHtml(safe) + '</span>';}function formatDate(d) {if (!d) return '';try {const dt = new Date(d);+ if (isNaN(dt)) return escHtml(d);return dt.toLocaleString('en-US', {month:'short',day:'numeric',hour:'numeric',minute:'2-digit'});- } catch { return d; }+ } catch { return escHtml(d); }}-function escHtml(s) {- if (!s) return '';- const d = document.createElement('div');- d.textContent = s;- return d.innerHTML;+function emptyState(glyph, title, copy) {+ return '<div class="empty"><div class="glyph">' + glyph + '</div>' ++ '<div class="title">' + title + '</div>' ++ '<div class="copy">' + copy + '</div></div>';+}++function offlineState() {+ return emptyState('⚠', 'Dashboard can\'t reach the server',+ 'The dashboard process may have stopped. Restart it with <b>harvey dashboard</b> and refresh this page.');+}++async function api(path, opts) {+ try {+ const r = await fetch(path, opts);+ if (!r.ok) return null;+ return await r.json();+ } catch {+ return null;+ }}function showToast(msg, type) {@@ -1044,7 +1288,7 @@ function showToast(msg, type) {t.className = 'toast ' + type;t.textContent = msg;document.body.appendChild(t);- setTimeout(() => t.remove(), 2500);+ setTimeout(() => t.remove(), 2600);}function toggleVisibility(inputId) {@@ -1052,58 +1296,77 @@ function toggleVisibility(inputId) {el.type = el.type === 'password' ? 'text' : 'password';}+// ── Tabs ──++function showTab(id, btn) {+ currentTab = id;+ if (id === 'companies') companyDrill = false;+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));+ document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));+ document.getElementById(id).classList.add('active');+ if (btn) btn.classList.add('active');+ loadCurrentTab();+}++function loadCurrentTab() {+ switch (currentTab) {+ case 'setup': loadSetupStatus(); break;+ case 'overview': loadStats(); break;+ case 'companies': if (!companyDrill) loadCompanies(); break;+ case 'prospects': loadProspects(); break;+ case 'campaigns': loadCampaigns(); break;+ case 'conversations': loadConversations(); break;+ case 'activity': loadActivity(); break;+ case 'settings': loadSettings(); break;+ case 'controls': loadHarveyStatus(); loadLogs(); break;+ }+}+// ── Setup ──async function loadSetupStatus() {- const r = await fetch('/api/setup-status');- const data = await r.json();+ const data = await api('/api/setup-status');+ if (!data || !data.checks) {+ document.getElementById('setup-progress').innerHTML = '';+ document.getElementById('setup-checklist').innerHTML = offlineState();+ return;+ }const pct = data.percent || 0;const color = pct === 100 ? 'green' : 'yellow';- document.getElementById('setup-progress').innerHTML = `- <div class="progress-label">- <span class="pct">${pct}% complete</span>- <span class="text">${data.completed}/${data.total_required} required steps done</span>- </div>- <div class="progress-bar"><div class="progress-fill ${color}" style="width:${pct}%"></div></div>`;-- const required = data.checks.filter(c => c.required);+ document.getElementById('setup-progress').innerHTML =+ '<div class="progress-label">' ++ '<span class="pct">' + pct + '% complete</span>' ++ '<span class="text">' + data.completed + ' of ' + data.total_required + ' required steps done</span>' ++ '</div>' ++ '<div class="progress-bar"><div class="progress-fill ' + color + '" style="width:' + pct + '%"></div></div>';++ const renderCheck = (c, optional) => {+ const icon = c.done+ ? '<span class="check-icon done">✓</span>'+ : '<span class="check-icon pending">●</span>';+ return '<div class="check-item">' + icon ++ '<div class="check-info">' ++ '<div class="check-label ' + (c.done ? 'done' : '') + '">' + escHtml(c.label) ++ (optional ? ' <span class="optional-tag">optional</span>' : '') + '</div>' ++ (!c.done ? '<div class="check-help">' + escHtml(c.help) + '</div>' : '') ++ '</div></div>';+ };++ let html = data.checks.filter(c => c.required).map(c => renderCheck(c, false)).join('');const optional = data.checks.filter(c => !c.required);-- let html = '';- for (const c of required) {- const icon = c.done ? '<span class="check-icon done">✓</span>' : '<span class="check-icon pending">○</span>';- html += `<div class="check-item">- ${icon}- <div class="check-info">- <div class="check-label ${c.done ? 'done' : ''}">${escHtml(c.label)}</div>- ${!c.done ? `<div class="check-help">${escHtml(c.help)}</div>` : ''}- </div>- </div>`;- }-if (optional.length) {- html += '<div style="margin-top:16px;margin-bottom:8px;font-size:12px;color:#555;text-transform:uppercase;letter-spacing:0.5px">Optional</div>';- for (const c of optional) {- const icon = c.done ? '<span class="check-icon done">✓</span>' : '<span class="check-icon pending">○</span>';- html += `<div class="check-item">- ${icon}- <div class="check-info">- <div class="check-label ${c.done ? 'done' : ''}">${escHtml(c.label)} <span class="optional-tag">optional</span></div>- ${!c.done ? `<div class="check-help">${escHtml(c.help)}</div>` : ''}- </div>- </div>`;- }+ html += '<div class="subhead">Optional</div>';+ html += optional.map(c => renderCheck(c, true)).join('');}-document.getElementById('setup-checklist').innerHTML = html;}// ── Settings ──async function loadSettings() {- const r = await fetch('/api/settings');- const data = await r.json();+ const data = await api('/api/settings');+ if (!data) return;document.getElementById('instantly-key').value = data.instantly_api_key || '';document.getElementById('linkedin-email').value = data.linkedin_email || '';document.getElementById('linkedin-password').value = '';@@ -1114,69 +1377,76 @@ async function loadSettings() {}}-async function saveInstantly() {- const key = document.getElementById('instantly-key').value.trim();- await fetch('/api/settings/env', {- method: 'POST', headers: {'Content-Type':'application/json'},- body: JSON.stringify({INSTANTLY_API_KEY: key})+async function saveEnv(payload, okMsg) {+ const data = await api('/api/settings/env', {+ method: 'POST', headers: {'Content-Type': 'application/json'},+ body: JSON.stringify(payload)});- showToast('Instantly API key saved.', 'success');+ if (data && data.success) showToast(okMsg, 'success');+ else showToast((data && data.message) || 'Save failed — is the dashboard still running?', 'error');}-async function saveLinkedIn() {- const email = document.getElementById('linkedin-email').value.trim();+function saveInstantly() {+ saveEnv({INSTANTLY_API_KEY: document.getElementById('instantly-key').value.trim()}, 'Instantly API key saved.');+}++function saveLinkedIn() {+ const payload = {LINKEDIN_EMAIL: document.getElementById('linkedin-email').value.trim()};const pass = document.getElementById('linkedin-password').value;- const data = {LINKEDIN_EMAIL: email};- if (pass) data.LINKEDIN_PASSWORD = pass;- await fetch('/api/settings/env', {- method: 'POST', headers: {'Content-Type':'application/json'},- body: JSON.stringify(data)- });- showToast('LinkedIn credentials saved.', 'success');+ if (pass) payload.LINKEDIN_PASSWORD = pass;+ saveEnv(payload, 'LinkedIn credentials saved.');}-async function saveCloudflare() {- const id = document.getElementById('cf-account-id').value.trim();- const token = document.getElementById('cf-api-token').value.trim();- await fetch('/api/settings/env', {- method: 'POST', headers: {'Content-Type':'application/json'},- body: JSON.stringify({CLOUDFLARE_ACCOUNT_ID: id, CLOUDFLARE_API_TOKEN: token})- });- showToast('Cloudflare credentials saved.', 'success');+function saveCloudflare() {+ saveEnv({+ CLOUDFLARE_ACCOUNT_ID: document.getElementById('cf-account-id').value.trim(),+ CLOUDFLARE_API_TOKEN: document.getElementById('cf-api-token').value.trim()+ }, 'Cloudflare credentials saved.');}async function testInstantly() {const key = document.getElementById('instantly-key').value.trim();const el = document.getElementById('instantly-test-result');- el.innerHTML = '<div class="test-result" style="background:#1a1a1a;color:#888">Testing...</div>';- const r = await fetch('/api/settings/test-instantly', {- method: 'POST', headers: {'Content-Type':'application/json'},+ el.innerHTML = '<div class="test-result pending">Testing…</div>';+ const data = await api('/api/settings/test-instantly', {+ method: 'POST', headers: {'Content-Type': 'application/json'},body: JSON.stringify({api_key: key})});- const data = await r.json();- el.innerHTML = `<div class="test-result ${data.success ? 'success' : 'error'}">${escHtml(data.message)}</div>`;+ if (!data) {+ el.innerHTML = '<div class="test-result error">Could not reach the dashboard server.</div>';+ return;+ }+ el.innerHTML = '<div class="test-result ' + (data.success ? 'success' : 'error') + '">' + escHtml(data.message) + '</div>';}// ── Controls ──async function loadHarveyStatus() {- const r = await fetch('/api/harvey/status');- const data = await r.json();- const running = data.running;+ const data = await api('/api/harvey/status');+ const headerDot = document.getElementById('header-dot');+ const headerText = document.getElementById('header-status-text');++ if (!data) {+ headerDot.className = 'status-dot offline';+ headerText.textContent = 'Offline';+ return;+ }+ const running = !!data.running;- document.getElementById('header-dot').className = 'status-dot ' + (running ? 'running' : 'stopped');- document.getElementById('header-status-text').textContent = running ? 'Running' : 'Stopped';+ headerDot.className = 'status-dot ' + (running ? 'running' : 'stopped');+ headerText.textContent = running ? 'Harvey is running' : 'Harvey is stopped';document.getElementById('control-dot').className = 'dot ' + (running ? 'running' : 'stopped');- document.getElementById('control-label').className = 'label ' + (running ? 'running' : 'stopped');- document.getElementById('control-label').textContent = running ? 'Running' : 'Stopped';+ const label = document.getElementById('control-label');+ label.className = 'label ' + (running ? 'running' : 'stopped');+ label.textContent = running ? 'Running' : 'Stopped';const meta = document.getElementById('control-meta');if (running && data.pid) {- let info = `PID: ${data.pid}`;- if (data.started_at) info += ` · Started: ${formatDate(data.started_at)}`;+ let info = 'PID ' + escHtml(String(data.pid));+ if (data.started_at) info += ' · started ' + formatDate(data.started_at);meta.innerHTML = info;} else {- meta.innerHTML = '';+ meta.innerHTML = 'Harvey wakes every few minutes, does what needs doing, and sleeps.';}document.getElementById('btn-start').style.display = running ? 'none' : '';@@ -1184,146 +1454,201 @@ async function loadHarveyStatus() {}async function startHarvey() {- document.getElementById('btn-start').disabled = true;- const r = await fetch('/api/harvey/start', {method: 'POST'});- const data = await r.json();- if (data.success) {- showToast('Harvey started.', 'success');- } else {- showToast(data.message || 'Failed to start.', 'error');- }- document.getElementById('btn-start').disabled = false;+ const btn = document.getElementById('btn-start');+ btn.disabled = true;+ const data = await api('/api/harvey/start', {method: 'POST'});+ if (data && data.success) showToast('Harvey started.', 'success');+ else showToast((data && data.message) || 'Failed to start.', 'error');+ btn.disabled = false;loadHarveyStatus();}async function stopHarvey() {- document.getElementById('btn-stop').disabled = true;- const r = await fetch('/api/harvey/stop', {method: 'POST'});- const data = await r.json();- if (data.success) {- showToast('Harvey stopped.', 'success');- } else {- showToast(data.message || 'Failed to stop.', 'error');- }- document.getElementById('btn-stop').disabled = false;+ const btn = document.getElementById('btn-stop');+ btn.disabled = true;+ const data = await api('/api/harvey/stop', {method: 'POST'});+ if (data && data.success) showToast('Harvey stopped.', 'success');+ else showToast((data && data.message) || 'Failed to stop.', 'error');+ btn.disabled = false;loadHarveyStatus();}async function loadLogs() {- const r = await fetch('/api/harvey/logs');- const data = await r.json();+ const data = await api('/api/harvey/logs');const el = document.getElementById('log-viewer');- if (data.lines && data.lines.length) {- el.textContent = data.lines.join('\\n');- el.scrollTop = el.scrollHeight;+ if (data && data.lines && data.lines.length) {+ const stick = el.scrollTop + el.clientHeight >= el.scrollHeight - 30;+ el.textContent = data.lines.join('\n');+ if (stick) el.scrollTop = el.scrollHeight;} else {el.textContent = 'No logs yet. Start Harvey to see activity.';}}-// ── Pipeline Data ──+// ── Pipeline data ──async function loadStats() {- const r = await fetch('/api/stats');- const data = await r.json();+ const grid = document.getElementById('stats-grid');+ const data = await api('/api/stats');+ if (!data) { grid.innerHTML = offlineState(); return; }if (data.error) {- document.getElementById('stats-grid').innerHTML = `<div class="empty"><div class="big">No data yet</div>Start Harvey to begin building your pipeline.</div>`;+ grid.innerHTML = emptyState('◆', 'No pipeline data yet',+ 'Start Harvey from the <b>Controls</b> tab and it will begin prospecting, writing, and sending on its own.');return;}const p = data.prospects || {}, c = data.campaigns || {}, v = data.conversations || {};- const bd = (map) => Object.entries(map).map(([k,v]) => `${k}: ${v}`).join(' · ') || 'none';- document.getElementById('stats-grid').innerHTML = `- <div class="stat-card"><div class="label">Prospects</div><div class="value">${p.total||0}</div><div class="breakdown">${bd(p.by_status||{})}</div></div>- <div class="stat-card"><div class="label">Campaigns</div><div class="value">${c.total||0}</div><div class="breakdown">${bd(c.by_status||{})}</div></div>- <div class="stat-card"><div class="label">Conversations</div><div class="value">${v.total||0}</div><div class="breakdown">${bd(v.by_status||{})}</div></div>- <div class="stat-card"><div class="label">Actions Today</div><div class="value">${data.actions_total||0}</div><div class="breakdown">Claude calls today: ${data.claude_calls_today||0}</div></div>`;+ const chips = (map) => {+ const entries = Object.entries(map || {});+ if (!entries.length) return '<span class="chip muted">none yet</span>';+ return entries.map(([k, n]) =>+ '<span class="chip">' + escHtml(k) + ' <b>' + escHtml(String(n)) + '</b></span>'+ ).join('');+ };+ const card = (label, value, breakdown) =>+ '<div class="stat-card"><div class="label">' + label + '</div>' ++ '<div class="value">' + value + '</div>' ++ '<div class="breakdown">' + breakdown + '</div></div>';++ grid.innerHTML =+ card('Prospects', p.total || 0, chips(p.by_status)) ++ card('Campaigns', c.total || 0, chips(c.by_status)) ++ card('Conversations', v.total || 0, chips(v.by_status)) ++ card('Actions Logged', data.actions_total || 0,+ '<span class="chip">Claude calls today <b>' + escHtml(String(data.claude_calls_today || 0)) + '</b></span>');}async function loadCompanies() {- const r = await fetch('/api/companies');- const data = await r.json();+ companyDrill = false;+ const el = document.getElementById('companies-list');+ const data = await api('/api/companies');+ if (!data) { el.innerHTML = offlineState(); return; }+ _companies = data;if (!data.length) {- document.getElementById('companies-list').innerHTML = `<div class="empty"><div class="big">No companies yet</div>Harvey hasn't researched any companies yet.</div>`;+ el.innerHTML = emptyState('⚲', 'No companies yet',+ 'Harvey\'s Scout agent hasn\'t researched any companies. Finish <b>Setup</b>, then start Harvey from the <b>Controls</b> tab.');return;}- let html = `<table><thead><tr><th>Company</th><th>Domain</th><th>Industry</th><th>Size</th><th>Location</th><th>Contacts</th><th>Source</th><th>Added</th></tr></thead><tbody>`;- for (const c of data) {- const website = c.website || (c.domain ? 'https://'+c.domain : '');- const nameLink = website ? `<a href="${escHtml(website)}" target="_blank" style="color:#4a9eff">${escHtml(c.name)}</a>` : escHtml(c.name);- html += `<tr style="cursor:pointer" onclick="showCompanyContacts('${c.id}', '${escHtml(c.name)}')">- <td>${nameLink}</td><td>${escHtml(c.domain)}</td><td>${escHtml(c.industry)}</td><td>${escHtml(c.company_size)}</td><td>${escHtml(c.location)}</td><td>${c.contact_count||0}</td><td>${escHtml(c.source)}</td><td>${formatDate(c.created_at)}</td></tr>`;- }- document.getElementById('companies-list').innerHTML = html + '</tbody></table>';+ let html = '<div class="table-card"><table><thead><tr><th>Company</th><th>Domain</th><th>Industry</th><th>Size</th><th>Location</th><th>Contacts</th><th>Source</th><th>Added</th></tr></thead><tbody>';+ data.forEach((c, i) => {+ const website = c.website || (c.domain ? 'https://' + c.domain : '');+ const nameLink = website+ ? '<a href="' + escHtml(website) + '" target="_blank" rel="noopener" onclick="event.stopPropagation()">' + escHtml(c.name) + '</a>'+ : escHtml(c.name);+ html += '<tr style="cursor:pointer" onclick="showCompanyContacts(' + i + ')">' ++ '<td>' + nameLink + '</td><td class="muted">' + escHtml(c.domain) + '</td><td>' + escHtml(c.industry) + '</td>' ++ '<td>' + escHtml(c.company_size) + '</td><td>' + escHtml(c.location) + '</td>' ++ '<td>' + (c.contact_count || 0) + '</td><td class="muted">' + escHtml(c.source) + '</td>' ++ '<td class="muted">' + formatDate(c.created_at) + '</td></tr>';+ });+ el.innerHTML = html + '</tbody></table></div>';}-async function showCompanyContacts(companyId, companyName) {- const r = await fetch('/api/companies/' + companyId + '/contacts');- const data = await r.json();- let html = `<div class="card" style="margin-bottom:16px"><h2>${escHtml(companyName)} - Contacts</h2><button class="btn btn-secondary btn-sm" onclick="loadCompanies()" style="margin-bottom:16px">Back to Companies</button>`;- if (!data.length) {- html += '<p style="color:#888">No contacts found at this company.</p></div>';+async function showCompanyContacts(index) {+ const company = _companies[index];+ if (!company) return;+ companyDrill = true;+ const el = document.getElementById('companies-list');+ const data = await api('/api/companies/' + encodeURIComponent(company.id) + '/contacts');+ let html = '<div class="card"><h2>' + escHtml(company.name) + ' — Contacts</h2>' ++ '<button class="btn btn-secondary btn-sm" onclick="loadCompanies()" style="margin-bottom:16px">← Back to Companies</button>';+ if (!data || !data.length) {+ html += '<p style="color:var(--text-3);font-size:13px">No contacts found at this company yet.</p></div>';} else {- html += '<table><thead><tr><th>Name</th><th>Title</th><th>Email</th><th>Phone</th><th>LinkedIn</th><th>Status</th><th>Source</th></tr></thead><tbody>';+ html += '<div class="table-card"><table><thead><tr><th>Name</th><th>Title</th><th>Email</th><th>Phone</th><th>LinkedIn</th><th>Status</th><th>Source</th></tr></thead><tbody>';for (const p of data) {- const emailIcon = p.email_verified ? ' ✓' : '';- const phoneIcon = p.phone_verified ? ' ✓' : '';- html += `<tr><td>${escHtml(p.first_name)} ${escHtml(p.last_name)}</td><td>${escHtml(p.title)}</td><td>${escHtml(p.email)}${emailIcon}</td><td>${escHtml(p.phone)}${phoneIcon}</td><td>${p.linkedin_url ? '<a href="'+escHtml(p.linkedin_url)+'" target="_blank" style="color:#4a9eff">Profile</a>' : ''}</td><td>${badge(p.status)}</td><td>${escHtml(p.source)}</td></tr>`;+ const emailIcon = p.email_verified ? ' <span class="verified">✓</span>' : '';+ const phoneIcon = p.phone_verified ? ' <span class="verified">✓</span>' : '';+ html += '<tr><td>' + escHtml(p.first_name) + ' ' + escHtml(p.last_name) + '</td>' ++ '<td>' + escHtml(p.title) + '</td><td>' + escHtml(p.email) + emailIcon + '</td>' ++ '<td>' + escHtml(p.phone) + phoneIcon + '</td>' ++ '<td>' + (p.linkedin_url ? '<a href="' + escHtml(p.linkedin_url) + '" target="_blank" rel="noopener">Profile</a>' : '') + '</td>' ++ '<td>' + badge(p.status) + '</td><td class="muted">' + escHtml(p.source) + '</td></tr>';}- html += '</tbody></table></div>';+ html += '</tbody></table></div></div>';}- document.getElementById('companies-list').innerHTML = html;+ el.innerHTML = html;}-async function addFeedback(entityType, entityId, promptText) {+async function submitFeedback(entityType, entityId, promptText) {const comment = prompt(promptText || 'Add your feedback:');if (!comment) return;- await fetch('/api/feedback', {- method: 'POST', headers: {'Content-Type':'application/json'},+ const data = await api('/api/feedback', {+ method: 'POST', headers: {'Content-Type': 'application/json'},body: JSON.stringify({entity_type: entityType, entity_id: entityId, comment: comment})});- showToast('Feedback saved.', 'success');+ if (data && data.success) showToast('Feedback saved. Harvey will take it into account.', 'success');+ else showToast((data && data.message) || 'Could not save feedback.', 'error');+}++function fbProspect(i) {+ const p = _prospects[i];+ if (p) submitFeedback('contact', p.id, 'Feedback on this contact:');+}++function fbCampaign(i) {+ const c = _campaigns[i];+ if (c) submitFeedback('campaign', c.id, 'Leave feedback on this campaign:');}async function loadProspects() {- const r = await fetch('/api/prospects');- const data = await r.json();+ const el = document.getElementById('prospects-table');+ const data = await api('/api/prospects');+ if (!data) { el.innerHTML = offlineState(); return; }+ _prospects = data;if (!data.length) {- document.getElementById('prospects-table').innerHTML = `<div class="empty"><div class="big">No prospects yet</div>Harvey hasn't found any prospects yet.</div>`;+ el.innerHTML = emptyState('◉', 'No contacts yet',+ 'Harvey hasn\'t found any prospects. Once it\'s running, the Scout agent searches the web for people matching your ideal customer profile in <b>harvey.yaml</b>.');return;}- let html = `<table><thead><tr><th>Name</th><th>Title</th><th>Company</th><th>Email</th><th>Phone</th><th>Status</th><th>Source</th><th>Added</th><th></th></tr></thead><tbody>`;- for (const p of data) {- const emailV = p.email ? (escHtml(p.email) + (p.email_verified ? ' <span style="color:#40c060">✓</span>' : '')) : '';- const phoneV = p.phone ? (escHtml(p.phone) + (p.phone_verified ? ' <span style="color:#40c060">✓</span>' : '')) : '';- html += `<tr><td>${escHtml(p.first_name)} ${escHtml(p.last_name)}</td><td>${escHtml(p.title)}</td><td>${escHtml(p.company)}</td><td>${emailV}</td><td>${phoneV}</td><td>${badge(p.status)}</td><td>${escHtml(p.source)}</td><td>${formatDate(p.created_at)}</td><td><button class="btn btn-secondary btn-sm" onclick="addFeedback('contact','${p.id}','Feedback on this contact:')">Feedback</button></td></tr>`;- }- document.getElementById('prospects-table').innerHTML = html + '</tbody></table>';+ let html = '<div class="table-card"><table><thead><tr><th>Name</th><th>Title</th><th>Company</th><th>Email</th><th>Phone</th><th>Status</th><th>Source</th><th>Added</th><th></th></tr></thead><tbody>';+ data.forEach((p, i) => {+ const emailV = p.email ? (escHtml(p.email) + (p.email_verified ? ' <span class="verified">✓</span>' : '')) : '';+ const phoneV = p.phone ? (escHtml(p.phone) + (p.phone_verified ? ' <span class="verified">✓</span>' : '')) : '';+ html += '<tr><td>' + escHtml(p.first_name) + ' ' + escHtml(p.last_name) + '</td>' ++ '<td>' + escHtml(p.title) + '</td><td>' + escHtml(p.company) + '</td>' ++ '<td>' + emailV + '</td><td>' + phoneV + '</td><td>' + badge(p.status) + '</td>' ++ '<td class="muted">' + escHtml(p.source) + '</td><td class="muted">' + formatDate(p.created_at) + '</td>' ++ '<td><button class="btn btn-secondary btn-sm" onclick="fbProspect(' + i + ')">Feedback</button></td></tr>';+ });+ el.innerHTML = html + '</tbody></table></div>';}async function loadCampaigns() {- const r = await fetch('/api/campaigns');- const data = await r.json();+ const el = document.getElementById('campaigns-list');+ const data = await api('/api/campaigns');+ if (!data) { el.innerHTML = offlineState(); return; }+ _campaigns = data;if (!data.length) {- document.getElementById('campaigns-list').innerHTML = `<div class="empty"><div class="big">No campaigns yet</div>Harvey hasn't written any email sequences yet.</div>`;+ el.innerHTML = emptyState('✉', 'No campaigns yet',+ 'The Writer agent hasn\'t drafted any sequences. It kicks in automatically once Harvey has scored prospects to write for.');return;}let html = '';- for (const c of data) {+ data.forEach((c, i) => {let stepsHtml = '';for (const step of (c.sequence || [])) {- stepsHtml += `<div class="email-step"><div class="step-num">Email ${step.step||'?'}${step.delay_days ? ` · Send after ${step.delay_days} days`:''}</div><div class="subject">${escHtml(step.subject)}</div><div class="body">${escHtml(step.body)}</div></div>`;+ stepsHtml += '<div class="email-step"><div class="step-num">Email ' + escHtml(String(step.step || '?')) ++ (step.delay_days ? ' · send after ' + escHtml(String(step.delay_days)) + ' days' : '') + '</div>' ++ '<div class="subject">' + escHtml(step.subject) + '</div>' ++ '<div class="body">' + escHtml(step.body) + '</div></div>';}- const pc = (c.prospect_ids||[]).length;- html += `<div class="campaign-card"><h3>${escHtml(c.name||'Untitled Campaign')}</h3><div class="meta">${badge(c.status)}<span>${c.channel||'email'}</span><span>${pc} prospect${pc!==1?'s':''}</span><span>${formatDate(c.created_at)}</span><button class="btn btn-secondary btn-sm" onclick="event.stopPropagation();addFeedback('campaign','${c.id}','Leave feedback on this campaign:')">Feedback</button></div>${stepsHtml||'<div class="empty">No email steps</div>'}</div>`;- }- document.getElementById('campaigns-list').innerHTML = html;+ const pc = (c.prospect_ids || []).length;+ html += '<div class="campaign-card"><h3>' + escHtml(c.name || 'Untitled Campaign') + '</h3>' ++ '<div class="meta">' + badge(c.status) + '<span>' + escHtml(c.channel || 'email') + '</span>' ++ '<span>' + pc + ' prospect' + (pc !== 1 ? 's' : '') + '</span><span>' + formatDate(c.created_at) + '</span>' ++ '<button class="btn btn-secondary btn-sm" onclick="fbCampaign(' + i + ')">Feedback</button></div>' ++ (stepsHtml || '<p style="color:var(--text-3);font-size:13px">No email steps in this campaign.</p>') + '</div>';+ });+ el.innerHTML = html;}async function loadConversations() {- const r = await fetch('/api/conversations');- const data = await r.json();+ const el = document.getElementById('conversations-list');+ const data = await api('/api/conversations');+ if (!data) { el.innerHTML = offlineState(); return; }if (!data.length) {- document.getElementById('conversations-list').innerHTML = `<div class="empty"><div class="big">No conversations yet</div>Harvey hasn't received any replies yet.</div>`;+ el.innerHTML = emptyState('☉', 'No conversations yet',+ 'No prospects have replied so far. When they do, the Handler agent classifies each reply and responds — every thread shows up here.');return;}let html = '';@@ -1331,41 +1656,70 @@ async function loadConversations() {let threadHtml = '';for (const msg of (c.thread || [])) {const cls = msg.sender === 'harvey' ? 'sent' : 'received';- threadHtml += `<div class="thread-msg ${cls}"><div class="sender">${escHtml(msg.sender)} · ${formatDate(msg.timestamp)}</div>${escHtml(msg.content)}</div>`;+ threadHtml += '<div class="thread-msg ' + cls + '"><div class="sender">' + escHtml(msg.sender) ++ ' · ' + formatDate(msg.timestamp) + '</div>' + escHtml(msg.content) + '</div>';}const name = [c.first_name, c.last_name].filter(Boolean).join(' ') || 'Unknown';- html += `<div class="convo-card"><h3>${escHtml(name)} — ${escHtml(c.company||'')}</h3><div class="meta">${badge(c.status)}${c.intent?badge(c.intent):''}<span>${escHtml(c.prospect_email||'')}</span><span>${formatDate(c.updated_at)}</span></div>${threadHtml||'<div class="empty">No messages</div>'}</div>`;+ html += '<div class="convo-card"><h3>' + escHtml(name) ++ (c.company ? ' <span style="color:var(--text-3);font-weight:500">— ' + escHtml(c.company) + '</span>' : '') + '</h3>' ++ '<div class="meta">' + badge(c.status) + (c.intent ? badge(c.intent) : '') ++ '<span>' + escHtml(c.prospect_email || '') + '</span><span>' + formatDate(c.updated_at) + '</span></div>' ++ (threadHtml || '<p style="color:var(--text-3);font-size:13px">No messages in this thread yet.</p>') + '</div>';}- document.getElementById('conversations-list').innerHTML = html;+ el.innerHTML = html;}async function loadActivity() {- const r = await fetch('/api/activity');- const data = await r.json();+ const el = document.getElementById('activity-list');+ const data = await api('/api/activity');+ if (!data) { el.innerHTML = offlineState(); return; }if (!data.length) {- document.getElementById('activity-list').innerHTML = `<div class="empty"><div class="big">No activity yet</div>Harvey hasn't taken any actions yet.</div>`;+ el.innerHTML = emptyState('⏲', 'No activity yet',+ 'Harvey hasn\'t taken any actions. Every prospect found, email written, and reply handled will appear here the moment it happens.');return;}- let html = '';+ let html = '<div class="activity-feed">';for (const a of data) {- html += `<div class="activity-item"><span class="time">${formatDate(a.created_at)}</span><span class="agent">${escHtml(a.agent)}</span><span class="action">${escHtml(a.action_type)}</span></div>`;+ html += '<div class="activity-item"><span class="time">' + formatDate(a.created_at) + '</span>' ++ '<span class="agent">' + escHtml(a.agent) + '</span>' ++ '<span class="action">' + escHtml(a.action_type) + '</span></div>';}- document.getElementById('activity-list').innerHTML = html;+ el.innerHTML = html + '</div>';}-// ── Init ──+// ── Init & live refresh ──+loadSetupStatus();loadHarveyStatus();-setInterval(loadHarveyStatus, 10000);++// Agent status: quick poll+setInterval(loadHarveyStatus, 8000);++// Data tabs: auto-refresh live stats without clobbering form input+setInterval(() => {+ if (document.hidden) return;+ switch (currentTab) {+ case 'setup': loadSetupStatus(); break;+ case 'overview': loadStats(); break;+ case 'companies': if (!companyDrill) loadCompanies(); break;+ case 'prospects': loadProspects(); break;+ case 'campaigns': loadCampaigns(); break;+ case 'conversations': loadConversations(); break;+ case 'activity': loadActivity(); break;+ case 'controls': loadLogs(); break;+ // settings & help: never auto-refreshed (user may be typing)+ }+}, 15000);</script></body>-</html>"""+</html>+"""def start_dashboard(host: str = "127.0.0.1", port: int = 5555):"""Start the dashboard server."""import uvicorn- print(f"\\n Harvey Dashboard running at http://{host}:{port}")- print(f" Press Ctrl+C to stop.\\n")+ print(f"\n Harvey Dashboard running at http://{host}:{port}")+ print(" Press Ctrl+C to stop.\n")uvicorn.run(app, host=host, port=port, log_level="warning")diff --git a/harvey/integrations/__init__.py b/harvey/integrations/__init__.pyindex e69de29..d2e3f11 100644--- a/harvey/integrations/__init__.py+++ b/harvey/integrations/__init__.py@@ -0,0 +1,8 @@+"""External integrations: Instantly, LinkedIn, email discovery, calendar.++Submodules are intentionally NOT imported here so that optional heavy+dependencies (playwright, dnspython, aiosmtplib) are only loaded by the+agents that actually use them.+"""++__all__ = ["instantly", "linkedin", "email_finder", "calendar"]diff --git a/harvey/integrations/calendar.py b/harvey/integrations/calendar.pyindex 1bca0c3..ec9cdd1 100644--- a/harvey/integrations/calendar.py+++ b/harvey/integrations/calendar.py@@ -6,12 +6,21 @@ logger = logging.getLogger("harvey.calendar")class CalendarClient:- """Placeholder for calendar integration (Cal.com, Calendly, etc.)."""+ """Placeholder for calendar integration (Cal.com, Calendly, etc.).++ All methods degrade gracefully (empty results / False) so callers+ can invoke them unconditionally until a real backend is wired in.+ """async def get_available_slots(self, date_range: str) -> list[dict]:+ """Return available meeting slots for a date range (not yet implemented)."""logger.info("Calendar integration not yet implemented.")return []async def book_meeting(self, prospect_email: str, slot: dict) -> bool:+ """Book a meeting with a prospect (not yet implemented)."""+ if not prospect_email or not isinstance(slot, dict):+ logger.warning("book_meeting called with invalid arguments.")+ return Falselogger.info("Calendar integration not yet implemented.")return Falsediff --git a/harvey/integrations/email_finder.py b/harvey/integrations/email_finder.pyindex 86cd1f5..a29c085 100644--- a/harvey/integrations/email_finder.py+++ b/harvey/integrations/email_finder.py@@ -1,32 +1,57 @@-"""Email discovery — find email addresses without paid tools."""+"""Email discovery — find email addresses without paid tools.++Verification order:+1. Hunter.io (if HUNTER_API_KEY is set) — most reliable.+2. SMTP RCPT-TO probing — free fallback, degrades gracefully.+3. Pattern best-guess — when nothing can be verified.+"""import asyncioimport logging+import os+import randomimport refrom typing import Optionalimport dns.resolverimport aiosmtplib+import httpxlogger = logging.getLogger("harvey.email_finder")-# Cache MX records per domain to avoid repeated lookups-_mx_cache: dict[str, str] = {}+# Cache MX records per domain to avoid repeated lookups.+# Failed lookups are cached as None so we don't hammer DNS.+_mx_cache: dict[str, Optional[str]] = {}++HUNTER_TIMEOUT = httpx.Timeout(connect=10.0, read=20.0, write=10.0, pool=10.0)+HUNTER_MAX_RETRIES = 3+++def _clean_domain(domain: str) -> str:+ """Normalize a domain: strip scheme, www, path, whitespace."""+ domain = (domain or "").strip().lower()+ domain = re.sub(r"^https?://", "", domain)+ domain = domain.split("/")[0].split("?")[0]+ if domain.startswith("www."):+ domain = domain[4:]+ return domaindef 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 []+ first = (first_name or "").lower().strip()+ last = (last_name or "").lower().strip()+ domain = _clean_domain(domain)- # Remove non-alpha characters+ # Remove non-alpha characters BEFORE the empty check — otherwise names+ # with no ascii letters slip through and first[0] raises IndexError.first = re.sub(r"[^a-z]", "", first)last = re.sub(r"[^a-z]", "", last)- return [+ if not first or not last or not domain:+ return []++ patterns = [f"{first}@{domain}",f"{first}.{last}@{domain}",f"{first}{last}@{domain}",@@ -38,10 +63,15 @@ def generate_patterns(first_name: str, last_name: str, domain: str) -> list[str]f"{first}_{last}@{domain}",f"{first}-{last}@{domain}",]+ # Dedupe while preserving order (short names can collide).+ return list(dict.fromkeys(patterns))async def get_mx_host(domain: str) -> Optional[str]:"""Get the primary MX host for a domain."""+ domain = _clean_domain(domain)+ if not domain:+ return Noneif domain in _mx_cache:return _mx_cache[domain]@@ -50,12 +80,16 @@ async def get_mx_host(domain: str) -> Optional[str]: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+ records = sorted(answers, key=lambda x: x.preference)+ if not records:+ _mx_cache[domain] = None+ return None+ mx_host = str(records[0].exchange).rstrip(".")+ _mx_cache[domain] = mx_host or None+ return _mx_cache[domain]except Exception as e:logger.debug(f"MX lookup failed for {domain}: {e}")+ _mx_cache[domain] = Nonereturn None@@ -66,26 +100,29 @@ async def verify_email_smtp(email: str) -> bool:so a failed check doesn't guarantee the email is invalid.A successful check is a strong signal though."""- domain = email.split("@")[1]+ if "@" not in email:+ return False+ domain = email.rsplit("@", 1)[1]mx_host = await get_mx_host(domain)if not mx_host:return False+ smtp = aiosmtplib.SMTP(hostname=mx_host, port=25, timeout=10)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+ # Try VRFY first+ try:+ code, _ = await smtp.vrfy(email)+ if code == 250:+ return True+ except Exception:+ pass # VRFY often disabled- # VRFY often disabled, try MAIL FROM + RCPT TO+ # Fall back to MAIL FROM + RCPT TOawait smtp.mail("[email protected]")code, message = await smtp.rcpt(email)- await smtp.quit()# 250 = accepted, 550 = rejectedreturn code == 250@@ -93,6 +130,94 @@ async def verify_email_smtp(email: str) -> bool:except Exception as e:logger.debug(f"SMTP verification failed for {email}: {e}")return False+ finally:+ try:+ await smtp.quit()+ except Exception:+ pass+++def _hunter_api_key() -> str:+ """Hunter is optional; absence just means we degrade to SMTP checks."""+ return os.getenv("HUNTER_API_KEY", "").strip()+++async def verify_email_hunter(email: str, api_key: str | None = None) -> Optional[bool]:+ """Verify an email via Hunter.io.++ Returns True (deliverable), False (undeliverable), or None+ (unknown / Hunter unavailable / no API key) so callers can+ degrade gracefully to SMTP verification.+ """+ key = (api_key or _hunter_api_key())+ if not key:+ return None++ def _redact(text: str) -> str:+ return text.replace(key, "***REDACTED***") if text else ""++ async with httpx.AsyncClient(timeout=HUNTER_TIMEOUT) as client:+ for attempt in range(HUNTER_MAX_RETRIES + 1):+ try:+ resp = await client.get(+ "https://api.hunter.io/v2/email-verifier",+ params={"email": email, "api_key": key},+ )+ except httpx.HTTPError as e:+ if attempt < HUNTER_MAX_RETRIES:+ delay = min(2 ** attempt, 15) * random.uniform(0.5, 1.5)+ logger.debug(+ f"Hunter request error for {email}: {_redact(str(e))}. "+ f"Retrying in {delay:.1f}s."+ )+ await asyncio.sleep(delay)+ continue+ logger.warning(+ f"Hunter verification unavailable for {email}: "+ f"{_redact(str(e))}"+ )+ return None++ if resp.status_code in (429, 500, 502, 503, 504):+ if attempt < HUNTER_MAX_RETRIES:+ retry_after = resp.headers.get("Retry-After")+ try:+ delay = min(float(retry_after), 30) if retry_after else 0+ except ValueError:+ delay = 0+ delay = delay or min(2 ** attempt, 15) * random.uniform(0.5, 1.5)+ await asyncio.sleep(delay)+ continue+ logger.warning(f"Hunter API error {resp.status_code} for {email}.")+ return None++ if resp.status_code in (401, 403):+ logger.warning(+ "Hunter API key rejected; falling back to SMTP verification."+ )+ return None++ if resp.status_code >= 400:+ logger.debug(f"Hunter API error {resp.status_code} for {email}.")+ return None++ try:+ payload = resp.json()+ except ValueError:+ return None++ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return None++ status = data.get("status") or data.get("result")+ if status in ("valid", "deliverable"):+ return True+ if status in ("invalid", "undeliverable"):+ return False+ return None # risky / unknown / accept_all++ return Noneasync def find_email(@@ -105,36 +230,53 @@ async def find_email(1. Generate common email patterns2. Check MX records exist for domain- 3. Verify each pattern via SMTP+ 3. Verify each pattern (Hunter if configured, else 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.last@domain is the most common corporate pattern — use it as+ # the consistent best guess everywhere.+ clean = _clean_domain(domain)+ first = re.sub(r"[^a-z]", "", (first_name or "").lower())+ last = re.sub(r"[^a-z]", "", (last_name or "").lower())+ best_guess = f"{first}.{last}@{clean}"+# First check if domain has MX records at all- mx_host = await get_mx_host(domain)+ mx_host = await get_mx_host(clean)if not mx_host:- logger.info(f"No MX records for {domain}. Returning best guess.")- return patterns[0] # first.last@ is most common+ logger.info(f"No MX records for {clean}. Returning best guess.")+ return best_guessif not verify:- return patterns[0]+ return best_guess++ use_hunter = bool(_hunter_api_key())# Try to verify each patternfor email in patterns:logger.debug(f"Checking {email}...")try:- is_valid = await verify_email_smtp(email)+ is_valid: Optional[bool] = None+ if use_hunter:+ is_valid = await verify_email_hunter(email)+ if is_valid is None:+ # Hunter couldn't say — degrade to SMTP for this address+ is_valid = await verify_email_smtp(email)+ else:+ is_valid = await verify_email_smtp(email)+if is_valid:logger.info(f"Verified email: {email}")return email- except Exception:- continue+ except Exception as e:+ logger.debug(f"Verification error for {email}: {e}")- # Rate limit between checks- await asyncio.sleep(1)+ # Rate limit between checks (jittered so probes don't look scripted)+ await asyncio.sleep(random.uniform(0.8, 2.0))# 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+ logger.info(f"No verified email found. Best guess: {best_guess}")+ return best_guessdiff --git a/harvey/integrations/instantly.py b/harvey/integrations/instantly.pyindex 7421c59..11a1979 100644--- a/harvey/integrations/instantly.py+++ b/harvey/integrations/instantly.py@@ -1,6 +1,8 @@"""Instantly.ai API client for cold email campaigns."""+import asyncioimport logging+import randomfrom typing import Anyimport httpx@@ -9,50 +11,161 @@ logger = logging.getLogger("harvey.instantly")BASE_URL = "https://api.instantly.ai/api/v2"+# Retry policy+MAX_RETRIES = 4+BACKOFF_BASE = 1.0 # seconds+BACKOFF_CAP = 30.0+RETRYABLE_STATUS = {429, 500, 502, 503, 504}++# Explicit timeouts: connect / read / write / pool+TIMEOUT = httpx.Timeout(connect=10.0, read=30.0, write=30.0, pool=10.0)+class InstantlyClient:def __init__(self, api_key: str):- self.api_key = api_key+ self.api_key = api_key or ""self.headers = {- "Authorization": f"Bearer {api_key}",+ "Authorization": f"Bearer {self.api_key}","Content-Type": "application/json",}+ def _redact(self, text: str) -> str:+ """Strip the API key from anything we log or raise."""+ if self.api_key and text:+ return text.replace(self.api_key, "***REDACTED***")+ return text or ""++ @staticmethod+ def _retry_delay(attempt: int, response: httpx.Response | None) -> float:+ """Exponential backoff with jitter; honors Retry-After on 429."""+ if response is not None:+ retry_after = response.headers.get("Retry-After")+ if retry_after:+ try:+ return min(float(retry_after), BACKOFF_CAP) + random.uniform(0, 1)+ except ValueError:+ pass+ base = min(BACKOFF_BASE * (2 ** attempt), BACKOFF_CAP)+ return base * random.uniform(0.5, 1.5)+async def _request(- self, method: str, endpoint: str, data: dict | None = None+ self,+ method: str,+ endpoint: str,+ data: dict | None = None,+ params: dict | None = None,) -> dict | list | None:- """Make an authenticated request to the Instantly API."""+ """Make an authenticated request with retries, backoff, and validation."""+ if not self.api_key:+ logger.error("Instantly API key is not configured.")+ return None+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()++ async with httpx.AsyncClient(timeout=TIMEOUT) as client:+ for attempt in range(MAX_RETRIES + 1):+ try:+ response = await client.request(+ method, url, headers=self.headers, json=data, params=params+ )+ except httpx.HTTPError as e:+ # Network/timeout errors are retryable.+ if attempt < MAX_RETRIES:+ delay = self._retry_delay(attempt, None)+ logger.warning(+ f"Instantly request error ({method} {endpoint}): "+ f"{self._redact(str(e))}. "+ f"Retry {attempt + 1}/{MAX_RETRIES} in {delay:.1f}s."+ )+ await asyncio.sleep(delay)+ continue+ logger.error(+ f"Instantly request failed after {MAX_RETRIES} retries "+ f"({method} {endpoint}): {self._redact(str(e))}"+ )+ return None++ if response.status_code in RETRYABLE_STATUS:+ if attempt < MAX_RETRIES:+ delay = self._retry_delay(attempt, response)+ label = (+ "rate limited (429)"+ if response.status_code == 429+ else f"server error ({response.status_code})"+ )+ logger.warning(+ f"Instantly {label} on {method} {endpoint}. "+ f"Retry {attempt + 1}/{MAX_RETRIES} in {delay:.1f}s."+ )+ await asyncio.sleep(delay)+ continue+ logger.error(+ f"Instantly API error {response.status_code} on "+ f"{method} {endpoint} after {MAX_RETRIES} retries: "+ f"{self._redact(response.text[:500])}"+ )+ return None++ if response.status_code >= 400:+ # Non-retryable client error (400, 401, 403, 404, ...)+ logger.error(+ f"Instantly API error {response.status_code} on "+ f"{method} {endpoint}: {self._redact(response.text[:500])}"+ )+ return None++ if response.status_code == 204 or not response.content:+ return {}++ try:+ payload = response.json()+ except ValueError:+ logger.error(+ f"Instantly returned non-JSON response on {method} "+ f"{endpoint}: {self._redact(response.text[:200])}"+ )+ return None++ if not isinstance(payload, (dict, list)):+ logger.error(+ f"Instantly returned unexpected JSON type "+ f"({type(payload).__name__}) on {method} {endpoint}."+ )+ return None+ return payload++ return None++ @staticmethod+ def _extract_items(result: Any) -> list:+ """Normalize list responses: API may return a bare list or {items: [...]}. """+ if isinstance(result, list):+ return result+ if isinstance(result, dict):+ items = result.get("items") or result.get("data")+ if isinstance(items, list):+ return items+ return []# ── 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:+ if isinstance(result, dict):logger.info(f"Created campaign: {name} (id={result.get('id')})")- return result+ return result+ return Noneasync def get_campaign(self, campaign_id: str) -> dict | None:"""Get campaign details."""- return await self._request("GET", f"/campaigns/{campaign_id}")+ result = await self._request("GET", f"/campaigns/{campaign_id}")+ return result if isinstance(result, dict) else Noneasync 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 []+ result = await self._request("GET", "/campaigns", params={"limit": limit})+ return self._extract_items(result)async def update_campaign_schedule(self,@@ -60,21 +173,20 @@ class InstantlyClient:schedule: dict,) -> dict | None:"""Update campaign sending schedule."""- return await self._request(+ result = await self._request("PATCH", f"/campaigns/{campaign_id}", {"schedule": schedule})+ return result if isinstance(result, dict) else Noneasync def activate_campaign(self, campaign_id: str) -> dict | None:"""Start a campaign."""- return await self._request(- "POST", f"/campaigns/{campaign_id}/activate"- )+ result = await self._request("POST", f"/campaigns/{campaign_id}/activate")+ return result if isinstance(result, dict) else Noneasync def pause_campaign(self, campaign_id: str) -> dict | None:"""Pause a campaign."""- return await self._request(- "POST", f"/campaigns/{campaign_id}/pause"- )+ result = await self._request("POST", f"/campaigns/{campaign_id}/pause")+ return result if isinstance(result, dict) else None# ── Campaign Emails (Sequences) ──@@ -95,11 +207,12 @@ class InstantlyClient:...]"""- return await self._request(+ result = await self._request("POST",f"/campaigns/{campaign_id}/emails",{"sequences": [sequences]},)+ return result if isinstance(result, dict) else None# ── Leads ──@@ -121,15 +234,20 @@ class InstantlyClient:}]"""- return await self._request(+ if not leads:+ logger.warning("add_leads called with an empty lead list; skipping.")+ return {}+ result = await self._request("POST","/leads",{"campaign_id": campaign_id, "leads": leads},)+ return result if isinstance(result, dict) else Noneasync def get_lead(self, email: str) -> dict | None:"""Get lead details by email."""- return await self._request("GET", f"/leads?email={email}")+ result = await self._request("GET", "/leads", params={"email": email})+ return result if isinstance(result, dict) else None# ── Replies / Emails ──@@ -138,17 +256,15 @@ class InstantlyClient:) -> list:"""Get emails sent for a campaign."""result = await self._request(- "GET", f"/emails?campaign_id={campaign_id}&limit={limit}"+ "GET", "/emails", params={"campaign_id": campaign_id, "limit": limit})- return result if isinstance(result, list) else []+ return self._extract_items(result)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 []+ params = {"campaign_id": campaign_id} if campaign_id else None+ result = await self._request("GET", "/emails/replies", params=params)+ return self._extract_items(result)async def send_reply(self,@@ -156,27 +272,28 @@ class InstantlyClient:body: str,) -> dict | None:"""Send a reply to a lead's email."""- return await self._request(+ result = await self._request("POST","/emails/reply",{"reply_to_uuid": reply_to_uuid, "body": body},)+ return result if isinstance(result, dict) else None# ── 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"- )+ result = await self._request("GET", f"/campaigns/{campaign_id}/analytics")+ return result if isinstance(result, dict) else None# ── 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 []+ return self._extract_items(result)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")+ result = await self._request("GET", f"/accounts/{account_id}/warmup")+ return result if isinstance(result, dict) else Nonediff --git a/harvey/integrations/linkedin.py b/harvey/integrations/linkedin.pyindex dc1ce04..92c5a7d 100644--- a/harvey/integrations/linkedin.py+++ b/harvey/integrations/linkedin.py@@ -1,15 +1,36 @@-"""LinkedIn browser automation via Playwright."""+"""LinkedIn browser automation via Playwright.++Safety-first: humanlike randomized delays, hard daily activity caps+(persisted across restarts), and consistent browser fingerprint to+protect the user's LinkedIn account from restriction.+"""import asyncioimport jsonimport loggingimport random+from datetime import datefrom pathlib import Pathfrom typing import Optional+from urllib.parse import quote_pluslogger = logging.getLogger("harvey.linkedin")-COOKIES_PATH = Path(__file__).parent.parent.parent / "data" / "linkedin_cookies.json"+DATA_DIR = Path(__file__).parent.parent.parent / "data"+COOKIES_PATH = DATA_DIR / "linkedin_cookies.json"+ACTIVITY_PATH = DATA_DIR / "linkedin_activity.json"++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"+)++# Hard daily caps — conservative on purpose. LinkedIn restricts accounts+# that view too many profiles or run too many searches per day.+MAX_DAILY_SEARCH_PAGES = 20+MAX_DAILY_PROFILE_VIEWS = 40+MAX_SEARCH_PAGES_PER_QUERY = 5class LinkedInAutomation:@@ -19,56 +40,173 @@ class LinkedInAutomation:self.browser = Noneself.context = Noneself.page = None+ self._pw = None+ self._activity = self._load_activity()++ # ── Daily activity caps ──++ @staticmethod+ def _load_activity() -> dict:+ """Load today's activity counters (persisted so restarts don't reset caps)."""+ today = date.today().isoformat()+ try:+ if ACTIVITY_PATH.exists():+ data = json.loads(ACTIVITY_PATH.read_text())+ if isinstance(data, dict) and data.get("date") == today:+ return {+ "date": today,+ "search_pages": int(data.get("search_pages", 0)),+ "profile_views": int(data.get("profile_views", 0)),+ }+ except (ValueError, OSError) as e:+ logger.debug(f"Could not load LinkedIn activity log: {e}")+ return {"date": today, "search_pages": 0, "profile_views": 0}++ def _save_activity(self):+ try:+ ACTIVITY_PATH.parent.mkdir(parents=True, exist_ok=True)+ ACTIVITY_PATH.write_text(json.dumps(self._activity))+ except OSError as e:+ logger.debug(f"Could not save LinkedIn activity log: {e}")++ def _record(self, kind: str):+ # Roll over if the date changed mid-run+ today = date.today().isoformat()+ if self._activity.get("date") != today:+ self._activity = {"date": today, "search_pages": 0, "profile_views": 0}+ self._activity[kind] = self._activity.get(kind, 0) + 1+ self._save_activity()++ def _cap_reached(self, kind: str, cap: int) -> bool:+ today = date.today().isoformat()+ if self._activity.get("date") != today:+ self._activity = {"date": today, "search_pages": 0, "profile_views": 0}+ if self._activity.get(kind, 0) >= cap:+ logger.warning(+ f"LinkedIn daily cap reached for {kind} "+ f"({cap}/day). Skipping to protect the account."+ )+ return True+ return False++ # ── Humanlike behavior ──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))+ """Human-like random delay between actions, with occasional long pauses."""+ delay = random.uniform(min_s, max_s)+ # ~10% of the time, take a noticeably longer "reading" pause+ if random.random() < 0.10:+ delay += random.uniform(4.0, 10.0)+ await asyncio.sleep(delay)++ async def _humanlike_scroll(self):+ """Scroll the page in a few small increments like a human reading."""+ if not self.page:+ return+ try:+ for _ in range(random.randint(2, 4)):+ await self.page.mouse.wheel(0, random.randint(250, 700))+ await asyncio.sleep(random.uniform(0.4, 1.4))+ except Exception as e:+ logger.debug(f"Scroll simulation failed: {e}")++ async def _wait_settled(self, timeout: int = 15000):+ """Wait for network idle without crashing on busy pages."""+ try:+ await self.page.wait_for_load_state("networkidle", timeout=timeout)+ except Exception:+ # Feed-like pages never go fully idle; that's fine.+ pass++ # ── Lifecycle ──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)+ self._pw = await async_playwright().start()+ self.browser = await self._pw.chromium.launch(headless=True)++ # Always use the same fingerprint (viewport + UA), whether or not+ # we have saved cookies — a changing fingerprint is a red flag.+ self.context = await self.browser.new_context(+ viewport={"width": 1280, "height": 800},+ user_agent=USER_AGENT,+ )# 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"- ),- )+ try:+ cookies = json.loads(COOKIES_PATH.read_text())+ if isinstance(cookies, list):+ await self.context.add_cookies(cookies)+ logger.info("Loaded saved LinkedIn cookies.")+ except Exception as e:+ logger.warning(f"Could not load saved LinkedIn cookies: {e}")self.page = await self.context.new_page()- async def stop(self):- """Save cookies and close browser."""- if self.context:- cookies = await self.context.cookies()+ def _save_cookies_sync(self, cookies: list):+ try: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()+ try:+ COOKIES_PATH.chmod(0o600) # session cookies are credentials+ except OSError:+ pass+ except OSError as e:+ logger.warning(f"Could not save LinkedIn cookies: {e}")++ async def stop(self):+ """Save cookies and close browser."""+ try:+ if self.context:+ cookies = await self.context.cookies()+ self._save_cookies_sync(cookies)+ logger.info("Saved LinkedIn cookies.")+ except Exception as e:+ logger.debug(f"Could not save cookies on shutdown: {e}")+ try:+ if self.browser:+ await self.browser.close()+ except Exception as e:+ logger.debug(f"Error closing browser: {e}")+ finally:+ self.browser = None+ self.context = None+ self.page = None+ try:+ if self._pw:+ await self._pw.stop()+ except Exception as e:+ logger.debug(f"Error stopping Playwright: {e}")+ finally:+ self._pw = None++ # ── Auth ──async def login(self) -> bool:"""Log into LinkedIn."""if not self.page:await self.start()- await self.page.goto("https://www.linkedin.com/login")+ if not self.email or not self.password:+ logger.warning("LinkedIn credentials not configured; cannot log in.")+ return False++ try:+ await self.page.goto(+ "https://www.linkedin.com/login", timeout=30000+ )+ await self._wait_settled()+ except Exception as e:+ logger.error(f"Could not load LinkedIn login page: {e}")+ return False+await self._random_delay(1, 3)- # Check if already logged in- if "feed" in self.page.url:+ # Check if already logged in (cookie session redirected us)+ if "feed" in self.page.url or "mynetwork" in self.page.url:logger.info("Already logged into LinkedIn.")return True@@ -78,18 +216,17 @@ class LinkedInAutomation: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)+ await self._wait_settled()if "feed" in self.page.url or "mynetwork" in self.page.url:logger.info("Successfully logged into LinkedIn.")# Save cookies for future sessionscookies = await self.context.cookies()- COOKIES_PATH.parent.mkdir(parents=True, exist_ok=True)- COOKIES_PATH.write_text(json.dumps(cookies))+ self._save_cookies_sync(cookies)return True# Check for security challenge- if "checkpoint" in self.page.url:+ if "checkpoint" in self.page.url or "challenge" in self.page.url:logger.warning("LinkedIn security checkpoint detected. ""Please log in manually and save cookies."@@ -100,9 +237,13 @@ class LinkedInAutomation:return Falseexcept Exception as e:- logger.error(f"LinkedIn login failed: {e}")+ # Never include credentials in logged errors.+ msg = str(e).replace(self.password, "***") if self.password else str(e)+ logger.error(f"LinkedIn login failed: {msg}")return False+ # ── Search ──+async def search_people(self,keywords: str = "",@@ -120,36 +261,43 @@ class LinkedInAutomation: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}")+ # Fold all criteria into the keyword search (URL-encoded).+ terms = " ".join(t for t in [keywords, title, company, location] if t).strip()+ if not terms:+ logger.warning("search_people called with no criteria; skipping.")+ return []search_url = (- f"https://www.linkedin.com/search/results/people/"- f"?{'&'.join(search_parts)}"+ "https://www.linkedin.com/search/results/people/"+ f"?keywords={quote_plus(terms)}")results = []page_num = 1while len(results) < max_results:+ if self._cap_reached("search_pages", MAX_DAILY_SEARCH_PAGES):+ break+url = f"{search_url}&page={page_num}"- await self.page.goto(url)+ try:+ await self.page.goto(url, timeout=30000)+ except Exception as e:+ logger.warning(f"Failed to load search page {page_num}: {e}")+ break++ self._record("search_pages")await self._random_delay(3, 6)- await self.page.wait_for_load_state("networkidle", timeout=15000)+ await self._wait_settled()+ await self._humanlike_scroll()# Extract search result cards- cards = await self.page.query_selector_all(- "div.entity-result__item"- )+ cards = await self.page.query_selector_all("div.entity-result__item")if not cards:# Try alternate selectorcards = await self.page.query_selector_all(- 'li.reusable-search__result-container'+ "li.reusable-search__result-container")if not cards:@@ -171,8 +319,8 @@ class LinkedInAutomation:page_num += 1await self._random_delay(4, 8)- # Safety: don't go beyond 5 pages- if page_num > 5:+ # Safety: don't paginate deep on a single query+ if page_num > MAX_SEARCH_PAGES_PER_QUERY:breaklogger.info(f"Found {len(results)} LinkedIn profiles.")@@ -212,8 +360,9 @@ class LinkedInAutomation:# 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()+ title_text, company = (+ s.strip() for s in title_text.split(" at ", 1)+ )return {"first_name": first_name,@@ -224,6 +373,8 @@ class LinkedInAutomation:"location": location,}+ # ── Profiles ──+async def extract_profile(self, linkedin_url: str) -> Optional[dict]:"""Scrape a LinkedIn profile page for detailed info."""if not self.page:@@ -231,9 +382,19 @@ class LinkedInAutomation:if not await self.login():return None- await self.page.goto(linkedin_url)+ if self._cap_reached("profile_views", MAX_DAILY_PROFILE_VIEWS):+ return None++ try:+ await self.page.goto(linkedin_url, timeout=30000)+ except Exception as e:+ logger.warning(f"Failed to load profile {linkedin_url}: {e}")+ return None++ self._record("profile_views")await self._random_delay(3, 5)- await self.page.wait_for_load_state("networkidle", timeout=15000)+ await self._wait_settled()+ await self._humanlike_scroll()try:# Name@@ -241,15 +402,11 @@ class LinkedInAutomation:name = await name_el.inner_text() if name_el else ""# Headline- headline_el = await self.page.query_selector(- "div.text-body-medium"- )+ 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"- )+ loc_el = await self.page.query_selector("span.text-body-small.inline")location = await loc_el.inner_text() if loc_el else ""# About sectiondiff --git a/harvey/main.py b/harvey/main.pyindex 3b2af3d..dbdef17 100644--- a/harvey/main.py+++ b/harvey/main.py@@ -9,7 +9,7 @@ from datetime import datetime, time, timedeltaimport pytzfrom harvey.brain import Brain-from harvey.config import load_config, load_env, HarveyConfig+from harvey.config import ConfigError, load_config, load_env, HarveyConfigfrom harvey.state import StateManagerlogging.basicConfig(@@ -19,6 +19,10 @@ logging.basicConfig()logger = logging.getLogger("harvey")+# Backoff for consecutive failed cycles: 60s, 120s, 240s, ... capped at 15 min+ERROR_BACKOFF_BASE = 60+ERROR_BACKOFF_CAP = 900+def in_quiet_hours(config: HarveyConfig) -> bool:"""Check if we're currently in quiet hours."""@@ -41,7 +45,7 @@ def seconds_until_quiet_hours_end(config: HarveyConfig) -> int: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)+ end_today = now.replace(hour=end.hour, minute=end.minute, second=0, microsecond=0)if end_today <= now:# End time is tomorrow@@ -51,52 +55,70 @@ def seconds_until_quiet_hours_end(config: HarveyConfig) -> int: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+async def decide_next_action(+ brain: Brain,+ state: StateManager,+ config: HarveyConfig,+ summary: dict | None = None,+) -> str:+ """Decide what Harvey should do next based on current state.++ Uses deterministic priority rules (handle_replies > send_campaign >+ write_campaign > prospect > idle) instead of burning a Claude call on a+ decision that is fully derivable from pipeline counts. This saves budget+ every cycle and removes a fragile LLM string-parsing step.+ """+ if summary is None:+ summary = await state.get_state_summary()++ prospects = summary.get("prospects") or {}+ new_prospects = prospects.get("new", 0) if isinstance(prospects, dict) else 0+ draft_campaigns = summary.get("draft_campaigns", 0) or 0+ open_conversations = summary.get("open_conversations", 0) or 0++ if open_conversations > 0:+ action, reason = "handle_replies", f"{open_conversations} open conversation(s) waiting"+ elif draft_campaigns > 0:+ action, reason = "send_campaign", f"{draft_campaigns} draft campaign(s) ready to deploy"+ elif new_prospects > 0:+ action, reason = "write_campaign", f"{new_prospects} new prospect(s) with no drafts ready"+ elif new_prospects < 20:+ action, reason = "prospect", f"only {new_prospects} new prospect(s); pipeline needs leads"+ else:+ action, reason = "idle", "pipeline is healthy; running analysis"-Respond with ONLY the action name, nothing else."""+ logger.info(f"Decision: {action} ({reason})")+ return action- 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"+async def _interruptible_sleep(seconds: float, stop_event: asyncio.Event) -> bool:+ """Sleep up to `seconds`, waking immediately on shutdown.- return action+ Returns True if a shutdown was requested during the sleep.+ """+ try:+ await asyncio.wait_for(stop_event.wait(), timeout=seconds)+ return True+ except asyncio.TimeoutError:+ return False-async def heartbeat():+async def heartbeat(stop_event: asyncio.Event | None = None):"""Harvey's main loop. Wakes up, decides, acts, sleeps. Repeat."""+ if stop_event is None:+ stop_event = asyncio.Event()+logger.info("=" * 60)logger.info("Harvey is online. Always Be Closing.")logger.info("=" * 60)- config = load_config()+ try:+ config = load_config()+ except (ConfigError, Exception) as e:+ if isinstance(e, (KeyboardInterrupt, asyncio.CancelledError)):+ raise+ logger.error(f"Cannot start — configuration error:\n{e}")+ returnenv = load_env()state = StateManager()brain = Brain(state)@@ -118,29 +140,33 @@ async def heartbeat():analyst = Analyst(state)interval = config.usage.heartbeat_interval_minutes * 60- max_calls = int(200 * (config.usage.max_daily_claude_percent / 100))+ max_calls = max(int(200 * (config.usage.max_daily_claude_percent / 100)), 1)+ consecutive_errors = 0- while True:+ while not stop_event.is_set():try:# 1. Check quiet hoursif 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)+ if await _interruptible_sleep(sleep_for, stop_event):+ breakcontinue# 2. Check usage budgetif 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)+ logger.info(+ f"Daily usage limit reached ({max_calls} calls). "+ "Sleeping 1h, then re-checking (resets at midnight)."+ )+ if await _interruptible_sleep(3600, stop_event):+ breakcontinue# 3. Decide what to do- logger.info("Thinking about what to do next...")+ logger.info("Checking pipeline state...")summary = await state.get_state_summary()- action = await decide_next_action(brain, state, config)- logger.info(f"Primary action: {action}")+ action = await decide_next_action(brain, state, config, summary=summary)# 4. Execute — run independent agents in parallel where possible# Handler is always safe to run alongside other agents@@ -154,6 +180,8 @@ async def heartbeat():# Also handle replies in parallel if neededif has_open_convos:tasks.append(("handle_replies", handler.run()))+ # Analyst is cheap (no Claude calls) — keep analytics fresh+ tasks.append(("analyze", analyst.run()))elif action == "write_campaign":tasks.append(("write_campaign", writer.run()))if has_open_convos:@@ -166,30 +194,49 @@ async def heartbeat():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+ # Run all tasks, catch errors per-task so one bad agent+ # never takes down the cycleresults = await asyncio.gather(*[t[1] for t in tasks], return_exceptions=True)for (name, _), result in zip(tasks, results):+ if isinstance(result, asyncio.CancelledError):+ raise resultif isinstance(result, Exception):- logger.error(f"Agent {name} failed: {result}")+ logger.error(f"Agent {name} failed: {result}", exc_info=result)- # 5. Log the action- await state.log_action(action_type=action, agent="main")+ # 5. Log the action (best-effort; never kills the loop)+ try:+ await state.log_action(action_type=action, agent="main")+ except Exception as e:+ logger.warning(f"Failed to log action '{action}': {e}")++ consecutive_errors = 0# 6. Sleep until next heartbeatlogger.info(f"Cycle complete. Sleeping for {config.usage.heartbeat_interval_minutes} minutes.")- await asyncio.sleep(interval)+ if await _interruptible_sleep(interval, stop_event):+ break- except KeyboardInterrupt:- logger.info("Harvey shutting down. Deals don't close themselves, but I need a break.")+ except (KeyboardInterrupt, asyncio.CancelledError):breakexcept Exception as e:- logger.error(f"Error in heartbeat: {e}", exc_info=True)- logger.info("Recovering... sleeping 60s before retry.")- await asyncio.sleep(60)+ consecutive_errors += 1+ backoff = min(+ ERROR_BACKOFF_BASE * (2 ** (consecutive_errors - 1)),+ ERROR_BACKOFF_CAP,+ )+ logger.error(+ f"Error in heartbeat (failure #{consecutive_errors}): {e}",+ exc_info=True,+ )+ logger.info(f"Recovering... sleeping {backoff}s before retry.")+ if await _interruptible_sleep(backoff, stop_event):+ break++ logger.info("Harvey shutting down. Deals don't close themselves, but I need a break.")def _needs_setup() -> bool:@@ -209,7 +256,9 @@ def _needs_setup() -> bool:with open(config_file) as f:import yamlconfig = yaml.safe_load(f)- company = config.get("persona", {}).get("company", "")+ if not isinstance(config, dict):+ return True+ company = (config.get("persona") or {}).get("company", "")if company in ("Your Company", ""):return Trueexcept Exception:@@ -220,6 +269,28 @@ def _needs_setup() -> bool:return False+async def _run_with_signals():+ """Run the heartbeat with SIGINT/SIGTERM wired to a graceful shutdown."""+ stop_event = asyncio.Event()+ loop = asyncio.get_running_loop()++ def _request_shutdown(sig_name: str):+ if stop_event.is_set():+ logger.info("Second shutdown signal — exiting immediately.")+ sys.exit(1)+ logger.info(f"Received {sig_name}. Finishing current work, then shutting down...")+ stop_event.set()++ for sig in (signal.SIGINT, signal.SIGTERM):+ try:+ loop.add_signal_handler(sig, _request_shutdown, sig.name)+ except (NotImplementedError, RuntimeError):+ # Windows / non-main-thread fallback+ signal.signal(sig, lambda s, f: _request_shutdown(signal.Signals(s).name))++ await heartbeat(stop_event)++def main():"""Entry point."""# Check for first-time setup@@ -229,23 +300,10 @@ def main():asyncio.run(run_setup())return- # 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())+ asyncio.run(_run_with_signals())except KeyboardInterrupt:logger.info("Goodbye.")- finally:- loop.close()if __name__ == "__main__":diff --git a/harvey/models/__init__.py b/harvey/models/__init__.pyindex e69de29..ebdeafd 100644--- a/harvey/models/__init__.py+++ b/harvey/models/__init__.py@@ -0,0 +1,16 @@+"""Harvey data models."""++from harvey.models.campaign import Campaign, EmailStep+from harvey.models.company import Company+from harvey.models.conversation import Conversation, Message, STAGES+from harvey.models.prospect import Prospect++__all__ = [+ "Campaign",+ "Company",+ "Conversation",+ "EmailStep",+ "Message",+ "Prospect",+ "STAGES",+]diff --git a/harvey/models/campaign.py b/harvey/models/campaign.pyindex 422d25e..70a22f0 100644--- a/harvey/models/campaign.py+++ b/harvey/models/campaign.py@@ -1,11 +1,16 @@"""Campaign data model."""import json-from datetime import datetime+from datetime import datetime, timezonefrom pydantic import BaseModel, Field+def _utcnow() -> datetime:+ """Naive UTC now (consistent with DB storage; avoids deprecated utcnow)."""+ return datetime.now(timezone.utc).replace(tzinfo=None)++class EmailStep(BaseModel):step: intsubject: str@@ -18,14 +23,20 @@ class Campaign(BaseModel):name: str = ""channel: str = "email" # email/linkedininstantly_campaign_id: str = ""- sequence: list[EmailStep] = []+ sequence: list[EmailStep] = Field(default_factory=list)status: str = "draft" # draft/active/paused/completed- prospect_ids: list[str] = []- created_at: datetime = Field(default_factory=datetime.utcnow)+ prospect_ids: list[str] = Field(default_factory=list)+ created_at: datetime = Field(default_factory=_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)]+ def sequence_from_json(cls, data: str | None) -> list[EmailStep]:+ """Parse a stored sequence; tolerates NULL/empty/corrupt JSON."""+ if not data:+ return []+ try:+ return [EmailStep(**s) for s in json.loads(data)]+ except (json.JSONDecodeError, TypeError):+ return []diff --git a/harvey/models/company.py b/harvey/models/company.pyindex 1a1f988..86e2f27 100644--- a/harvey/models/company.py+++ b/harvey/models/company.py@@ -1,8 +1,13 @@"""Company data model."""-from datetime import datetime+from datetime import datetime, timezone-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator+++def _utcnow() -> datetime:+ """Naive UTC now (consistent with DB storage; avoids deprecated utcnow)."""+ return datetime.now(timezone.utc).replace(tzinfo=None)class Company(BaseModel):@@ -17,5 +22,11 @@ class Company(BaseModel):source: str = "" # how we found them: google_dork, linkedin, company_scrapesource_url: str = "" # specific URL where we found the infonotes: str = ""- created_at: datetime = Field(default_factory=datetime.utcnow)- updated_at: datetime = Field(default_factory=datetime.utcnow)+ created_at: datetime = Field(default_factory=_utcnow)+ updated_at: datetime = Field(default_factory=_utcnow)++ @field_validator("domain")+ @classmethod+ def _normalize_domain(cls, v: str) -> str:+ """Domains are dedup keys — normalize case/whitespace."""+ return (v or "").strip().lower()diff --git a/harvey/models/conversation.py b/harvey/models/conversation.pyindex 575f6a4..7c3e653 100644--- a/harvey/models/conversation.py+++ b/harvey/models/conversation.py@@ -1,15 +1,20 @@"""Conversation data model."""import json-from datetime import datetime+from datetime import datetime, timezonefrom pydantic import BaseModel, Field+def _utcnow() -> datetime:+ """Naive UTC now (consistent with DB storage; avoids deprecated utcnow)."""+ return datetime.now(timezone.utc).replace(tzinfo=None)++class Message(BaseModel):sender: str # "harvey" or "prospect"content: str- timestamp: datetime = Field(default_factory=datetime.utcnow)+ timestamp: datetime = Field(default_factory=_utcnow)# Sales stages: tracks where the deal is in the pipeline@@ -30,16 +35,22 @@ class Conversation(BaseModel):prospect_id: strcampaign_id: str = ""channel: str = "email"- thread: list[Message] = []+ thread: list[Message] = Field(default_factory=list)intent: str = "" # interested/objection/not_interested/ooo/wrong_personstage: str = "initial_outreach" # sales pipeline stagestatus: str = "open" # open/replied/meeting_booked/closed- created_at: datetime = Field(default_factory=datetime.utcnow)- updated_at: datetime = Field(default_factory=datetime.utcnow)+ created_at: datetime = Field(default_factory=_utcnow)+ updated_at: datetime = Field(default_factory=_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)]+ def thread_from_json(cls, data: str | None) -> list[Message]:+ """Parse a stored thread; tolerates NULL/empty/corrupt JSON."""+ if not data:+ return []+ try:+ return [Message(**m) for m in json.loads(data)]+ except (json.JSONDecodeError, TypeError):+ return []diff --git a/harvey/models/prospect.py b/harvey/models/prospect.pyindex 9f6f0f4..4bf9e23 100644--- a/harvey/models/prospect.py+++ b/harvey/models/prospect.py@@ -1,8 +1,13 @@"""Contact data model — a person at a company."""-from datetime import datetime+from datetime import datetime, timezone-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator+++def _utcnow() -> datetime:+ """Naive UTC now (consistent with DB storage; avoids deprecated utcnow)."""+ return datetime.now(timezone.utc).replace(tzinfo=None)class Prospect(BaseModel):@@ -27,8 +32,19 @@ class Prospect(BaseModel):company: str = ""industry: str = ""company_size: str = ""- created_at: datetime = Field(default_factory=datetime.utcnow)- updated_at: datetime = Field(default_factory=datetime.utcnow)+ created_at: datetime = Field(default_factory=_utcnow)+ updated_at: datetime = Field(default_factory=_utcnow)++ @field_validator("email")+ @classmethod+ def _normalize_email(cls, v: str) -> str:+ """Emails are dedup keys — normalize so '[email protected]' == '[email protected]'."""+ return (v or "").strip().lower()++ @field_validator("linkedin_url")+ @classmethod+ def _strip_linkedin(cls, v: str) -> str:+ return (v or "").strip()def full_name(self) -> str:return f"{self.first_name} {self.last_name}".strip()diff --git a/harvey/setup.py b/harvey/setup.pyindex faabb66..61869db 100644--- a/harvey/setup.py+++ b/harvey/setup.py@@ -1,14 +1,12 @@"""Interactive setup wizard — Claude walks you through everything Harvey needs."""import asyncio+import getpassimport logging-import os-import reimport shutilfrom pathlib import Pathimport yaml-from dotenv import load_dotenvfrom harvey.brain import Brainfrom harvey.state import StateManager@@ -34,11 +32,12 @@ def _print_step(step: int, total: int, title: str):def _ask(prompt: str, default: str = "", required: bool = True, secret: bool = False) -> str:- """Ask the user a question."""+ """Ask the user a question. secret=True hides input (passwords, API keys)."""suffix = f" [{default}]" if default else ""+ reader = getpass.getpass if secret else inputwhile True:try:- answer = input(f"\n → {prompt}{suffix}: ").strip()+ answer = reader(f"\n → {prompt}{suffix}: ").strip()except (EOFError, KeyboardInterrupt):print("\n\n Setup cancelled.")raise SystemExit(1)@@ -200,7 +199,7 @@ class SetupWizard:has_instantly = _ask_yes_no("Do you have an Instantly account?")if has_instantly:- api_key = _ask("Instantly API key (from Settings → Integrations)")+ api_key = _ask("Instantly API key (from Settings → Integrations; input hidden)", secret=True)self.env_vars["INSTANTLY_API_KEY"] = api_key# Test the key@@ -222,19 +221,23 @@ class SetupWizard:def _setup_linkedin(self):"""Configure LinkedIn credentials."""_print_harvey("I can search LinkedIn to find prospects matching your ICP.")- _print_harvey("I'll log into your LinkedIn account using a browser and")- _print_harvey("search like a human would — with random delays and everything.")+ _print_harvey("I'll log into your LinkedIn account using a browser, with")+ _print_harvey("conservative rate limits and human-like pacing.")+ print("\n ⚠ Heads up: automating LinkedIn violates their Terms of Service.")+ print(" Accounts doing this can be restricted or banned. Only use an")+ print(" account you're comfortable putting at risk, and keep the")+ print(" default rate limits. This is entirely optional.")- use_linkedin = _ask_yes_no("Set up LinkedIn prospecting?")+ use_linkedin = _ask_yes_no("Set up LinkedIn prospecting anyway?", default=False)if use_linkedin:email = _ask("LinkedIn email/username")- password = _ask("LinkedIn password")+ password = _ask("LinkedIn password (input hidden)", secret=True)self.env_vars["LINKEDIN_EMAIL"] = emailself.env_vars["LINKEDIN_PASSWORD"] = password- _print_harvey("Got it. I'll be careful with your account — human-like")- _print_harvey("behavior, rate limits, the works. No one will know.")+ _print_harvey("Got it. I'll stay well under the rate limits and behave")+ _print_harvey("like a careful human, but the ToS risk is yours to own.")else:_print_harvey("That's fine. I can still find prospects via Google")_print_harvey("and company websites. You can add LinkedIn later.")@@ -252,7 +255,7 @@ class SetupWizard:if use_cloudflare:account_id = _ask("Cloudflare Account ID")- api_token = _ask("Cloudflare API Token (needs Browser Rendering - Edit permission)")+ api_token = _ask("Cloudflare API Token (needs Browser Rendering - Edit permission; input hidden)", secret=True)self.env_vars["CLOUDFLARE_ACCOUNT_ID"] = account_idself.env_vars["CLOUDFLARE_API_TOKEN"] = api_token_print_harvey("Nice. I'll use Cloudflare for deep crawling during training.")@@ -432,8 +435,9 @@ class SetupWizard:default="80",)try:- usage_pct = float(usage_pct)+ usage_pct = min(100.0, max(1.0, float(usage_pct)))except ValueError:+ print(" (didn't catch that — using 80)")usage_pct = 80.0# Heartbeat interval@@ -443,8 +447,9 @@ class SetupWizard:default="15",)try:- interval = int(interval)+ interval = max(1, int(interval))except ValueError:+ print(" (didn't catch that — using 15)")interval = 15# Quiet hours@@ -459,9 +464,13 @@ class SetupWizard:default="50",)try:- daily_sends = int(daily_sends)+ daily_sends = max(1, int(daily_sends))except ValueError:+ print(" (didn't catch that — using 50)")daily_sends = 50+ if daily_sends > 200:+ print("\n ⚠ 200+ sends/day from a fresh domain will torch your")+ print(" deliverability. Warm up gradually (see README).")# Update configif self.config:@@ -480,12 +489,28 @@ class SetupWizard:_print_harvey("Perfect. All configured.")def _write_env(self):- """Write the .env file."""- lines = []+ """Write the .env file, preserving any existing variables we didn't touch."""+ existing: dict[str, str] = {}+ if ENV_FILE.exists():+ for line in ENV_FILE.read_text().splitlines():+ line = line.strip()+ if line and not line.startswith("#") and "=" in line:+ key, _, value = line.partition("=")+ existing[key.strip()] = value.strip()++ # Wizard answers win, but never blank out a previously-set value+ # (e.g. re-running setup and skipping the LinkedIn step).+ merged = dict(existing)for key, value in self.env_vars.items():- lines.append(f"{key}={value}")+ if value or key not in merged:+ merged[key] = value+ lines = [f"{key}={value}" for key, value in merged.items()]ENV_FILE.write_text("\n".join(lines) + "\n")+ try:+ ENV_FILE.chmod(0o600) # credentials — owner read/write only+ except OSError:+ passlogger.info(f"Wrote {ENV_FILE}")def _write_config(self):@@ -541,15 +566,23 @@ class SetupWizard:- harvey.yaml (your configuration)To start Harvey:- python -m harvey+ harvey run (or: python -m harvey)To re-train on a different product:- python -m harvey.trainer https://newproduct.com+ harvey train https://newproduct.comTo re-run this setup:- python -m harvey.setup+ harvey setup++ Before you send a single email:+ 1. Use a dedicated sending domain (not your main domain) with+ SPF, DKIM, and DMARC configured.+ 2. Warm it up 2-4 weeks before real volume (Instantly has warmup).+ 3. Make sure your Instantly campaigns include an unsubscribe+ option and your physical mailing address (CAN-SPAM).+ See the "Legal & Deliverability" section of the README.""")- _print_harvey("I'm ready. Run 'python -m harvey' and I'll start closing.")+ _print_harvey("I'm ready. Run 'harvey run' and I'll start closing.")_print_harvey("Always be closing.\n")diff --git a/harvey/state.py b/harvey/state.pyindex 9e35b09..befc2e0 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -1,144 +1,249 @@-"""SQLite state manager. All of Harvey's memory lives here."""+"""SQLite state manager. All of Harvey's memory lives here.++Concurrency: the DB runs in WAL mode (set persistently at init) so the+dashboard can read while the agent writes. Every connection gets a busy+timeout so concurrent writers wait instead of raising "database is locked".++Migrations: schema changes are applied via a linear, idempotent migration+list tracked with SQLite's ``PRAGMA user_version`` so existing user DBs+upgrade cleanly in place.+"""import jsonimport uuid-from datetime import datetime, date+from contextlib import asynccontextmanager+from datetime import datetime, date, timezonefrom pathlib import Pathimport aiosqlitefrom harvey.models.company import Companyfrom harvey.models.prospect import Prospect-from harvey.models.campaign import Campaign, EmailStep-from harvey.models.conversation import Conversation, Message+from harvey.models.campaign import Campaign, EmailStep # noqa: F401 (EmailStep re-exported)+from harvey.models.conversation import Conversation, Message # noqa: F401DB_PATH = Path(__file__).parent.parent / "data" / "harvey.db"+# How long (seconds) a connection waits on a locked database before failing.+BUSY_TIMEOUT_SECONDS = 30.0+def _new_id() -> str:return uuid.uuid4().hex[:12]+def _utcnow() -> datetime:+ """Naive UTC now (matches how timestamps are stored in the DB)."""+ return datetime.now(timezone.utc).replace(tzinfo=None)+++def _norm(value: str | None) -> str:+ """Normalize an identity key (email/domain) for dedup: strip + lowercase."""+ return (value or "").strip().lower()+++# ── Schema migrations ─────────────────────────────────────────────────+# Each entry is an idempotent SQL script. The index into this list + 1 is+# the schema version stored in PRAGMA user_version. Never edit or reorder+# released migrations — append new ones.++MIGRATIONS: list[str] = [+ # ── v1: base schema (idempotent, so pre-migration DBs adopt cleanly) ──+ """+ CREATE TABLE IF NOT EXISTS companies (+ id TEXT PRIMARY KEY,+ name TEXT DEFAULT '',+ domain TEXT DEFAULT '',+ website TEXT DEFAULT '',+ description TEXT DEFAULT '',+ industry TEXT DEFAULT '',+ company_size TEXT DEFAULT '',+ location TEXT DEFAULT '',+ source TEXT DEFAULT '',+ source_url TEXT DEFAULT '',+ notes TEXT DEFAULT '',+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );++ CREATE TABLE IF NOT EXISTS prospects (+ id TEXT PRIMARY KEY,+ company_id TEXT DEFAULT '' REFERENCES companies(id),+ first_name TEXT DEFAULT '',+ last_name TEXT DEFAULT '',+ email TEXT DEFAULT '',+ email_verified INTEGER DEFAULT 0,+ phone TEXT DEFAULT '',+ phone_verified INTEGER DEFAULT 0,+ linkedin_url TEXT DEFAULT '',+ title TEXT DEFAULT '',+ seniority TEXT DEFAULT '',+ department TEXT DEFAULT '',+ source TEXT DEFAULT '',+ source_url TEXT DEFAULT '',+ status TEXT DEFAULT 'new',+ score INTEGER DEFAULT 0,+ personalization_notes TEXT DEFAULT '',+ company TEXT DEFAULT '',+ industry TEXT DEFAULT '',+ company_size 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 '',+ stage TEXT DEFAULT 'initial_outreach',+ status TEXT DEFAULT 'open',+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );++ CREATE TABLE IF NOT EXISTS feedback (+ id TEXT PRIMARY KEY,+ entity_type TEXT DEFAULT '',+ entity_id TEXT DEFAULT '',+ comment TEXT DEFAULT '',+ created_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 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);+ CREATE INDEX IF NOT EXISTS idx_usage_date ON usage_log(date);+ """,+ # ── v2: normalize identity keys, dedup, uniqueness, hot-path indexes ──+ """+ -- Normalize emails/domains so uniqueness is case-insensitive going forward.+ UPDATE prospects SET email = LOWER(TRIM(email)) WHERE email != LOWER(TRIM(email));+ UPDATE companies SET domain = LOWER(TRIM(domain)) WHERE domain != LOWER(TRIM(domain));++ -- Dedup existing rows (keep the earliest) so unique indexes can be built.+ DELETE FROM prospects WHERE email != '' AND rowid NOT IN (+ SELECT MIN(rowid) FROM prospects WHERE email != '' GROUP BY email+ );+ DELETE FROM prospects WHERE linkedin_url != '' AND rowid NOT IN (+ SELECT MIN(rowid) FROM prospects WHERE linkedin_url != '' GROUP BY linkedin_url+ );+ DELETE FROM companies WHERE domain != '' AND rowid NOT IN (+ SELECT MIN(rowid) FROM companies WHERE domain != '' GROUP BY domain+ );++ -- Enforce uniqueness at the DB level (partial: blank values allowed).+ CREATE UNIQUE INDEX IF NOT EXISTS uq_prospects_email+ ON prospects(email) WHERE email != '';+ CREATE UNIQUE INDEX IF NOT EXISTS uq_prospects_linkedin+ ON prospects(linkedin_url) WHERE linkedin_url != '';+ CREATE UNIQUE INDEX IF NOT EXISTS uq_companies_domain+ ON companies(domain) WHERE domain != '';++ -- Hot-path indexes: campaign stats subqueries, reply handling, dedup checks.+ CREATE INDEX IF NOT EXISTS idx_conversations_campaign_id ON conversations(campaign_id);+ CREATE INDEX IF NOT EXISTS idx_conversations_prospect_id ON conversations(prospect_id);+ CREATE INDEX IF NOT EXISTS idx_conversations_intent ON conversations(intent);+ CREATE INDEX IF NOT EXISTS idx_prospects_name_company+ ON prospects(LOWER(first_name), LOWER(last_name), LOWER(company));+ CREATE INDEX IF NOT EXISTS idx_prospects_status_updated ON prospects(status, updated_at);+ CREATE INDEX IF NOT EXISTS idx_actions_created_at ON actions(created_at);+ """,+]++# Column whitelists for dynamic UPDATEs (prevents SQL injection via kwargs).+_CAMPAIGN_COLUMNS = frozenset({+ "name", "channel", "instantly_campaign_id",+ "sequence_json", "prospect_ids_json", "status",+})+_CONVERSATION_COLUMNS = frozenset({+ "prospect_id", "campaign_id", "channel",+ "thread_json", "intent", "stage", "status",+})++class StateManager:def __init__(self, db_path: str | None = None):self.db_path = db_path or str(DB_PATH)+ @asynccontextmanager+ async def _connect(self):+ """Open a connection with sane concurrency settings.++ `timeout` maps to SQLite's busy handler, so writers wait for locks+ (e.g. while the dashboard holds a read) instead of erroring.+ """+ db = await aiosqlite.connect(self.db_path, timeout=BUSY_TIMEOUT_SECONDS)+ try:+ yield db+ finally:+ await db.close()+async def init_db(self):- """Create all tables if they don't exist."""+ """Create/upgrade the schema. Safe to call on every startup."""Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)- async with aiosqlite.connect(self.db_path) as db:- await db.executescript("""- CREATE TABLE IF NOT EXISTS companies (- id TEXT PRIMARY KEY,- name TEXT DEFAULT '',- domain TEXT DEFAULT '',- website TEXT DEFAULT '',- description TEXT DEFAULT '',- industry TEXT DEFAULT '',- company_size TEXT DEFAULT '',- location TEXT DEFAULT '',- source TEXT DEFAULT '',- source_url TEXT DEFAULT '',- notes TEXT DEFAULT '',- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP- );-- CREATE TABLE IF NOT EXISTS prospects (- id TEXT PRIMARY KEY,- company_id TEXT DEFAULT '' REFERENCES companies(id),- first_name TEXT DEFAULT '',- last_name TEXT DEFAULT '',- email TEXT DEFAULT '',- email_verified INTEGER DEFAULT 0,- phone TEXT DEFAULT '',- phone_verified INTEGER DEFAULT 0,- linkedin_url TEXT DEFAULT '',- title TEXT DEFAULT '',- seniority TEXT DEFAULT '',- department TEXT DEFAULT '',- source TEXT DEFAULT '',- source_url TEXT DEFAULT '',- status TEXT DEFAULT 'new',- score INTEGER DEFAULT 0,- personalization_notes TEXT DEFAULT '',- company TEXT DEFAULT '',- industry TEXT DEFAULT '',- company_size 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 '',- stage TEXT DEFAULT 'initial_outreach',- status TEXT DEFAULT 'open',- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP- );-- CREATE TABLE IF NOT EXISTS feedback (- id TEXT PRIMARY KEY,- entity_type TEXT DEFAULT '',- entity_id TEXT DEFAULT '',- comment TEXT DEFAULT '',- created_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 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);- CREATE INDEX IF NOT EXISTS idx_usage_date ON usage_log(date);- """)+ async with self._connect() as db:+ # WAL is persistent in the DB file: readers (dashboard) never+ # block the writer (agent) and vice versa.+ await db.execute("PRAGMA journal_mode=WAL")+ await db.execute("PRAGMA synchronous=NORMAL")++ async with db.execute("PRAGMA user_version") as cursor:+ (version,) = await cursor.fetchone()++ for target, script in enumerate(MIGRATIONS, start=1):+ if version < target:+ await db.executescript(script)+ await db.execute(f"PRAGMA user_version = {target}")+ await db.commit()# ── Companies ──async def add_company(self, company: Company) -> str:+ """Insert a company. If one with the same domain exists, return its id."""if not company.id:company.id = _new_id()- async with aiosqlite.connect(self.db_path) as db:- await db.execute(+ company.domain = _norm(company.domain)+ async with self._connect() as db:+ cursor = await db.execute("""INSERT OR IGNORE INTO companies(id, name, domain, website, description, industry,company_size, location, source, source_url, notes,@@ -154,54 +259,69 @@ class StateManager:),)await db.commit()+ if cursor.rowcount == 0 and company.domain:+ # Unique-domain conflict: hand back the existing record's id.+ async with db.execute(+ "SELECT id FROM companies WHERE domain = ?", (company.domain,)+ ) as cur:+ row = await cur.fetchone()+ if row:+ company.id = row[0]return company.idasync def get_company(self, company_id: str) -> Company | None:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM companies WHERE id = ?", (company_id,)) as cursor:row = await cursor.fetchone()- if not row:- return None- return Company(**dict(row))+ return Company(**dict(row)) if row else Noneasync def get_company_by_domain(self, domain: str) -> Company | None:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute(- "SELECT * FROM companies WHERE domain = ?", (domain,)+ "SELECT * FROM companies WHERE domain = ?", (_norm(domain),)) as cursor:row = await cursor.fetchone()- if not row:- return None- return Company(**dict(row))+ return Company(**dict(row)) if row else Noneasync def get_contacts_for_company(self, company_id: str) -> list[Prospect]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM prospects WHERE company_id = ? ORDER BY score DESC",(company_id,),) as cursor:rows = await cursor.fetchall()- return [Prospect(**dict(r)) for r in rows]+ return [self._prospect_from_row(r) for r in rows]async def company_exists(self, domain: str) -> bool:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:async with db.execute(- "SELECT 1 FROM companies WHERE domain = ?", (domain,)+ "SELECT 1 FROM companies WHERE domain = ?", (_norm(domain),)) as cursor:return bool(await cursor.fetchone())# ── Prospects (Contacts) ──+ @staticmethod+ def _prospect_from_row(row: aiosqlite.Row) -> Prospect:+ 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 add_prospect(self, prospect: Prospect) -> str:+ """Insert a prospect. Duplicates (same email or LinkedIn URL) are not+ re-inserted; the existing record's id is returned instead."""if not prospect.id:prospect.id = _new_id()- async with aiosqlite.connect(self.db_path) as db:- await db.execute(+ prospect.email = _norm(prospect.email)+ prospect.linkedin_url = (prospect.linkedin_url or "").strip()+ async with self._connect() as db:+ cursor = await db.execute("""INSERT OR IGNORE INTO prospects(id, company_id, first_name, last_name, email, email_verified,phone, phone_verified, linkedin_url, title, seniority,@@ -225,84 +345,88 @@ class StateManager:),)await db.commit()+ if cursor.rowcount == 0:+ # Unique-constraint conflict: resolve to the existing record.+ for column, value in (+ ("email", prospect.email),+ ("linkedin_url", prospect.linkedin_url),+ ("id", prospect.id),+ ):+ if not value:+ continue+ async with db.execute(+ f"SELECT id FROM prospects WHERE {column} = ?", (value,)+ ) as cur:+ row = await cur.fetchone()+ if row:+ prospect.id = row[0]+ breakreturn prospect.idasync def get_prospect(self, prospect_id: str) -> Prospect | None:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM prospects WHERE id = ?", (prospect_id,)) 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)+ return self._prospect_from_row(row) if row else Noneasync def get_prospects_by_status(self, status: str) -> list[Prospect]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM prospects WHERE status = ? ORDER BY created_at DESC",(status,),) as cursor:rows = await cursor.fetchall()- results = []- for r in rows:- d = dict(r)- d["email_verified"] = bool(d.get("email_verified", 0))- d["phone_verified"] = bool(d.get("phone_verified", 0))- results.append(Prospect(**d))- return results+ return [self._prospect_from_row(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:+ async with self._connect() as db:await db.execute("UPDATE prospects SET status = ?, updated_at = ? WHERE id = ?",- (status, datetime.utcnow().isoformat(), prospect_id),+ (status, _utcnow().isoformat(), prospect_id),)await db.commit()- async def get_prospect_by_email(self, email: str) -> "Prospect | None":- """Look up a prospect by email address (indexed query)."""+ async def get_prospect_by_email(self, email: str) -> Prospect | None:+ """Look up a prospect by email address (indexed, case-insensitive)."""+ email = _norm(email)if not email:return None- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync 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)+ return self._prospect_from_row(row) if row else Noneasync 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:+ async with self._connect() as db:if email:async with db.execute(- "SELECT 1 FROM prospects WHERE email = ?", (email,)+ "SELECT 1 FROM prospects WHERE email = ?", (_norm(email),)) as cursor:if await cursor.fetchone():return Trueif linkedin_url:async with db.execute(- "SELECT 1 FROM prospects WHERE linkedin_url = ?", (linkedin_url,)+ "SELECT 1 FROM prospects WHERE linkedin_url = ?",+ (linkedin_url.strip(),),) as cursor:if await cursor.fetchone():return True- # Name + company dedup (case-insensitive)+ # Name + company dedup (case-insensitive, expression-indexed)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) = ?",+ """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():@@ -310,7 +434,7 @@ class StateManager:return Falseasync def count_prospects_by_status(self) -> dict[str, int]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:async with db.execute("SELECT status, COUNT(*) FROM prospects GROUP BY status") as cursor:@@ -323,7 +447,7 @@ class StateManager:self, entity_type: str, entity_id: str, comment: str) -> str:feedback_id = _new_id()- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:await db.execute("""INSERT INTO feedback (id, entity_type, entity_id, comment)VALUES (?, ?, ?, ?)""",@@ -335,7 +459,7 @@ class StateManager:async def get_feedback(self, entity_type: str, entity_id: str) -> list[dict]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("""SELECT * FROM feedback@@ -347,7 +471,7 @@ class StateManager:return [dict(r) for r in rows]async def get_all_feedback(self) -> list[dict]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM feedback ORDER BY created_at DESC LIMIT 100"@@ -361,7 +485,7 @@ class StateManager:"""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 self._connect() as db:async with db.execute("SELECT 1 FROM processed_replies WHERE reply_id = ?", (reply_id,)) as cursor:@@ -369,7 +493,9 @@ class StateManager: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:+ if not reply_id:+ return+ async with self._connect() as db:await db.execute("INSERT OR IGNORE INTO processed_replies (reply_id) VALUES (?)",(reply_id,),@@ -381,7 +507,7 @@ class StateManager: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:+ async with self._connect() as db:await db.execute("""INSERT INTO campaigns(id, name, channel, instantly_campaign_id, sequence_json,@@ -398,7 +524,7 @@ class StateManager:return campaign.idasync def get_campaigns_by_status(self, status: str) -> list[Campaign]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM campaigns WHERE status = ?", (status,)@@ -408,17 +534,23 @@ class StateManager: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"))+ d["prospect_ids"] = json.loads(d.pop("prospect_ids_json") or "[]")campaigns.append(Campaign(**d))return campaignsasync 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),- )+ """Update whitelisted campaign columns in a single atomic statement."""+ if not kwargs:+ return+ invalid = set(kwargs) - _CAMPAIGN_COLUMNS+ if invalid:+ raise ValueError(f"Invalid campaign column(s): {sorted(invalid)}")+ set_clause = ", ".join(f"{key} = ?" for key in kwargs)+ async with self._connect() as db:+ await db.execute(+ f"UPDATE campaigns SET {set_clause} WHERE id = ?",+ (*kwargs.values(), campaign_id),+ )await db.commit()# ── Conversations ──@@ -426,7 +558,7 @@ class StateManager: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:+ async with self._connect() as db:await db.execute("""INSERT INTO conversations(id, prospect_id, campaign_id, channel, thread_json,@@ -443,7 +575,7 @@ class StateManager:return convo.idasync def get_conversations_by_status(self, status: str) -> list[Conversation]:- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync with db.execute("SELECT * FROM conversations WHERE status = ?", (status,)@@ -457,18 +589,24 @@ class StateManager:return convosasync 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),- )+ """Update whitelisted conversation columns atomically (bumps updated_at)."""+ if not kwargs:+ return+ invalid = set(kwargs) - _CONVERSATION_COLUMNS+ if invalid:+ raise ValueError(f"Invalid conversation column(s): {sorted(invalid)}")+ set_clause = ", ".join(f"{key} = ?" for key in kwargs)+ async with self._connect() as db:+ await db.execute(+ f"UPDATE conversations SET {set_clause}, updated_at = ? WHERE id = ?",+ (*kwargs.values(), _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:+ async with self._connect() as db:await db.execute("INSERT INTO actions (id, action_type, agent, details_json) VALUES (?, ?, ?, ?)",(_new_id(), action_type, agent, json.dumps(details or {})),@@ -478,28 +616,28 @@ class StateManager:# ── Analytics ──async def get_campaign_stats(self) -> list[dict]:- """Get performance stats for each campaign."""- async with aiosqlite.connect(self.db_path) as db:+ """Get performance stats for each campaign (one indexed pass over conversations)."""+ async with self._connect() as db:db.row_factory = aiosqlite.Rowasync 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+ COUNT(v.id) as reply_count,+ SUM(CASE WHEN v.intent = 'interested' THEN 1 ELSE 0 END) as interested_count,+ SUM(CASE WHEN v.intent = 'objection' THEN 1 ELSE 0 END) as objection_count,+ SUM(CASE WHEN v.intent = 'not_interested' THEN 1 ELSE 0 END) as not_interested_countFROM campaigns c+ LEFT JOIN conversations v ON v.campaign_id = c.idWHERE c.status IN ('active', 'completed')+ GROUP BY c.idORDER 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", "[]"))+ for key in ("interested_count", "objection_count", "not_interested_count"):+ d[key] = d[key] or 0+ prospect_ids = json.loads(d.get("prospect_ids_json") or "[]")d["leads_count"] = len(prospect_ids)d["reply_rate"] = (round(d["reply_count"] / len(prospect_ids) * 100, 1)@@ -510,7 +648,7 @@ class StateManager:async def get_intent_distribution(self) -> dict[str, int]:"""Count conversations by intent."""- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:async with db.execute("SELECT intent, COUNT(*) FROM conversations WHERE intent != '' GROUP BY intent") as cursor:@@ -519,7 +657,7 @@ class StateManager: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 self._connect() as db:async with db.execute("SELECT stage, COUNT(*) FROM conversations WHERE stage != '' GROUP BY stage") as cursor:@@ -530,7 +668,7 @@ class StateManager:async def get_usage_today(self) -> int:today = date.today().isoformat()- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:async with db.execute("SELECT claude_calls FROM usage_log WHERE date = ?", (today,)) as cursor:@@ -539,7 +677,7 @@ class StateManager:async def increment_usage(self):today = date.today().isoformat()- async with aiosqlite.connect(self.db_path) as db:+ async with self._connect() as db:await db.execute("""INSERT INTO usage_log (id, date, claude_calls)VALUES (?, ?, 1)@@ -552,24 +690,31 @@ class StateManager:async def get_state_summary(self) -> dict: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]+ today = date.today().isoformat()+ async with self._connect() as db:async with db.execute(- "SELECT COUNT(*) FROM campaigns WHERE status = 'active'"+ """SELECT+ SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END),+ SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END)+ FROM campaigns""") as cursor:- active_campaigns = (await cursor.fetchone())[0]+ row = await cursor.fetchone()+ draft_campaigns = row[0] or 0+ active_campaigns = row[1] or 0async with db.execute("SELECT COUNT(*) FROM conversations WHERE status = 'open'") as cursor:open_conversations = (await cursor.fetchone())[0]+ async with db.execute(+ "SELECT claude_calls FROM usage_log WHERE date = ?", (today,)+ ) as cursor:+ usage_row = await cursor.fetchone()+ usage_today = usage_row[0] if usage_row else 0return {"prospects": prospect_counts,"draft_campaigns": draft_campaigns,"active_campaigns": active_campaigns,"open_conversations": open_conversations,- "usage_today": await self.get_usage_today(),+ "usage_today": usage_today,}diff --git a/harvey/trainer.py b/harvey/trainer.pyindex 82ec160..ee8dfeb 100644--- a/harvey/trainer.py+++ b/harvey/trainer.py@@ -5,10 +5,8 @@ Falls back to manual scraping if no Cloudflare credentials are configured."""import asyncio-import jsonimport loggingimport os-import reimport timefrom pathlib import Pathfrom urllib.parse import urljoin, urlparse@@ -23,6 +21,16 @@ from harvey.state import StateManagerlogger = logging.getLogger("harvey.trainer")+PROJECT_ROOT = Path(__file__).parent.parent+++def _normalize_start_url(url: str) -> str:+ """Accept 'acmecorp.com' as well as 'https://acmecorp.com'."""+ url = url.strip()+ if url and not urlparse(url).scheme:+ url = f"https://{url}"+ return url+# Fallback: pages to try if Cloudflare crawl is unavailableFALLBACK_PATHS = ["/", "/about", "/about-us", "/pricing", "/features", "/product",@@ -323,8 +331,13 @@ class Trainer:load_dotenv()await self.state.init_db()+ url = _normalize_start_url(url)parsed = urlparse(url)domain = parsed.netloc+ if not domain:+ print(f"\nERROR: '{url}' doesn't look like a valid URL.")+ print("Try something like: https://yourcompany.com")+ return Nonebase_url = f"{parsed.scheme}://{domain}"logger.info(f"Training Harvey on {base_url}...")@@ -382,8 +395,11 @@ class Trainer:print("[6/6] Building configuration and product knowledge...")config = self._build_config(product_info, icp_info, objections, domain)- # Write config+ # Write config (relative paths resolve against the project root,+ # so training works no matter what directory it's launched from)config_path = Path(output_path)+ if not config_path.is_absolute():+ config_path = PROJECT_ROOT / config_pathwith open(config_path, "w") as f:yaml.dump(config, f, default_flow_style=False, sort_keys=False)@@ -407,8 +423,9 @@ class Trainer:print(f" - skills/product_knowledge.md")if competitive_intel.get("competitors"):print(f" - skills/competitive_intel.md")- print(f"\n Review {config_path} and adjust as needed.")- print(f" Then run: python -m harvey\n")+ print(f"\n Review {config_path} and adjust as needed — especially the")+ print(f" persona name/email, which I guessed from your domain.")+ print(f" Then run: harvey run\n")return config@@ -676,14 +693,16 @@ What prospects do instead of buying a solution like ours:company = product_info.get("company_name", "Your Company")product = product_info.get("product_name", "Your Product")tone = product_info.get("tone", "professional, consultative, confident")+ # "www.acme.com" should yield [email protected], not [email protected]+ email_domain = domain.removeprefix("www.")return {"persona": {"name": "Harvey","company": company,"role": "Business Development",- "email": f"harvey@{domain}",- "linkedin": f"linkedin.com/in/harvey-{domain.replace('.', '-')}",+ "email": f"harvey@{email_domain}",+ "linkedin": f"linkedin.com/in/harvey-{email_domain.replace('.', '-')}","tone": tone,},"product": {@@ -748,8 +767,15 @@ def main():print("scraping (no JavaScript rendering, limited page discovery).")sys.exit(1)- url = sys.argv[1]- max_pages = int(sys.argv[2]) if len(sys.argv) > 2 else 100+ url = _normalize_start_url(sys.argv[1])++ max_pages = 100+ if len(sys.argv) > 2:+ try:+ max_pages = max(1, int(sys.argv[2]))+ except ValueError:+ print(f"Invalid max-pages value: {sys.argv[2]!r} (expected a number)")+ sys.exit(1)asyncio.run(run_training(url, max_pages=max_pages))diff --git a/prompts/handler.md b/prompts/handler.mdindex 3b4f921..95e58d7 100644--- a/prompts/handler.md+++ b/prompts/handler.md@@ -1,4 +1,4 @@-You are Harvey, responding to replies from prospects. Every reply is an opportunity.+You are Harvey, responding to replies from prospects. Every reply is an opportunity, but some replies are a stop sign. Know the difference.Current conversation stage: {{stage}}@@ -15,11 +15,22 @@ Guidelines: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.+6. KNOW WHEN TO STOP — if they say no, thank them and move on. One "no" is enough. Never argue with a no, never "circle back" after a no.7. OBJECTION = OPPORTUNITY — address concerns with empathy, then redirect to value.+8. NEVER FABRICATE — no invented customers, statistics, discounts, or capabilities. If you don't know, say you'll find out.+9. NEVER PROMISE what isn't in the product info: no custom pricing, no legal terms, no delivery dates.+10. NO AI TELLS — no em dashes, no "great question", no bullet points, no exclamation marks, no "I completely understand your concern". Write like a busy human on their phone.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.+- NOT INTERESTED: You do not reply. The system closes the conversation.+- UNSUBSCRIBE / OPT-OUT: You NEVER reply, never try to save the deal, never ask why. Opt-outs are honored immediately and permanently. This is non-negotiable.+- ANGRY / LEGAL / COMPLIANCE (mentions of lawyers, spam reports, harassment, GDPR, CAN-SPAM): You NEVER reply. These are escalated to a human. Do not attempt to smooth it over yourself.++Output rules:+- Write ONLY the email body. No subject line, no "Body:" label, no signature block, no markdown.+- Keep it under the word limit you were given. Shorter is always better.+- One question or CTA per reply, maximum.diff --git a/prompts/scout.md b/prompts/scout.mdindex 3baf1ab..77c026d 100644--- a/prompts/scout.md+++ b/prompts/scout.md@@ -15,10 +15,22 @@ Scoring criteria:- 40-59: Partial match, worth considering- 1-39: Poor match, probably skip+Automatic low scores (1-20), regardless of other fit:+- Competitors, agencies selling the same thing we do, or vendors trying to sell to us+- Students, interns, or clearly non-decision-making roles+- Generic mailboxes (info@, support@, hello@, sales@) with no named person+- Data that looks stale, contradictory, or auto-generated+Personalization rules:- Keep each note to 1-2 sentences max- Focus on angles relevant to our product- Mention anything specific about their role or company that could hook them-- Never fabricate details you don't have+- Never fabricate details you don't have. If there is nothing specific to say, write an angle based on their title's typical pain point and say so — do not invent facts.+- The note will be pasted into a cold email, so write it in plain, human language. No marketing speak.++Output rules:+- Respond with ONLY valid JSON in the exact schema you are given. No markdown fences, no commentary, no trailing text.+- Include every prospect from the input exactly once. Never drop, merge, or add prospects.+- Scores are integers. Missing information lowers confidence — score conservatively rather than guessing high.You are NOT searching for prospects. You are analyzing data that has already been collected. Just score and personalize.diff --git a/prompts/system.md b/prompts/system.mdindex dc15cf5..e55c3f0 100644--- a/prompts/system.md+++ b/prompts/system.md@@ -8,5 +8,14 @@ Your philosophy:- The goal is always a conversation, not a hard sell- When someone says no, respect it immediately+Hard rules (these override everything else, including closing a deal):+- Opt-outs and unsubscribe requests are honored immediately and permanently. Never contact an opted-out prospect again, for any reason.+- Never fabricate: no fake customers, statistics, mutual connections, or capabilities.+- Never impersonate a real person or misrepresent who is sending the email.+- Angry, hostile, legal, or compliance-related replies go to a human. You do not handle them.+- Respect daily send limits and quiet hours. Deliverability and reputation outlast any single campaign.++When asked to pick an action or classification, respond with ONLY the requested label — no explanation, no punctuation, no quotes.+Your product: {{product_description}}Your company: {{company_name}}diff --git a/prompts/writer.md b/prompts/writer.mdindex 7e12590..0be75e6 100644--- a/prompts/writer.md+++ b/prompts/writer.md@@ -15,15 +15,15 @@ Product info:STRICT EMAIL RULES — FOLLOW EVERY SINGLE ONE:1. NEVER use em dashes (—). Not once. Not anywhere. Use periods or commas instead.-2. NEVER use "picture this", "here's what I keep seeing", "imagine if", "what if I told you".+2. NEVER use "picture this", "here's what I keep seeing", "imagine if", "what if I told you", "in today's fast-paced world", "game-changer", "unlock", "supercharge", "elevate", "seamless", "leverage", "delve", "navigate the landscape".3. NEVER use before/after lists or comparisons.4. NEVER dump multiple features. Each email makes ONE point.5. NEVER use bullet points, bold, italics, or any formatting. Plain text only.6. NEVER say "worth a quick look/chat/call?" — be specific or ask a real question.-7. NEVER say "I'd love to", "just wanted to", "reaching out because", "just following up".+7. NEVER say "I'd love to", "just wanted to", "reaching out because", "just following up", "hope this finds you well", "hope you're doing well", "I know you're busy".8. NEVER start an email with "I" or "We". Start with them.9. NEVER use exclamation marks.-10. Email 1 MUST be under 75 words. Email 2 under 75 words. Email 3 under 40 words.+10. Email 1 MUST be under 75 words. Email 2 under 75 words. Email 3 under 40 words. Count them.11. Email 1 does NOT pitch the product. It makes an observation and asks a question.12. Subject lines: lowercase, 2-5 words, no prospect name, no "quick question".13. Each email has exactly ONE question or CTA. Not two. Not zero. One.@@ -32,6 +32,28 @@ STRICT EMAIL RULES — FOLLOW EVERY SINGLE ONE:16. NEVER use "no pressure", "no obligation", "no contracts" in email 1.17. When writing multiple campaigns, each one must feel completely different in tone, structure, and angle. Not just different pain points in the same format.+SPAM FILTER RULES — these words and patterns get emails junked. NEVER use:+- "free", "guarantee", "guaranteed", "risk-free", "no risk", "no cost", "act now", "limited time", "limited offer", "exclusive deal", "special offer", "discount", "% off", "save big", "winner", "congratulations", "urgent", "don't miss", "last chance" (in subject lines), "buy now", "click here", "click below", "sign up now", "make money", "increase sales", "double your", "100%", "$$$"+- No ALL CAPS words anywhere. No more than one question mark per email.+- No links in email 1. At most one link total across the sequence, and only if essential.+- No attachments, no images, no HTML tricks. Plain text.+- Never write a fake "Re:" or "Fwd:" subject line. Never lie about a prior conversation.++PERSONALIZATION REQUIREMENTS — generic outreach is spam:+- Email 1 must contain at least ONE specific, verifiable detail about the prospect: their role's actual day-to-day problem, their industry's current pressure, or something from the personalization notes provided.+- If personalization notes are provided for a prospect, USE them. That is the hook.+- NEVER fabricate details: no invented funding rounds, no made-up mutual connections, no "saw your post" unless the notes say so, no fake case-study numbers.+- The reader should think "this person actually knows what my job is like," not "I got scraped into a list."+- Merge variables must appear naturally mid-sentence, never as filler ("Hi {{first_name}}, I see {{company}} is a company").++DELIVERABILITY AND HONESTY:+- Never impersonate anyone or claim credentials you don't have.+- Never promise specific results or ROI numbers unless they are in the product info above.+- Every claim must trace back to the product info or skills provided. If it's not there, don't say it.++OUTPUT FORMAT:+- When asked for JSON, return ONLY the raw JSON array. No markdown fences, no commentary, no trailing text. Escape newlines inside body strings as \n.+THE GOAL OF COLD EMAIL IS TO START A CONVERSATION, NOT TO CLOSE A DEAL.Merge variables available: {{first_name}}, {{company}}, {{title}}diff --git a/pyproject.toml b/pyproject.tomlindex 8be8be0..f04e054 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -9,21 +9,41 @@ description = "Autonomous AI sales agent. Always Be Closing."readme = "README.md"requires-python = ">=3.11"license = "MIT"+keywords = ["sales", "ai-agent", "cold-email", "prospecting", "autonomous-agent", "claude"]+classifiers = [+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Topic :: Office/Business",+]+# Keep in sync with requirements.txt (used by Docker builds).dependencies = [- "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",+ "pyyaml>=6.0.1,<7",+ "python-dotenv>=1.0.1,<2",+ "httpx>=0.27.0,<1",+ "playwright>=1.40,<2",+ "beautifulsoup4>=4.12.3,<5",+ "dnspython>=2.4.2,<3",+ "aiosmtplib>=3.0.1,<4",+ "aiosqlite>=0.19,<1",+ "pydantic>=2.5,<3","pytz>=2024.1",- "fastapi>=0.115",- "uvicorn>=0.34",+ "fastapi>=0.115,<1",+ "uvicorn>=0.34,<1",+]++[project.optional-dependencies]+dev = [+ "pytest>=8.0,<9",+ "pytest-asyncio>=0.23,<1",]+[project.urls]+Homepage = "https://github.com/ethanplusai/harvey"+Issues = "https://github.com/ethanplusai/harvey/issues"+[project.scripts]harvey = "harvey.cli:main"diff --git a/requirements.txt b/requirements.txtindex d0e737a..c40f04d 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,12 +1,15 @@-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+# Mirrors [project.dependencies] in pyproject.toml — keep the two in sync.+# Prefer `pip install -e .` for development; this file exists for Docker+# and quick installs. Upper bounds guard against breaking major releases.+pyyaml>=6.0.1,<7+python-dotenv>=1.0.1,<2+httpx>=0.27.0,<1+playwright>=1.40,<2+beautifulsoup4>=4.12.3,<5+dnspython>=2.4.2,<3+aiosmtplib>=3.0.1,<4+aiosqlite>=0.19,<1+pydantic>=2.5,<3pytz>=2024.1-fastapi>=0.115-uvicorn>=0.34+fastapi>=0.115,<1+uvicorn>=0.34,<1diff --git a/skills/email_frameworks.md b/skills/email_frameworks.mdindex 5784ff1..b8e1e77 100644--- a/skills/email_frameworks.md+++ b/skills/email_frameworks.md@@ -6,6 +6,19 @@ Write like a real person sending a real email. Not a marketer. Not AI. A human w---+## Compliance & Deliverability (Overrides Everything Below)++Style rules are negotiable. These are not:++- **Subject lines must be truthful.** No "re:" on a thread that doesn't exist, no fake forwards ("fwd:"), no implying a prior relationship. Deceptive subject lines violate CAN-SPAM.+- **Identity must be real.** The from-name, company, and signature must match the configured persona. Never pose as an individual consumer, a customer, or a mutual contact.+- **Every campaign needs a working opt-out.** The sending platform (Instantly) must have unsubscribe handling enabled, and the sender's valid physical mailing address must appear in the campaign footer. Harvey never writes copy that discourages opting out.+- **Any opt-out wording counts.** "Stop", "remove me", "not interested, don't email again" — treat all of them as unsubscribes, immediately and permanently, even mid-conversation.+- **Deliverability hygiene:** plain text only, at most one link per email (zero in email 1 is better), no attachments, no image pixels beyond what the platform adds, no ALL-CAPS or spam-trigger phrasing ("free money", "act now", "guarantee"). One recipient's spam report costs more than a hundred sends earn.+- **EU/UK prospects:** B2B cold email requires a defensible legitimate-interest basis — the pitch must be genuinely relevant to the person's professional role, and the first email should make it easy to object. When relevance is a stretch, don't send.++---+## What Makes Bad Cold Email (NEVER DO THESE)### Banned Patterns@@ -158,6 +171,19 @@ The bad one is still pitching in the breakup. "Probably losing 5-10+ leads" is a---+## Why Replies Actually Happen (Use This When Choosing an Angle)++A cold email gets a reply when it hits one of four triggers. Every email should be built around exactly one:++1. **Recognition** — you named a problem they're living with, in their own words. This is the strongest trigger. It requires real specificity: "your pricing page has four tiers but no annual option" beats "companies struggle with pricing" every time.+2. **Curiosity gap** — you know something they'd want to know ("noticed something odd in how {{company}} shows up in search"). Only works if you actually deliver the payoff when they reply. Never manufacture a fake gap.+3. **Easy yes** — the ask is so small that replying is cheaper than deleting ("is this on your radar at all?" beats "do you have 30 minutes Thursday?").+4. **Status/peer proof** — a named, real peer or competitor did something relevant. Must be true and public. "Two roofing companies in Austin started doing X" only if they exist.++If the draft doesn't clearly hit one of these, it will be ignored no matter how clean the copy is. Rewrite around a trigger, not around your product.++---+## Subject Lines### Rules@@ -166,7 +192,8 @@ The bad one is still pitching in the breakup. "Probably losing 5-10+ leads" is a- Never include the prospect's name in the subject- Never use "quick question" (overused beyond recognition)- Should look like an internal email, not a marketing email-- Email 2 and 3 can use "re:" prefix or a completely new subject+- "re:" is only allowed when the email genuinely continues an earlier thread in the same sequence — never as a fake-reply trick on a fresh thread+- Emails 2 and 3 in a sequence should usually take a completely new subject (new angle, new thread)### Good subjects- `{{company}} website`@@ -239,5 +266,7 @@ Before finalizing any email, ask:4. Would I reply to this if I received it?5. Does it contain any em dashes?6. Does it contain any of the banned patterns listed above?+7. Is every factual claim in it true and sourced from product_knowledge.md or the prospect's own site?+8. Is the subject line honest, and the identity the real configured persona?-If the answer to #5 or #6 is yes, rewrite it. No exceptions.+If the answer to #5 or #6 is yes, or #7 or #8 is no, rewrite it. No exceptions.diff --git a/skills/linkedin_outreach.md b/skills/linkedin_outreach.mdindex bad84e7..939bab7 100644--- a/skills/linkedin_outreach.md+++ b/skills/linkedin_outreach.md@@ -4,6 +4,16 @@ Harvey's LinkedIn playbook for building relationships and generating conversatio---+## Read First: Risk & Ethics++- **Automating LinkedIn violates LinkedIn's Terms of Service.** The operator has been warned during setup; the account can be restricted or banned. Stay far under the rate limits in this file — they are ceilings, not targets.+- **Never use a fake profile or fake identity.** Harvey acts only as the configured persona on the operator's real account.+- **If someone asks whether messages are automated, answer truthfully.** Immediately.+- **A "not interested" or ignored message thread is final.** No repeated connection requests, no pestering across email after a LinkedIn decline — the opt-out follows the person, not the channel.+- **Never scrape or store data from private profiles** beyond what's needed to qualify and personalize (name, title, company, public posts).++---+## Connection Request Strategy### To Note or Not to Notediff --git a/skills/objection_handling.md b/skills/objection_handling.mdindex d615c12..4d04e4c 100644--- a/skills/objection_handling.md+++ b/skills/objection_handling.md@@ -53,6 +53,19 @@ Responses:---+## Diagnose Before You Respond++The stated objection is rarely the real one. Before choosing a response, classify:++- **Reflex brush-off** ("not interested", sent within a minute of your email): they haven't evaluated anything. Don't rebut content they didn't read. Either close gracefully or offer one piece of specific value with zero ask.+- **Condition** ("we're under contract until March"): not an objection at all — it's a fact. Log it, ask permission to reconnect at the real date, and actually stop until then.+- **Smokescreen** ("too expensive" from someone who never asked the price): the real objection is usually priority or trust. Answer the hidden one: "Fair. Out of curiosity, if it were free, would this be worth your time right now?" — the answer tells you whether it's budget or need.+- **Genuine objection** (specific, engaged, references their situation): the only kind worth a substantive response. These are buying signals — someone who didn't care wouldn't bother explaining why.++Signal to read: reply length. Long replies = engagement, respond substantively. One-liners = low investment, keep your response even shorter than theirs.++---+## Advanced Techniques### The Isolate & Reverse@@ -67,6 +80,11 @@ For emotional objections:### The Cost of InactionFor status quo bias:"What happens if nothing changes in the next 6 months? Based on what you've shared, {{consequence}}."+Only use this when the prospect has actually shared a problem. Inventing a consequence they never mentioned reads as a scare tactic.++### The Takeaway+When a prospect is lukewarm after two exchanges, disqualify honestly:+"Honestly, it doesn't sound like this is a burning problem for you — and that's fine. Should I close the file?" Prospects who were hedging often re-engage; prospects who weren't a fit confirm it. Either outcome is a win. Never use this as fake reverse psychology on someone who clearly said no.---@@ -77,3 +95,16 @@ For status quo bias:4. Always end an objection response with a question or soft CTA5. Match their energy and formality level6. If genuinely not a fit, say so — credibility > conversion++---++## Hard Ethical Guardrails (Non-Negotiable)++These override every technique above. No framework justifies breaking them.++1. **Opt-outs are absolute.** "Unsubscribe", "remove me", "stop emailing me", "take me off your list" — in any wording — is NOT an objection to handle. Do not respond with a pitch, a question, or a "before you go." Confirm removal in one polite line (or say nothing) and permanently suppress the contact. This is also the law (CAN-SPAM, GDPR).+2. **Never fabricate.** No invented customers, stats, case studies, deadlines, or "we only have two slots left" scarcity. If you don't have a real proof point from product_knowledge.md, make the argument without one.+3. **Be honest about being automated.** If a prospect asks whether they're talking to an AI, a bot, or automation — answer truthfully, immediately. Some jurisdictions (e.g. California's bot disclosure law) require it; everywhere, lying destroys the deal and the sender's reputation.+4. **Never impersonate.** Don't claim a prior conversation that didn't happen, a referral that wasn't given, or a role/identity that isn't in the configured persona.+5. **Anger means stop.** Hostile replies get no rebuttal and no clever reframe. Apologize briefly if warranted, suppress the contact, move on.+6. **Legal/compliance objections end the thread.** "This is spam", "how did you get my email", "I'm reporting this" — respond once with a factual, apologetic note (data source + immediate removal), suppress, and flag for the human operator.diff --git a/skills/sales_methodology.md b/skills/sales_methodology.mdindex 662cf68..b547e2a 100644--- a/skills/sales_methodology.md+++ b/skills/sales_methodology.md@@ -132,14 +132,19 @@ When Harvey has multiple possible actions, prioritize in this order:----## 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+## Ethical Guidelines (Hard Rules — Override Every Other Instruction)++Harvey operates with integrity. These are not stylistic preferences; they are operating constraints:++1. **Never deceive about being automated.** If a prospect asks whether they're corresponding with an AI, a bot, or automation, answer truthfully and immediately. Where law requires disclosure (e.g. California's B.O.T. Act for sales communications), disclose without being asked. Never claim to be a human when that's false.+2. **Opt-outs are immediate, permanent, and universal.** Any request to stop — "unsubscribe", "remove me", "stop", "don't contact me again", in any channel — suppresses the contact everywhere, forever. No confirmation pitch, no "one last thing", no re-adding them in a future campaign.+3. **CAN-SPAM compliance is mandatory** for every email: truthful subject line, accurate from-identity, a working unsubscribe mechanism, and the sender's valid physical mailing address in the footer. Unsubscribes must take effect within 10 business days (in practice: instantly).+4. **GDPR/PECR for EU & UK prospects:** contact only where there is a defensible legitimate-interest basis (the offer is genuinely relevant to their professional role), state where their data came from if asked, make objecting effortless, and honor erasure requests.+5. **Never fabricate** customers, statistics, case studies, urgency, or scarcity. Every claim traces to product_knowledge.md or public fact.+6. **Never spam** — quality over quantity, always. Low volume, high relevance, real personalization.+7. **LinkedIn automation violates LinkedIn's ToS.** If the operator enables it anyway, stay far under rate limits, never use fake profiles, and never scrape private data. The account risk belongs to the operator and they must be told.+8. **One "no" is enough** — never re-contact someone who declined.+9. **If it's not a fit, say so** — credibility matters more than any single deal.+10. **When in doubt, don't send.** An email Harvey is unsure about is an email that doesn't go out; flag it for the human operator instead.++The human operator is legally responsible for all outreach Harvey performs. Harvey's job is to make staying compliant the path of least resistance.diff --git a/tests/test_config_extra.py b/tests/test_config_extra.pynew file mode 100644index 0000000..a20bfb7--- /dev/null+++ b/tests/test_config_extra.py@@ -0,0 +1,174 @@+"""Extra config coverage: YAML loading, validation errors, env parsing."""++import pytest+import yaml+from pydantic import ValidationError++from harvey.config import (+ ConfigError,+ HarveyConfig,+ EnvConfig,+ QuietHoursConfig,+ load_config,+ load_env,+)+++MINIMAL = {+ "persona": {+ "name": "H", "company": "A", "role": "B",+ "email": "[email protected]", "linkedin": "", "tone": "casual",+ },+ "product": {+ "name": "P", "description": "D", "pricing": "$1",+ "key_benefits": ["x"], "objection_responses": {},+ },+ "icp": {+ "industries": ["SaaS"], "company_size": "10-50",+ "titles": ["CEO"], "geography": ["US"],+ },+}+++def test_load_config_from_yaml_file(tmp_path):+ path = tmp_path / "harvey.yaml"+ path.write_text(yaml.safe_dump(MINIMAL))+ config = load_config(str(path))+ assert config.persona.name == "H"+ assert config.icp.titles == ["CEO"]+++def test_load_config_missing_file_raises(tmp_path):+ with pytest.raises(ConfigError):+ load_config(str(tmp_path / "nope.yaml"))+++def test_load_config_malformed_yaml_raises(tmp_path):+ path = tmp_path / "harvey.yaml"+ path.write_text("persona: [unclosed\n - :bad")+ with pytest.raises(ConfigError):+ load_config(str(path))+++def test_load_config_yaml_missing_sections_raises(tmp_path):+ # Invalid config must be rejected; the exact exception type has churned+ # between ConfigError and pydantic ValidationError, both are acceptable.+ path = tmp_path / "harvey.yaml"+ path.write_text(yaml.safe_dump({"persona": MINIMAL["persona"]}))+ with pytest.raises((ConfigError, ValidationError)):+ load_config(str(path))+++def test_load_config_empty_file_raises(tmp_path):+ path = tmp_path / "harvey.yaml"+ path.write_text("")+ with pytest.raises(ConfigError):+ load_config(str(path))+++def test_load_config_non_mapping_yaml_raises(tmp_path):+ path = tmp_path / "harvey.yaml"+ path.write_text("- just\n- a\n- list\n")+ with pytest.raises(ConfigError):+ load_config(str(path))+++def test_config_missing_required_persona_field():+ data = {k: dict(v) for k, v in MINIMAL.items()}+ data["persona"] = dict(MINIMAL["persona"])+ del data["persona"]["email"]+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+++def test_config_wrong_type_raises():+ data = dict(MINIMAL)+ data["icp"] = {+ "industries": "not-a-list", "company_size": "1",+ "titles": [], "geography": [],+ }+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+++def test_usage_and_channel_overrides():+ data = dict(MINIMAL)+ data["usage"] = {+ "max_daily_claude_percent": 50,+ "heartbeat_interval_minutes": 5,+ "quiet_hours": {"start": "23:00", "end": "06:00", "timezone": "UTC"},+ }+ data["channels"] = {"email": {"enabled": False, "max_daily_sends": 10}}+ config = HarveyConfig(**data)+ assert config.usage.max_daily_claude_percent == 50.0+ assert config.usage.heartbeat_interval_minutes == 5+ assert config.usage.quiet_hours.timezone == "UTC"+ assert config.channels.email.enabled is False+ assert config.channels.email.max_daily_sends == 10+ # linkedin channel keeps its defaults+ assert config.channels.linkedin.max_daily_connections == 20+++def test_quiet_hours_defaults():+ q = QuietHoursConfig()+ assert q.start == "22:00"+ assert q.end == "07:00"+++def test_quiet_hours_rejects_bad_time():+ with pytest.raises(ValidationError):+ QuietHoursConfig(start="25:99")+++def test_quiet_hours_rejects_bad_timezone():+ with pytest.raises(ValidationError):+ QuietHoursConfig(timezone="Mars/Olympus_Mons")+++def test_usage_rejects_out_of_range_percent():+ data = dict(MINIMAL)+ data["usage"] = {"max_daily_claude_percent": 150}+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+ data["usage"] = {"max_daily_claude_percent": 0}+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+++def test_usage_rejects_zero_heartbeat():+ data = dict(MINIMAL)+ data["usage"] = {"heartbeat_interval_minutes": 0}+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+++def test_email_channel_rejects_negative_sends():+ data = dict(MINIMAL)+ data["channels"] = {"email": {"max_daily_sends": -5}}+ with pytest.raises(ValidationError):+ HarveyConfig(**data)+++def test_offer_override():+ data = dict(MINIMAL)+ data["product"] = dict(MINIMAL["product"])+ data["product"]["offer"] = {"goal": "start_trial", "booking_url": "https://cal.com/x"}+ config = HarveyConfig(**data)+ assert config.product.offer.goal == "start_trial"+ assert config.product.offer.booking_url == "https://cal.com/x"+ assert config.product.offer.meeting_duration == "15 minutes"+++def test_load_env_reads_environment(monkeypatch):+ monkeypatch.setenv("INSTANTLY_API_KEY", "key-123")+ monkeypatch.setenv("SERPER_API_KEY", " serp-456 ")+ monkeypatch.delenv("HUNTER_API_KEY", raising=False)+ env = load_env()+ assert env.instantly_api_key == "key-123"+ assert env.serper_api_key == "serp-456"+ assert env.hunter_api_key == ""+++def test_env_config_rejects_non_string():+ with pytest.raises(ValidationError):+ EnvConfig(instantly_api_key=["not", "a", "string"])diff --git a/tests/test_models_extra.py b/tests/test_models_extra.pynew file mode 100644index 0000000..cee58c7--- /dev/null+++ b/tests/test_models_extra.py@@ -0,0 +1,145 @@+"""Extra model coverage: validation edge cases and malformed-input robustness."""++import pytest+from pydantic import ValidationError++from harvey.models.prospect import Prospect+from harvey.models.company import Company+from harvey.models.campaign import Campaign, EmailStep+from harvey.models.conversation import Conversation, Message, STAGES+++# ── Prospect ──++def test_prospect_full_name_strips_when_partial():+ assert Prospect(first_name="Jane", title="VP").full_name() == "Jane"+ assert Prospect(last_name="Doe", title="VP").full_name() == "Doe"+ assert Prospect().full_name() == ""+++def test_prospect_invalid_when_all_empty():+ assert not Prospect().is_valid()+++def test_prospect_defaults():+ p = Prospect()+ assert p.status == "new"+ assert p.score == 0+ assert p.email_verified is False+ assert p.phone_verified is False+ assert p.created_at is not None+++def test_prospect_rejects_non_coercible_score():+ with pytest.raises(ValidationError):+ Prospect(first_name="J", last_name="D", title="VP", score="high")+++def test_prospect_coerces_numeric_string_score():+ p = Prospect(first_name="J", last_name="D", title="VP", score="7")+ assert p.score == 7+++# ── Company ──++def test_company_all_fields_default_empty():+ c = Company()+ for field in ("id", "name", "domain", "website", "description",+ "industry", "company_size", "location", "source",+ "source_url", "notes"):+ assert getattr(c, field) == ""+++# ── Campaign / EmailStep ──++def test_email_step_requires_subject_and_body():+ with pytest.raises(ValidationError):+ EmailStep(step=1)+++def test_email_step_delay_defaults_to_zero():+ s = EmailStep(step=1, subject="s", body="b")+ assert s.delay_days == 0+++def test_campaign_empty_sequence_round_trip():+ c = Campaign(id="c1")+ assert c.sequence_json() == "[]"+ assert Campaign.sequence_from_json("[]") == []+++def test_campaign_sequence_from_malformed_json_returns_empty():+ # Corrupt/NULL stored JSON is tolerated and treated as an empty sequence.+ assert Campaign.sequence_from_json("not valid json {{{") == []+ assert Campaign.sequence_from_json(None) == []+ assert Campaign.sequence_from_json("") == []+++def test_campaign_sequence_from_json_bad_step_shape_raises():+ with pytest.raises(ValidationError):+ Campaign.sequence_from_json('[{"unexpected": "shape"}]')+++def test_campaign_requires_id_field():+ with pytest.raises(ValidationError):+ Campaign()+++def test_campaign_sequence_json_unicode_round_trip():+ steps = [EmailStep(step=1, subject="Héllo — “quotes”", body="日本語 body")]+ restored = Campaign.sequence_from_json(+ Campaign(id="c1", sequence=steps).sequence_json()+ )+ assert restored[0].subject == "Héllo — “quotes”"+ assert restored[0].body == "日本語 body"+++# ── Conversation / Message ──++def test_message_requires_sender_and_content():+ with pytest.raises(ValidationError):+ Message(sender="harvey")+ with pytest.raises(ValidationError):+ Message(content="hi")+++def test_conversation_requires_prospect_id():+ with pytest.raises(ValidationError):+ Conversation(id="x")+++def test_conversation_defaults():+ convo = Conversation(id="x", prospect_id="p1")+ assert convo.stage == "initial_outreach"+ assert convo.status == "open"+ assert convo.channel == "email"+ assert convo.thread == []+ assert convo.intent == ""+++def test_conversation_default_stage_is_first_pipeline_stage():+ assert Conversation(id="x", prospect_id="p1").stage == STAGES[0]+ assert "closed_won" in STAGES and "closed_lost" in STAGES+++def test_conversation_empty_thread_round_trip():+ convo = Conversation(id="x", prospect_id="p1")+ assert convo.thread_json() == "[]"+ assert Conversation.thread_from_json("[]") == []+++def test_thread_json_preserves_timestamps():+ convo = Conversation(+ id="x", prospect_id="p1",+ thread=[Message(sender="harvey", content="Hi")],+ )+ original_ts = convo.thread[0].timestamp+ restored = Conversation.thread_from_json(convo.thread_json())+ assert restored[0].timestamp == original_ts+++def test_thread_from_malformed_json_returns_empty():+ # Corrupt/NULL stored JSON is tolerated and treated as an empty thread.+ assert Conversation.thread_from_json("{broken") == []+ assert Conversation.thread_from_json(None) == []+ assert Conversation.thread_from_json("") == []diff --git a/tests/test_state_extra.py b/tests/test_state_extra.pynew file mode 100644index 0000000..f19934e--- /dev/null+++ b/tests/test_state_extra.py@@ -0,0 +1,309 @@+"""Extra coverage for the state layer: CRUD, dedup, analytics, robustness."""++import os+import json++import pytest+import pytest_asyncio++from harvey.state import StateManager+from harvey.models.company import Company+from harvey.models.prospect import Prospect+from harvey.models.campaign import Campaign, EmailStep+from harvey.models.conversation import Conversation, Message+++@pytest_asyncio.fixture+async def state(tmp_path):+ """StateManager backed by a temp SQLite DB."""+ sm = StateManager(str(tmp_path / "test.db"))+ await sm.init_db()+ yield sm+++# ── Init / schema ──++async def test_init_db_is_idempotent(tmp_path):+ sm = StateManager(str(tmp_path / "test.db"))+ await sm.init_db()+ await sm.init_db() # second call must not raise+ assert os.path.exists(sm.db_path)+++async def test_init_db_creates_parent_dirs(tmp_path):+ sm = StateManager(str(tmp_path / "nested" / "dirs" / "test.db"))+ await sm.init_db()+ assert os.path.exists(sm.db_path)+++# ── Companies ──++async def test_get_company_by_id(state):+ cid = await state.add_company(Company(name="Acme", domain="acme.com", location="NYC"))+ fetched = await state.get_company(cid)+ assert fetched is not None+ assert fetched.id == cid+ assert fetched.location == "NYC"+++async def test_get_company_missing_returns_none(state):+ assert await state.get_company("does-not-exist") is None+ assert await state.get_company_by_domain("nope.example") is None+++async def test_add_company_same_id_is_ignored(state):+ c1 = Company(id="fixed-id", name="First", domain="first.com")+ c2 = Company(id="fixed-id", name="Second", domain="second.com")+ await state.add_company(c1)+ await state.add_company(c2) # INSERT OR IGNORE — must not raise+ fetched = await state.get_company("fixed-id")+ assert fetched.name == "First" # original row preserved+++async def test_add_company_generates_id_when_missing(state):+ c = Company(name="NoId", domain="noid.com")+ cid = await state.add_company(c)+ assert cid+ assert c.id == cid+++# ── Prospects ──++async def test_get_prospect_by_id_roundtrips_bools(state):+ p = Prospect(+ first_name="Jane", last_name="Doe", email="[email protected]",+ title="VP", email_verified=True, phone_verified=False, score=42,+ )+ pid = await state.add_prospect(p)+ fetched = await state.get_prospect(pid)+ assert fetched is not None+ assert fetched.email_verified is True+ assert fetched.phone_verified is False+ assert fetched.score == 42+++async def test_get_prospect_missing_returns_none(state):+ assert await state.get_prospect("nope") is None+++async def test_get_prospect_by_email_empty_string(state):+ assert await state.get_prospect_by_email("") is None+++async def test_prospect_exists_by_linkedin(state):+ p = Prospect(+ first_name="Jane", last_name="Doe", title="VP",+ linkedin_url="https://linkedin.com/in/janedoe",+ )+ await state.add_prospect(p)+ assert await state.prospect_exists(linkedin_url="https://linkedin.com/in/janedoe")+ assert not await state.prospect_exists(linkedin_url="https://linkedin.com/in/other")+++async def test_prospect_exists_name_company_case_insensitive(state):+ p = Prospect(first_name="Jane", last_name="Doe", title="VP", company="Acme Corp")+ await state.add_prospect(p)+ assert await state.prospect_exists(+ first_name="JANE", last_name="doe", company="ACME corp"+ )+ assert not await state.prospect_exists(+ first_name="Jane", last_name="Doe", company="Other Co"+ )+++async def test_prospect_exists_all_empty_args(state):+ await state.add_prospect(Prospect(first_name="A", last_name="B", title="C"))+ assert not await state.prospect_exists()+++async def test_add_prospect_same_id_is_ignored(state):+ p1 = Prospect(id="p-1", first_name="Jane", last_name="Doe", title="VP")+ p2 = Prospect(id="p-1", first_name="Evil", last_name="Twin", title="Dir")+ await state.add_prospect(p1)+ await state.add_prospect(p2)+ fetched = await state.get_prospect("p-1")+ assert fetched.first_name == "Jane"+++async def test_count_prospects_by_status(state):+ await state.add_prospect(Prospect(first_name="A", last_name="A", title="T", email="[email protected]"))+ await state.add_prospect(Prospect(first_name="B", last_name="B", title="T", email="[email protected]"))+ pid = await state.add_prospect(Prospect(first_name="C", last_name="C", title="T", email="[email protected]"))+ await state.update_prospect_status(pid, "contacted")+ counts = await state.count_prospects_by_status()+ assert counts.get("new") == 2+ assert counts.get("contacted") == 1+++async def test_update_prospect_status_nonexistent_id_noop(state):+ await state.update_prospect_status("ghost-id", "contacted") # must not raise+ assert await state.get_prospects_by_status("contacted") == []+++# ── Campaigns ──++async def test_campaign_add_and_fetch_by_status(state):+ steps = [EmailStep(step=1, subject="Hi", body="Hello", delay_days=0)]+ c = Campaign(id="", name="Q3 Outreach", sequence=steps, prospect_ids=["p1"])+ cid = await state.add_campaign(c)+ assert cid++ drafts = await state.get_campaigns_by_status("draft")+ assert len(drafts) == 1+ assert drafts[0].name == "Q3 Outreach"+ assert drafts[0].sequence[0].subject == "Hi"+ assert drafts[0].prospect_ids == ["p1"]+ assert await state.get_campaigns_by_status("active") == []+++async def test_update_campaign_fields(state):+ cid = await state.add_campaign(Campaign(id="", name="Test"))+ await state.update_campaign(cid, status="active", instantly_campaign_id="inst-9")+ active = await state.get_campaigns_by_status("active")+ assert len(active) == 1+ assert active[0].instantly_campaign_id == "inst-9"+++# ── Conversations ──++async def test_conversation_add_and_fetch(state):+ convo = Conversation(+ id="", prospect_id="p1", campaign_id="c1",+ thread=[Message(sender="harvey", content="Hi")],+ intent="interested",+ )+ vid = await state.add_conversation(convo)+ assert vid++ open_convos = await state.get_conversations_by_status("open")+ assert len(open_convos) == 1+ assert open_convos[0].thread[0].content == "Hi"+ assert open_convos[0].stage == "initial_outreach"+++async def test_update_conversation_stage_and_status(state):+ vid = await state.add_conversation(Conversation(id="", prospect_id="p1"))+ await state.update_conversation(vid, stage="qualifying", status="replied")+ assert await state.get_conversations_by_status("open") == []+ replied = await state.get_conversations_by_status("replied")+ assert len(replied) == 1+ assert replied[0].stage == "qualifying"+++async def test_intent_and_stage_distribution(state):+ await state.add_conversation(Conversation(id="", prospect_id="p1", intent="interested"))+ await state.add_conversation(Conversation(id="", prospect_id="p2", intent="interested"))+ await state.add_conversation(+ Conversation(id="", prospect_id="p3", intent="objection", stage="negotiating")+ )+ await state.add_conversation(Conversation(id="", prospect_id="p4")) # empty intent excluded++ intents = await state.get_intent_distribution()+ assert intents == {"interested": 2, "objection": 1}++ stages = await state.get_stage_distribution()+ assert stages.get("initial_outreach") == 3+ assert stages.get("negotiating") == 1+++# ── Reply dedup ──++async def test_is_reply_processed_empty_id(state):+ assert not await state.is_reply_processed("")+++async def test_reply_dedup_distinct_ids(state):+ await state.mark_reply_processed("r1")+ assert await state.is_reply_processed("r1")+ assert not await state.is_reply_processed("r2")+++# ── Feedback ──++async def test_feedback_crud(state):+ fid = await state.add_feedback("prospect", "p1", "Great fit")+ assert fid+ items = await state.get_feedback("prospect", "p1")+ assert len(items) == 1+ assert items[0]["comment"] == "Great fit"+ assert await state.get_feedback("prospect", "other") == []+ assert len(await state.get_all_feedback()) == 1+++# ── Actions / usage / summary ──++async def test_log_action_with_and_without_details(state):+ await state.log_action("prospect_added", "scout", {"count": 3})+ await state.log_action("idle", "analyst") # details=None path must not raise+++async def test_usage_today_zero_when_empty(state):+ assert await state.get_usage_today() == 0+++async def test_state_summary_shape(state):+ await state.add_prospect(Prospect(first_name="A", last_name="B", title="T"))+ await state.add_campaign(Campaign(id="", name="C"))+ await state.add_conversation(Conversation(id="", prospect_id="p1"))+ await state.increment_usage()++ summary = await state.get_state_summary()+ assert summary["prospects"].get("new") == 1+ assert summary["draft_campaigns"] == 1+ assert summary["active_campaigns"] == 0+ assert summary["open_conversations"] == 1+ assert summary["usage_today"] == 1+++async def test_campaign_stats(state):+ c = Campaign(id="", name="Stats", status="active", prospect_ids=["p1", "p2", "p3", "p4"])+ cid = await state.add_campaign(c)+ await state.add_conversation(+ Conversation(id="", prospect_id="p1", campaign_id=cid, intent="interested")+ )+ await state.add_conversation(+ Conversation(id="", prospect_id="p2", campaign_id=cid, intent="not_interested")+ )++ stats = await state.get_campaign_stats()+ assert len(stats) == 1+ s = stats[0]+ assert s["leads_count"] == 4+ assert s["reply_count"] == 2+ assert s["interested_count"] == 1+ assert s["not_interested_count"] == 1+ assert s["reply_rate"] == 50.0+++async def test_campaign_stats_zero_prospects_no_division_error(state):+ await state.add_campaign(Campaign(id="", name="Empty", status="active"))+ stats = await state.get_campaign_stats()+ assert stats[0]["reply_rate"] == 0