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.
Rework email finding into a pattern-first, honestly-graded pipeline
Ethana6a69304480c
diff --git a/.env.example b/.env.exampleindex 051dd55..f539e3b 100644--- a/.env.example+++ b/.env.example@@ -35,10 +35,27 @@ CLOUDFLARE_ACCOUNT_ID=CLOUDFLARE_API_TOKEN=# -------------------------------------------------------------# Hunter.io — email discovery/verification fallback [OPTIONAL]+# Email verification — how Harvey confirms a prospect's address really+# exists before sending. Harvey learns each company's email PATTERN, then+# verifies ONE candidate (raw SMTP probing no longer works against Google+# Workspace / Microsoft 365). Any ONE of these keys is enough; add both for+# best coverage. Without any, addresses are marked "guess" and never sent.++# Reoon — best free tier for cold-email verification (600 checks/month,+# renews monthly + 100 non-expiring). Good catch-all flagging.+# Where to get it: https://reoon.com/email-verifier → sign up → API+REOON_API_KEY=++# ZeroBounce — 100 free/month. Its 2026 engine is the reliable one for+# Microsoft 365 / Google Workspace catch-all domains; Harvey routes those+# domains here specifically. https://zerobounce.net → API+ZEROBOUNCE_API_KEY=++# Hunter.io — email discovery + pattern lookup [OPTIONAL]+# Free tier: 50 verifications + 25 domain-searches/month. Its domain-search+# is the cheapest way to learn a company's email pattern (used first, so+# Harvey verifies one address instead of guessing six).# 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=# ------------------------------------------------------------diff --git a/CLAUDE.md b/CLAUDE.mdindex e2fc940..dfa9cb0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -38,7 +38,7 @@ People will ask "how does this work?" — explain it simply:- **"What does Harvey do?"** → It's like having a tireless sales assistant. Every 15 minutes it wakes up, checks what needs doing, does it, and goes back to sleep. It finds prospects, writes emails, sends campaigns, and responds to replies.-- **"How does it find people?"** → It searches the web (DuckDuckGo, Bing, Google) for companies matching your target profile, visits their websites, finds team members, and verifies their email addresses. No expensive tools needed.+- **"How does it find people?"** → It searches the web (DuckDuckGo, Bing, Google) for companies matching your target profile, visits their websites, and finds team members. For emails, it learns each company's address pattern (from their site, or a free Hunter domain lookup) and verifies a single candidate through a free verification tier — every address is tagged verified / catch-all / guess, and only deliverable ones get sent. No expensive tools needed.- **"How does it write emails?"** → It uses proven cold email frameworks (like AIDA and PAS) with strict rules — short, personal, no AI-sounding language. Each email is tailored to the specific person and their company.@@ -75,10 +75,14 @@ LINKEDIN_EMAIL= # Optional — for LinkedIn prospectingLINKEDIN_PASSWORD= # Optional — for LinkedIn prospectingCLOUDFLARE_ACCOUNT_ID= # Optional — for deep JS-rendered website crawlingCLOUDFLARE_API_TOKEN= # Optional — for deep JS-rendered website crawling-HUNTER_API_KEY= # Optional — for email verification fallback+REOON_API_KEY= # Optional — email verification (600 free/mo; best free tier)+ZEROBOUNCE_API_KEY= # Optional — email verification (100 free/mo; best for M365/Workspace catch-alls)+HUNTER_API_KEY= # Optional — email pattern lookup + verification (50 free/mo)SERPER_API_KEY= # Optional — for reliable web search ($5/mo at serper.dev)```+**Email verification matters:** Harvey learns each company's email *pattern* and verifies ONE candidate rather than guessing (raw SMTP probing no longer works against Google Workspace / Microsoft 365). Add any one of Reoon / ZeroBounce / Hunter to get verified addresses. Without a verifier key, found emails are marked `guess` and are **never sent** — so at least one key is strongly recommended before running campaigns.+After getting the Instantly API key, test it:```bashsource .venv/bin/activate && python3 -c "@@ -162,7 +166,7 @@ Users will come back with questions and tasks. Common ones:- **Skills** (`skills/`): Markdown knowledge files injected into agent prompts### Sub-Agents-- **Scout**: Python does all web searching (DuckDuckGo → Bing → Google → Serper API). Claude only scores/personalizes found data.+- **Scout**: Python does all web searching (DuckDuckGo → Bing → Google → Serper API) and email resolution (pattern-first: cache → scraped mailto → Hunter domain search → default, then verify one candidate via Reoon/ZeroBounce/Hunter/SMTP; catch-alls flagged `risky`). Claude only scores/personalizes found data.- **Writer**: Generates 3-email sequences (Email 1 < 75 words, Email 2 < 75, Email 3 < 40). Strict ban list on AI patterns.- **Sender**: Deploys to Instantly API. Enforces daily send limits.- **Handler**: Classifies reply intent, advances conversation stage, auto-responds. Has reply deduplication.diff --git a/harvey/agents/scout.py b/harvey/agents/scout.pyindex 1c5c4cc..e922f98 100644--- a/harvey/agents/scout.py+++ b/harvey/agents/scout.py@@ -501,9 +501,9 @@ class Scout:)email = ""- email_verified = False+ email_status = ""if domain and first_name and last_name:- email, email_verified = await self._resolve_email(+ email, email_status = await self._resolve_email(first_name, last_name, domain)@@ -511,7 +511,8 @@ class Scout:first_name=first_name,last_name=last_name,email=email,- email_verified=email_verified,+ email_status=email_status,+ email_verified=(email_status == "verified"),linkedin_url=li_url,company=company_name,company_id=company_id,@@ -670,7 +671,7 @@ class Scout:if not first_name or not last_name:continue- email, email_verified = await self._resolve_email(+ email, email_status = await self._resolve_email(first_name, last_name, domain)@@ -678,7 +679,8 @@ class Scout:first_name=first_name,last_name=last_name,email=email,- email_verified=email_verified,+ email_status=email_status,+ email_verified=(email_status == "verified"),company=company.get("name") or self._domain_to_name(domain),company_id=company_id,title=title,@@ -919,37 +921,25 @@ class Scout: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.+ ) -> tuple[str, str]:+ """Find an email and return (address, honest_status).- ``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.+ Status is one of verified / risky / guess / invalid — the pipeline+ never reports a mere pattern guess as verified (that old bug bounced+ mail and burned domains). Passes env (verifier keys) and state (the+ pattern cache) so the domain's pattern is learned once and reused."""if not (first_name and last_name and domain):- return "", False+ return "", "invalid"try:- verified = await find_email(first_name, last_name, domain, verify=True)+ result = await find_email(+ first_name, last_name, domain,+ verify=True, env=self.env, state=self.state,+ )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_mx+ return "", "invalid"+ return result.email, result.statusasync def _score_contacts(self, contacts: list[Prospect]) -> list[Prospect]:"""Use Claude to score and add personalization notes to found contacts.@@ -1049,11 +1039,13 @@ Respond ONLY with the JSON array."""):score += 10- # Deliverability: a verified email is worth more.- if contact.email_verified:- score += 5+ # Deliverability: reward confidence in the address.+ if contact.email_status == "verified":+ score += 8+ elif contact.email_status == "risky":+ score += 3elif contact.email:- score += 2+ score += 1return max(1, min(100, score))@@ -1148,6 +1140,10 @@ Respond ONLY with the JSON array."""if soup is None:continue+ # Harvest any real address on the page — one confirmed email+ # reveals the domain's whole pattern (learned once, reused free).+ await self._learn_pattern_from_page(soup, resp.text, domain)+try:cards = soup.select(".team-member, .person, .staff, [class*='team'], "@@ -1202,6 +1198,63 @@ Respond ONLY with the JSON array."""unique.append(m)return unique+ async def _learn_pattern_from_page(self, soup, html: str, domain: str):+ """Find a real on-domain email on a page and cache the derived pattern.++ Prefers mailto: links (cleanest), falls back to inline addresses.+ Skips role addresses (info@, sales@) — they don't reveal a+ person-name pattern.+ """+ domain = domain.lower()+ role_locals = {+ "info", "sales", "support", "hello", "contact", "admin",+ "team", "help", "office", "press", "media", "careers", "jobs",+ "hr", "billing", "noreply", "no-reply", "marketing",+ }+ found = []+ try:+ for a in soup.find_all("a", href=True):+ href = self._attr_str(a.get("href"))+ if href.lower().startswith("mailto:"):+ addr = href[7:].split("?")[0].strip().lower()+ if "@" in addr:+ found.append(addr)+ except Exception:+ pass+ if not found:+ try:+ found = [+ m.lower() for m in re.findall(+ r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}",+ html[:20000],+ )+ ]+ except Exception:+ found = []++ for addr in found:+ local, _, adomain = addr.partition("@")+ if adomain != domain or local in role_locals or "." not in local:+ continue+ # Looks like first.last@ — infer and cache the pattern.+ from harvey.integrations.email_finder import (+ infer_pattern_from_email,+ )+ parts = local.replace("_", ".").replace("-", ".").split(".")+ if len(parts) < 2:+ continue+ pattern = infer_pattern_from_email(addr, parts[0], parts[-1])+ if pattern:+ try:+ await self.state.save_email_pattern(+ domain, pattern=pattern, source="scraped_mailto",+ confidence=0.85,+ )+ logger.debug(f"Scout: learned pattern {pattern} for {domain}")+ except Exception as e:+ logger.debug(f"save_email_pattern failed: {e}")+ return+async def _guess_domain(self, company_name: str) -> str:"""Guess a company's domain from its name and confirm it resolves."""name = company_name.lower().strip()diff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex c78f105..39634a9 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -17,6 +17,12 @@ EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")# we never re-send to someone already contacted, replied, opted out, or lost.SENDABLE_STATUSES = {"new", "queued"}+# Email confidence levels safe to send to. "verified" only by default;+# "risky" (catch-all domains) is opt-in via config. Never send to a "guess"+# or "invalid" address — that bounces and burns the sending domain.+SENDABLE_EMAIL_STATUSES = {"verified"}+SENDABLE_EMAIL_STATUSES_WITH_RISKY = {"verified", "risky"}+class Sender:def __init__(@@ -125,9 +131,15 @@ class Sender:logger.error(f"Sender: Failed to set emails for campaign {campaign_id}")return- # 3. Add leads — validated, deduped, and only never-contacted prospects+ # 3. Add leads — validated, deduped, never-contacted, deliverable-only+ allow_risky = getattr(self.config.channels.email, "send_to_risky", False)+ sendable_email = (+ SENDABLE_EMAIL_STATUSES_WITH_RISKY if allow_risky+ else SENDABLE_EMAIL_STATUSES+ )prospects = []seen_emails: set[str] = set()+ skipped_unverified = 0for prospect_id in campaign.prospect_ids:prospect = await self.state.get_prospect(prospect_id)if not prospect or not prospect.email:@@ -144,9 +156,24 @@ class Sender:f"Sender: Skipping {email} (status '{prospect.status}' is not sendable).")continue+ # Deliverability gate: never send to unverified/guessed addresses —+ # bounces are the fastest way to torch a sending domain.+ if (prospect.email_status or "guess") not in sendable_email:+ skipped_unverified += 1+ logger.debug(+ f"Sender: Skipping {email} (email_status "+ f"'{prospect.email_status or 'guess'}' not deliverable)."+ )+ continueseen_emails.add(email)prospects.append(prospect)+ if skipped_unverified:+ logger.info(+ f"Sender: Held back {skipped_unverified} prospect(s) with "+ f"unverified emails from '{campaign.name}'."+ )+if not prospects:# Retry path: leads were already staged and marked 'contacted'# on a previous cycle but activation failed. Just activate.diff --git a/harvey/agents/writer.py b/harvey/agents/writer.pyindex 5bfe989..77955f8 100644--- a/harvey/agents/writer.py+++ b/harvey/agents/writer.py@@ -30,10 +30,18 @@ class Writer:logger.info("Writer: No new prospects to write for.")return- # Filter to only those with emails- prospects_with_email = [p for p in new_prospects if p.email]+ # Only write for prospects we can actually deliver to. Guessed and+ # invalid addresses are skipped so we don't spend Claude calls (or+ # sending reputation) on mail that will bounce.+ deliverable = {"verified", "risky"}+ prospects_with_email = [+ p for p in new_prospects+ if p.email and (p.email_status or "guess") in deliverable+ ]if not prospects_with_email:- logger.info("Writer: No prospects with verified emails.")+ logger.info(+ "Writer: No prospects with deliverable (verified/risky) emails yet."+ )return# Batch prospects into campaign groups (by industry/title for relevance)diff --git a/harvey/config.py b/harvey/config.pyindex 806612e..e9c437b 100644--- a/harvey/config.py+++ b/harvey/config.py@@ -62,6 +62,10 @@ class EmailChannelConfig(BaseModel):enabled: bool = Trueprovider: str = "instantly"max_daily_sends: int = 50+ # When True, also send to catch-all ("risky") domains, not just verified+ # mailboxes. Off by default — catch-alls accept everything, so a bad+ # guess still bounces.+ send_to_risky: bool = False@field_validator("max_daily_sends")@classmethod@@ -144,6 +148,8 @@ class EnvConfig(BaseModel):linkedin_password: str = ""hunter_api_key: str = ""serper_api_key: str = ""+ reoon_api_key: str = ""+ zerobounce_api_key: str = ""def _format_validation_error(e: ValidationError) -> str:@@ -205,6 +211,8 @@ def load_env() -> EnvConfig: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(),+ reoon_api_key=os.getenv("REOON_API_KEY", "").strip(),+ zerobounce_api_key=os.getenv("ZEROBOUNCE_API_KEY", "").strip(),)if not env.instantly_api_key:logger.warning(diff --git a/harvey/dashboard.py b/harvey/dashboard.pyindex b7239e2..74b3021 100644--- a/harvey/dashboard.py+++ b/harvey/dashboard.py@@ -965,6 +965,11 @@ DASHBOARD_HTML = r"""<!DOCTYPE html>tbody tr { transition: background .1s; }tbody tr:hover td { background: rgba(255,255,255,0.02); }.verified { color: var(--accent); }+ .email-tag { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; padding: 1px 6px; border-radius: 4px; margin-left: 6px; }+ .email-tag.verified { color: var(--accent); background: var(--accent-soft); }+ .email-tag.risky { color: var(--amber); background: rgba(229,181,103,0.12); }+ .email-tag.guess { color: var(--text-3); background: rgba(255,255,255,0.05); }+ .email-tag.invalid { color: var(--red); background: rgba(224,108,117,0.12); }.muted { color: var(--text-3); }.badge {@@ -1599,6 +1604,15 @@ function fmtTokens(n) {function fmtCost(v) { return '$' + (v || 0).toFixed(2); }+function emailTag(p) {+ if (!p.email) return '';+ // Fall back to the legacy boolean for rows predating email_status.+ const status = p.email_status || (p.email_verified ? 'verified' : 'guess');+ const labels = {verified: 'verified', risky: 'catch-all', guess: 'guess', invalid: 'invalid'};+ if (!labels[status]) return '';+ return ' <span class="email-tag ' + status + '">' + labels[status] + '</span>';+}+async function loadUsage() {const data = await api('/api/usage');const statsEl = document.getElementById('usage-stats');@@ -1734,7 +1748,7 @@ async function showCompanyContacts(index) {} else {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 ? ' <span class="verified">✓</span>' : '';+ const emailIcon = emailTag(p);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>' +@@ -1780,7 +1794,7 @@ async function loadProspects() {}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 emailV = p.email ? (escHtml(p.email) + emailTag(p)) : '';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>' +diff --git a/harvey/integrations/email_finder.py b/harvey/integrations/email_finder.pyindex a29c085..d4a91ff 100644--- a/harvey/integrations/email_finder.py+++ b/harvey/integrations/email_finder.py@@ -1,9 +1,22 @@-"""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.+"""Email discovery — pattern-first, verify-once, honest about confidence.++Raw SMTP probing is largely dead against Google Workspace and Microsoft+365 (which host most B2B mail): they tarpit probers or accept every+recipient and bounce later. So instead of brute-forcing every name+permutation, this pipeline:++1. Classifies the domain by its MX host (google / microsoft / gateway / other).+2. Derives the domain's email PATTERN once — from cache, then Hunter's+ free domain-search, then known addresses scraped off the site, else a+ sensible default — collapsing N guesses to one candidate.+3. Verifies that single candidate through the best available channel for+ the domain type: a real-verdict API (Reoon, ZeroBounce for the big+ providers), Hunter, or SMTP for small self-hosted servers.+4. Detects catch-all domains and buckets them as ``risky`` instead of+ pretending they're verified.++Every result carries an honest status: verified / risky / guess / invalid.+Only ``verified`` (and optionally ``risky``) should ever be emailed."""import asyncio@@ -11,6 +24,7 @@ import loggingimport osimport randomimport re+from dataclasses import dataclassfrom typing import Optionalimport dns.resolver@@ -19,16 +33,47 @@ import httpxlogger = logging.getLogger("harvey.email_finder")-# Cache MX records per domain to avoid repeated lookups.-# Failed lookups are cached as None so we don't hammer DNS.+# Cache MX host + type per domain to avoid repeated lookups._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+API_TIMEOUT = httpx.Timeout(connect=10.0, read=20.0, write=10.0, pool=10.0)++# Named email-format patterns → builder. {f}=first, {l}=last, {fi}=first initial,+# {li}=last initial. Ordered by real-world prevalence for the default fallback.+PATTERN_BUILDERS = {+ "{f}.{l}": lambda f, l: f"{f}.{l}",+ "{f}{l}": lambda f, l: f"{f}{l}",+ "{fi}{l}": lambda f, l: f"{f[0]}{l}",+ "{f}": lambda f, l: f"{f}",+ "{fi}.{l}": lambda f, l: f"{f[0]}.{l}",+ "{f}_{l}": lambda f, l: f"{f}_{l}",+ "{l}": lambda f, l: f"{l}",+ "{l}.{f}": lambda f, l: f"{l}.{f}",+ "{f}-{l}": lambda f, l: f"{f}-{l}",+ "{l}{fi}": lambda f, l: f"{l}{f[0]}",+}+DEFAULT_PATTERN = "{f}.{l}"+++@dataclass+class EmailResult:+ """Outcome of an email lookup. status is the source of truth."""+ email: str+ status: str # verified / risky / guess / invalid+ pattern: str = ""+ mx_type: str = ""++ @property+ def verified(self) -> bool:+ return self.status == "verified"++ @property+ def sendable(self) -> bool:+ """Safe to send cold: confirmed mailbox only (risky is opt-in elsewhere)."""+ return self.status == "verified"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]@@ -37,54 +82,68 @@ def _clean_domain(domain: str) -> str:return domain-def generate_patterns(first_name: str, last_name: str, domain: str) -> list[str]:- """Generate common email patterns for a person at a domain."""- first = (first_name or "").lower().strip()- last = (last_name or "").lower().strip()- domain = _clean_domain(domain)+def _clean_name_part(value: str) -> str:+ return re.sub(r"[^a-z]", "", (value or "").lower())- # 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)+def build_email(pattern: str, first: str, last: str, domain: str) -> str:+ """Render a named pattern into an address, or '' if it can't be built."""+ first = _clean_name_part(first)+ last = _clean_name_part(last)+ domain = _clean_domain(domain)if not first or not last or not domain:- return []-- patterns = [- f"{first}@{domain}",- f"{first}.{last}@{domain}",- f"{first}{last}@{domain}",- f"{first[0]}{last}@{domain}",- f"{first}{last[0]}@{domain}",- f"{first[0]}.{last}@{domain}",- f"{last}.{first}@{domain}",- f"{last}@{domain}",- f"{first}_{last}@{domain}",- f"{first}-{last}@{domain}",- ]- # Dedupe while preserving order (short names can collide).- return list(dict.fromkeys(patterns))+ return ""+ builder = PATTERN_BUILDERS.get(pattern)+ if not builder:+ return ""+ try:+ local = builder(first, last)+ except IndexError:+ return ""+ return f"{local}@{domain}" if local else ""+++def generate_patterns(first_name: str, last_name: str, domain: str) -> list[str]:+ """All candidate addresses for a person, most-likely first (deduped)."""+ out = []+ for pattern in PATTERN_BUILDERS:+ email = build_email(pattern, first_name, last_name, domain)+ if email:+ out.append(email)+ return list(dict.fromkeys(out))+++# ── MX classification ──++def classify_mx(mx_host: str) -> str:+ """Bucket a domain by its mail host — decides the verification strategy."""+ if not mx_host:+ return "none"+ h = mx_host.lower()+ if "google" in h or "googlemail" in h or "aspmx.l" in h:+ return "google"+ if "outlook" in h or "protection.outlook" in h or "microsoft" in h:+ return "microsoft"+ if any(g in h for g in ("pphosted", "mimecast", "barracuda", "proofpoint",+ "messagelabs", "cisco", "fortinet", "trendmicro")):+ return "gateway"+ return "other"async def get_mx_host(domain: str) -> Optional[str]:- """Get the primary MX host for a domain."""+ """Primary MX host for a domain (cached; None on failure)."""domain = _clean_domain(domain)if not domain:return Noneif domain in _mx_cache:return _mx_cache[domain]-try:loop = asyncio.get_event_loop()answers = await loop.run_in_executor(None, lambda: dns.resolver.resolve(domain, "MX"))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_host = str(records[0].exchange).rstrip(".") if records else None_mx_cache[domain] = mx_host or Nonereturn _mx_cache[domain]except Exception as e:@@ -93,43 +152,221 @@ async def get_mx_host(domain: str) -> Optional[str]:return None-async def verify_email_smtp(email: str) -> bool:- """Verify an email exists via SMTP RCPT TO check.+# ── Pattern derivation ──++def infer_pattern_from_email(email: str, first: str, last: str) -> Optional[str]:+ """Given one known address, work out which named pattern produced it."""+ email = (email or "").strip().lower()+ if "@" not in email:+ return None+ local = email.split("@", 1)[0]+ first = _clean_name_part(first)+ last = _clean_name_part(last)+ if not first or not last:+ return None+ for pattern, builder in PATTERN_BUILDERS.items():+ try:+ if builder(first, last) == local:+ return pattern+ except IndexError:+ continue+ return None+++async def _hunter_domain_pattern(domain: str, api_key: str) -> Optional[tuple[str, float]]:+ """Hunter's free domain-search returns the org's dominant email pattern.- Note: Many servers don't support this (catch-all domains, etc.)- so a failed check doesn't guarantee the email is invalid.- A successful check is a strong signal though.+ Hunter formats it with {first}/{last}/{f} tokens; translate to ours.+ Returns (named_pattern, confidence 0-1) or None.+ """+ try:+ async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:+ resp = await client.get(+ "https://api.hunter.io/v2/domain-search",+ params={"domain": domain, "api_key": api_key, "limit": 1},+ )+ except httpx.HTTPError as e:+ logger.debug(f"Hunter domain-search failed for {domain}: {e}")+ return None+ if resp.status_code != 200:+ return None+ try:+ data = (resp.json() or {}).get("data") or {}+ except ValueError:+ return None++ hunter_pattern = data.get("pattern") or ""+ translated = _translate_hunter_pattern(hunter_pattern)+ if translated:+ # Hunter's presence of a pattern is a strong signal; scale by how+ # many known emails back it (capped).+ n = len(data.get("emails") or [])+ confidence = min(0.7 + 0.05 * n, 0.95)+ return translated, confidence+ return None+++def _translate_hunter_pattern(hunter_pattern: str) -> Optional[str]:+ """Map Hunter's {first}.{last}-style tokens to our named patterns."""+ if not hunter_pattern:+ return None+ p = hunter_pattern.lower().strip()+ mapping = {+ "{first}.{last}": "{f}.{l}",+ "{first}{last}": "{f}{l}",+ "{f}{last}": "{fi}{l}",+ "{first}": "{f}",+ "{f}.{last}": "{fi}.{l}",+ "{first}_{last}": "{f}_{l}",+ "{last}": "{l}",+ "{last}.{first}": "{l}.{f}",+ "{first}-{last}": "{f}-{l}",+ "{last}{f}": "{l}{fi}",+ }+ return mapping.get(p)+++def _hunter_api_key() -> str:+ return os.getenv("HUNTER_API_KEY", "").strip()+++async def derive_pattern(+ domain: str,+ known_emails: Optional[list[tuple[str, str, str]]] = None,+ state=None,+) -> tuple[str, str, float]:+ """Determine a domain's email pattern. Returns (pattern, source, confidence).++ Order: DB cache → a known address for this domain (scraped mailto,+ GitHub, etc.) → Hunter domain-search → default. This is the step that+ collapses six guesses to one and is where free tiers stretch furthest.+ """+ domain = _clean_domain(domain)++ if state is not None:+ try:+ cached = await state.get_email_pattern(domain)+ if cached and cached.get("pattern"):+ return cached["pattern"], cached.get("source", "cache"), cached.get("confidence", 0.6)+ except Exception as e:+ logger.debug(f"Pattern cache read failed for {domain}: {e}")++ # A confirmed address for this domain reveals the pattern for free.+ for email, first, last in known_emails or []:+ if email.split("@")[-1].lower() == domain:+ inferred = infer_pattern_from_email(email, first, last)+ if inferred:+ return inferred, "known_email", 0.9++ key = _hunter_api_key()+ if key:+ result = await _hunter_domain_pattern(domain, key)+ if result:+ return result[0], "hunter_domain_search", result[1]++ return DEFAULT_PATTERN, "default", 0.3+++# ── Verification channels ──++async def verify_reoon(email: str, api_key: str) -> Optional[dict]:+ """Reoon email-verifier — generous free tier, good catch-all flagging.++ Returns {'status': ..., 'catch_all': bool} or None if unavailable.+ Reoon 'status' values: valid / invalid / disabled / catch_all / unknown.+ """+ try:+ async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:+ resp = await client.get(+ "https://emailverifier.reoon.com/api/v1/verify",+ params={"email": email, "key": api_key, "mode": "power"},+ )+ except httpx.HTTPError as e:+ logger.debug(f"Reoon request failed for {email}: {e}")+ return None+ if resp.status_code != 200:+ return None+ try:+ data = resp.json()+ except ValueError:+ return None+ if not isinstance(data, dict):+ return None+ status = str(data.get("status") or "").lower()+ is_catch_all = bool(data.get("is_catch_all") or status == "catch_all")+ return {"status": status, "catch_all": is_catch_all}+++async def verify_zerobounce(email: str, api_key: str) -> Optional[dict]:+ """ZeroBounce — its 2026 engine is the reliable one for M365/Workspace catch-alls."""+ try:+ async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:+ resp = await client.get(+ "https://api.zerobounce.net/v2/validate",+ params={"email": email, "api_key": api_key},+ )+ except httpx.HTTPError as e:+ logger.debug(f"ZeroBounce request failed for {email}: {e}")+ return None+ if resp.status_code != 200:+ return None+ try:+ data = resp.json()+ except ValueError:+ return None+ if not isinstance(data, dict):+ return None+ status = str(data.get("status") or "").lower()+ sub = str(data.get("sub_status") or "").lower()+ return {"status": status, "catch_all": sub == "catch-all" or status == "catch-all"}+++async def verify_hunter(email: str, api_key: str) -> Optional[dict]:+ try:+ async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:+ resp = await client.get(+ "https://api.hunter.io/v2/email-verifier",+ params={"email": email, "api_key": api_key},+ )+ except httpx.HTTPError as e:+ logger.debug(f"Hunter verify failed for {email}: {e}")+ return None+ if resp.status_code != 200:+ return None+ try:+ data = (resp.json() or {}).get("data") or {}+ except ValueError:+ return None+ status = str(data.get("status") or data.get("result") or "").lower()+ return {"status": status, "catch_all": bool(data.get("accept_all"))}+++async def verify_email_smtp(email: str) -> Optional[bool]:+ """SMTP RCPT check — only trustworthy for small, self-hosted mail servers.++ Returns True (accepted), False (rejected), or None (couldn't tell).+ Port 25 is blocked on most cloud hosts, so this frequently returns None."""if "@" not in email:return Falsedomain = email.rsplit("@", 1)[1]mx_host = await get_mx_host(domain)if not mx_host:- return False-+ return Nonesmtp = aiosmtplib.SMTP(hostname=mx_host, port=25, timeout=10)try:await smtp.connect()await smtp.ehlo()-- # Try VRFY first- try:- code, _ = await smtp.vrfy(email)- if code == 250:- return True- except Exception:- pass # VRFY often disabled-- # Fall back to MAIL FROM + RCPT TOawait smtp.mail("[email protected]")- code, message = await smtp.rcpt(email)-- # 250 = accepted, 550 = rejected- return code == 250-+ code, _ = await smtp.rcpt(email)+ if code == 250:+ return True+ if code in (550, 551, 553):+ return False+ return Noneexcept Exception as e:logger.debug(f"SMTP verification failed for {email}: {e}")- return False+ return Nonefinally:try:await smtp.quit()@@ -137,146 +374,159 @@ async def verify_email_smtp(email: str) -> bool: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 detect_catch_all(domain: str) -> Optional[bool]:+ """Probe a definitely-fake address; if accepted, the domain is catch-all.+ Only works where SMTP probing works at all (small hosts). Returns None+ when we can't tell.+ """+ fake = f"zz-no-such-user-{random.randint(10000, 99999)}@{_clean_domain(domain)}"+ result = await verify_email_smtp(fake)+ if result is True:+ return True # accepted a fake address → catch-all+ if result is False:+ return False # rejected a fake address → not catch-all+ return None-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 _status_from_verdict(verdict: dict) -> Optional[str]:+ """Map a provider verdict dict to our status, or None if inconclusive."""+ if verdict.get("catch_all"):+ return "risky"+ status = verdict.get("status", "")+ if status in ("valid", "deliverable"):+ return "verified"+ if status in ("invalid", "undeliverable", "disabled"):+ return "invalid"+ if status in ("catch_all", "catch-all", "accept_all"):+ return "risky"+ return None # unknown / risky-unknown — inconclusive- 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 None+async def _verify_candidate(email: str, mx_type: str, env) -> tuple[Optional[str], bool]:+ """Run the best available verifier for this domain type.+ Returns (status_or_None, catch_all_seen). Order is chosen so scarce+ paid-ish credits are spent only where they actually resolve the domain.+ """+ reoon_key = getattr(env, "reoon_api_key", "") if env else ""+ zerobounce_key = getattr(env, "zerobounce_api_key", "") if env else ""+ hunter_key = _hunter_api_key()++ catch_all_seen = False++ # Big providers: ZeroBounce first (its engine cracks their catch-alls),+ # then Reoon, then Hunter. SMTP is useless/misleading here.+ if mx_type in ("google", "microsoft", "gateway"):+ channels = []+ if zerobounce_key:+ channels.append(lambda: verify_zerobounce(email, zerobounce_key))+ if reoon_key:+ channels.append(lambda: verify_reoon(email, reoon_key))+ if hunter_key:+ channels.append(lambda: verify_hunter(email, hunter_key))+ for channel in channels:+ verdict = await channel()+ if verdict is None:+ continue+ if verdict.get("catch_all"):+ catch_all_seen = True+ status = _status_from_verdict(verdict)+ if status is not None:+ return status, catch_all_seen+ return None, catch_all_seen++ # Small / self-hosted: Reoon → SMTP (still works here) → Hunter.+ if reoon_key:+ verdict = await verify_reoon(email, reoon_key)+ if verdict:+ if verdict.get("catch_all"):+ catch_all_seen = True+ status = _status_from_verdict(verdict)+ if status is not None:+ return status, catch_all_seen++ smtp = await verify_email_smtp(email)+ if smtp is True:+ # Confirm it's not just a catch-all before trusting "verified".+ if await detect_catch_all(email.split("@")[1]) is True:+ return "risky", True+ return "verified", catch_all_seen+ if smtp is False:+ return "invalid", catch_all_seen++ if hunter_key:+ verdict = await verify_hunter(email, hunter_key)+ if verdict:+ if verdict.get("catch_all"):+ catch_all_seen = True+ status = _status_from_verdict(verdict)+ if status is not None:+ return status, catch_all_seen++ return None, catch_all_seen+++# ── Top-level entry point ──async def find_email(first_name: str,last_name: str,domain: str,verify: bool = True,-) -> Optional[str]:- """Try to find a valid email for a person at a company domain.-- 1. Generate common email patterns- 2. Check MX records exist for domain- 3. Verify each pattern (Hunter if configured, else SMTP)- 4. Return first verified email, or best guess if verification unavailable+ env=None,+ state=None,+ known_emails: Optional[list[tuple[str, str, str]]] = None,+) -> EmailResult:+ """Find and honestly grade one email for a person at a company.++ Returns an EmailResult whose ``status`` is verified / risky / guess /+ invalid. When ``verify`` is False (or no verifier is configured), the+ best pattern guess is returned as ``guess`` — never as verified."""- 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}"+ domain = _clean_domain(domain)+ if not (first_name and last_name and domain):+ return EmailResult(email="", status="invalid")- # First check if domain has MX records at all- mx_host = await get_mx_host(clean)+ mx_host = await get_mx_host(domain)if not mx_host:- logger.info(f"No MX records for {clean}. Returning best guess.")- return best_guess+ # No MX → cannot receive mail at all.+ guess = build_email(DEFAULT_PATTERN, first_name, last_name, domain)+ return EmailResult(email=guess, status="invalid", mx_type="none")- if not verify:- return best_guess+ mx_type = classify_mx(mx_host)- use_hunter = bool(_hunter_api_key())+ pattern, source, confidence = await derive_pattern(+ domain, known_emails=known_emails, state=state+ )+ candidate = build_email(pattern, first_name, last_name, domain)+ if not candidate:+ candidate = build_email(DEFAULT_PATTERN, first_name, last_name, domain)+ pattern = DEFAULT_PATTERN- # Try to verify each pattern- for email in patterns:- logger.debug(f"Checking {email}...")+ if state is not None:try:- 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+ await state.save_email_pattern(+ domain, pattern=pattern, source=source,+ confidence=confidence, mx_type=mx_type,+ )except Exception as e:- logger.debug(f"Verification error for {email}: {e}")+ logger.debug(f"Pattern cache write failed for {domain}: {e}")++ if not verify:+ return EmailResult(email=candidate, status="guess", pattern=pattern, mx_type=mx_type)++ status, catch_all = await _verify_candidate(candidate, mx_type, env)++ if catch_all and state is not None:+ try:+ await state.save_email_pattern(domain, mx_type=mx_type, is_catch_all=1)+ except Exception:+ pass- # Rate limit between checks (jittered so probes don't look scripted)- await asyncio.sleep(random.uniform(0.8, 2.0))+ if status is None:+ # Verification couldn't decide — an honest guess, never "verified".+ status = "guess"- # If no verification worked, return the most common pattern- logger.info(f"No verified email found. Best guess: {best_guess}")- return best_guess+ logger.info(f"Email for {first_name} {last_name}@{domain}: {candidate} [{status}]")+ return EmailResult(email=candidate, status=status, pattern=pattern, mx_type=mx_type)diff --git a/harvey/models/prospect.py b/harvey/models/prospect.pyindex 4bf9e23..3aad1ef 100644--- a/harvey/models/prospect.py+++ b/harvey/models/prospect.py@@ -17,6 +17,8 @@ class Prospect(BaseModel):last_name: str = "" # required for a valid contactemail: str = ""email_verified: bool = False+ # verified / risky (catch-all) / guess (never auto-sent) / invalid / ""+ email_status: str = ""phone: str = ""phone_verified: bool = Falselinkedin_url: str = ""diff --git a/harvey/state.py b/harvey/state.pyindex 93bbc50..e670c81 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -218,6 +218,30 @@ MIGRATIONS: list[str] = [CREATE UNIQUE INDEX IF NOT EXISTS uq_usage_events_requestON usage_events(request_key) WHERE request_key != '';""",+ # ── v4: honest email statuses + per-domain pattern cache ──+ """+ -- verified: a provider confirmed the mailbox exists+ -- risky: catch-all / accept-all domain — sendable only in low volume+ -- guess: pattern guess, never verified — never auto-sent+ -- invalid: provider said undeliverable+ ALTER TABLE prospects ADD COLUMN email_status TEXT DEFAULT '';++ -- Backfill: the old email_verified flag over-reported (pattern guesses+ -- at any MX-bearing domain were marked verified), so every existing+ -- address is downgraded to an honest 'guess' and must re-verify.+ UPDATE prospects SET email_status = 'guess', email_verified = 0+ WHERE email != '';++ CREATE TABLE IF NOT EXISTS email_patterns (+ domain TEXT PRIMARY KEY,+ pattern TEXT DEFAULT '',+ source TEXT DEFAULT '',+ confidence REAL DEFAULT 0.0,+ mx_type TEXT DEFAULT '',+ is_catch_all INTEGER DEFAULT -1,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );+ """,]# Column whitelists for dynamic UPDATEs (prevents SQL injection via kwargs).@@ -342,6 +366,7 @@ class StateManager:d = dict(row)d["email_verified"] = bool(d.get("email_verified", 0))d["phone_verified"] = bool(d.get("phone_verified", 0))+ d["email_status"] = d.get("email_status") or ""return Prospect(**d)async def add_prospect(self, prospect: Prospect) -> str:@@ -355,15 +380,16 @@ class StateManager: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,- department, source, source_url, status, score,+ email_status, phone, phone_verified, linkedin_url, title,+ seniority, department, source, source_url, status, score,personalization_notes, company, industry, company_size,created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(prospect.id, prospect.company_id,prospect.first_name, prospect.last_name,prospect.email, int(prospect.email_verified),+ prospect.email_status,prospect.phone, int(prospect.phone_verified),prospect.linkedin_url, prospect.title,prospect.seniority, prospect.department,@@ -434,6 +460,77 @@ class StateManager:row = await cursor.fetchone()return self._prospect_from_row(row) if row else None+ async def update_prospect_email(+ self, prospect_id: str, email: str, email_status: str+ ):+ """Set a prospect's email + honesty status (verified/risky/guess/invalid)."""+ async with self._connect() as db:+ await db.execute(+ """UPDATE prospects+ SET email = ?, email_status = ?, email_verified = ?, updated_at = ?+ WHERE id = ?""",+ (+ _norm(email), email_status,+ 1 if email_status == "verified" else 0,+ _utcnow().isoformat(), prospect_id,+ ),+ )+ await db.commit()++ # ── Email pattern cache (per-domain) ──++ async def get_email_pattern(self, domain: str) -> dict | None:+ async with self._connect() as db:+ db.row_factory = aiosqlite.Row+ async with db.execute(+ "SELECT * FROM email_patterns WHERE domain = ?", (_norm(domain),)+ ) as cursor:+ row = await cursor.fetchone()+ return dict(row) if row else None++ async def save_email_pattern(+ self,+ domain: str,+ pattern: str = "",+ source: str = "",+ confidence: float = 0.0,+ mx_type: str = "",+ is_catch_all: int | None = None,+ ):+ """Upsert what we've learned about a domain's email conventions.++ Only overwrites the stored pattern when the new one has equal or+ higher confidence; mx_type/is_catch_all always refresh.+ """+ domain = _norm(domain)+ if not domain:+ return+ async with self._connect() as db:+ await db.execute(+ """INSERT INTO email_patterns+ (domain, pattern, source, confidence, mx_type, is_catch_all, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)+ ON CONFLICT(domain) DO UPDATE SET+ pattern = CASE WHEN excluded.confidence >= email_patterns.confidence+ AND excluded.pattern != ''+ THEN excluded.pattern ELSE email_patterns.pattern END,+ source = CASE WHEN excluded.confidence >= email_patterns.confidence+ AND excluded.pattern != ''+ THEN excluded.source ELSE email_patterns.source END,+ confidence = MAX(email_patterns.confidence, excluded.confidence),+ mx_type = CASE WHEN excluded.mx_type != ''+ THEN excluded.mx_type ELSE email_patterns.mx_type END,+ is_catch_all = CASE WHEN excluded.is_catch_all != -1+ THEN excluded.is_catch_all+ ELSE email_patterns.is_catch_all END,+ updated_at = CURRENT_TIMESTAMP""",+ (+ domain, pattern, source, float(confidence), mx_type,+ -1 if is_catch_all is None else int(is_catch_all),+ ),+ )+ await db.commit()+async def prospect_exists(self, email: str = "", linkedin_url: str = "",first_name: str = "", last_name: str = "", company: str = "",diff --git a/tests/test_email_finder.py b/tests/test_email_finder.pynew file mode 100644index 0000000..e2236d3--- /dev/null+++ b/tests/test_email_finder.py@@ -0,0 +1,221 @@+"""Tests for the pattern-first email pipeline."""++import os+import tempfile++import pytest+import pytest_asyncio++from harvey.state import StateManager+from harvey.integrations import email_finder as ef+from harvey.integrations.email_finder import (+ EmailResult,+ build_email,+ classify_mx,+ derive_pattern,+ find_email,+ generate_patterns,+ infer_pattern_from_email,+ _status_from_verdict,+ _translate_hunter_pattern,+)+++@pytest_asyncio.fixture+async def state():+ with tempfile.TemporaryDirectory() as tmpdir:+ sm = StateManager(os.path.join(tmpdir, "test.db"))+ await sm.init_db()+ yield sm+++class Env:+ def __init__(self, **kw):+ self.reoon_api_key = kw.get("reoon", "")+ self.zerobounce_api_key = kw.get("zerobounce", "")+++# ── pattern building / inference ──+++def test_build_email_patterns():+ assert build_email("{f}.{l}", "Jane", "Doe", "acme.com") == "[email protected]"+ assert build_email("{fi}{l}", "Jane", "Doe", "acme.com") == "[email protected]"+ assert build_email("{f}", "Jane", "Doe", "acme.com") == "[email protected]"+ assert build_email("{f}.{l}", "", "Doe", "acme.com") == ""+ assert build_email("nonexistent", "Jane", "Doe", "acme.com") == ""+++def test_generate_patterns_dedup_and_order():+ patterns = generate_patterns("Jane", "Doe", "acme.com")+ assert patterns[0] == "[email protected]" # most common first+ assert "[email protected]" in patterns+ assert len(patterns) == len(set(patterns))+++def test_infer_pattern_from_email():+ assert infer_pattern_from_email("[email protected]", "Jane", "Doe") == "{f}.{l}"+ assert infer_pattern_from_email("[email protected]", "Jane", "Doe") == "{fi}{l}"+ assert infer_pattern_from_email("[email protected]", "Jane", "Doe") == "{f}{l}"+ assert infer_pattern_from_email("[email protected]", "Jane", "Doe") is None+++def test_translate_hunter_pattern():+ assert _translate_hunter_pattern("{first}.{last}") == "{f}.{l}"+ assert _translate_hunter_pattern("{f}{last}") == "{fi}{l}"+ assert _translate_hunter_pattern("{unknown}") is None+++# ── MX classification ──+++def test_classify_mx():+ assert classify_mx("aspmx.l.google.com") == "google"+ assert classify_mx("acme-com.mail.protection.outlook.com") == "microsoft"+ assert classify_mx("mx.pphosted.com") == "gateway"+ assert classify_mx("mail.smallco.com") == "other"+ assert classify_mx("") == "none"+++# ── verdict → status mapping ──+++def test_status_from_verdict():+ assert _status_from_verdict({"status": "valid", "catch_all": False}) == "verified"+ assert _status_from_verdict({"status": "deliverable"}) == "verified"+ assert _status_from_verdict({"status": "invalid"}) == "invalid"+ # catch_all always wins, even over a "valid" status+ assert _status_from_verdict({"status": "valid", "catch_all": True}) == "risky"+ assert _status_from_verdict({"status": "unknown"}) is None+++# ── pattern derivation with cache + known emails ──+++async def test_derive_pattern_from_known_email(state):+ pattern, source, conf = await derive_pattern(+ "acme.com",+ known_emails=[("[email protected]", "John", "Smith")],+ state=state,+ )+ assert pattern == "{f}.{l}"+ assert source == "known_email"+ assert conf >= 0.9+++async def test_derive_pattern_uses_cache(state):+ await state.save_email_pattern(+ "acme.com", pattern="{fi}{l}", source="scraped_mailto", confidence=0.85+ )+ pattern, source, conf = await derive_pattern("acme.com", state=state)+ assert pattern == "{fi}{l}"+ assert source == "scraped_mailto"+++async def test_derive_pattern_default_no_signal(state, monkeypatch):+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")+ pattern, source, conf = await derive_pattern("unknown-co.com", state=state)+ assert pattern == "{f}.{l}"+ assert source == "default"+ assert conf < 0.5+++# ── find_email end-to-end (mocked network) ──+++async def test_find_email_no_mx_is_invalid(state, monkeypatch):+ async def no_mx(domain):+ return None+ monkeypatch.setattr(ef, "get_mx_host", no_mx)+ result = await find_email("Jane", "Doe", "acme.com", state=state)+ assert result.status == "invalid"+ assert result.mx_type == "none"+++async def test_find_email_verify_false_is_guess(state, monkeypatch):+ async def google_mx(domain):+ return "aspmx.l.google.com"+ monkeypatch.setattr(ef, "get_mx_host", google_mx)+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")++ result = await find_email("Jane", "Doe", "acme.com", verify=False, state=state)+ assert result.status == "guess"+ assert result.email == "[email protected]"+ assert result.mx_type == "google"+ # Pattern still cached even without verification+ cached = await state.get_email_pattern("acme.com")+ assert cached["mx_type"] == "google"+++async def test_find_email_verified_via_reoon(state, monkeypatch):+ async def google_mx(domain):+ return "aspmx.l.google.com"+ monkeypatch.setattr(ef, "get_mx_host", google_mx)+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")++ async def fake_reoon(email, key):+ return {"status": "valid", "catch_all": False}+ monkeypatch.setattr(ef, "verify_reoon", fake_reoon)++ result = await find_email(+ "Jane", "Doe", "acme.com", env=Env(reoon="k"), state=state+ )+ assert result.status == "verified"+ assert result.verified and result.sendable+++async def test_find_email_catch_all_is_risky(state, monkeypatch):+ async def ms_mx(domain):+ return "acme.mail.protection.outlook.com"+ monkeypatch.setattr(ef, "get_mx_host", ms_mx)+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")++ async def fake_zb(email, key):+ return {"status": "valid", "catch_all": True}+ monkeypatch.setattr(ef, "verify_zerobounce", fake_zb)++ result = await find_email(+ "Jane", "Doe", "acme.com", env=Env(zerobounce="k"), state=state+ )+ assert result.status == "risky"+ assert not result.sendable # verified-only by default+ # catch-all flag persisted+ cached = await state.get_email_pattern("acme.com")+ assert cached["is_catch_all"] == 1+++async def test_find_email_invalid_from_provider(state, monkeypatch):+ async def google_mx(domain):+ return "aspmx.l.google.com"+ monkeypatch.setattr(ef, "get_mx_host", google_mx)+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")++ async def fake_reoon(email, key):+ return {"status": "invalid", "catch_all": False}+ monkeypatch.setattr(ef, "verify_reoon", fake_reoon)++ result = await find_email(+ "Jane", "Doe", "acme.com", env=Env(reoon="k"), state=state+ )+ assert result.status == "invalid"+++async def test_find_email_inconclusive_is_guess_not_verified(state, monkeypatch):+ """The core bug fix: no verifier confirmation → 'guess', never 'verified'."""+ async def google_mx(domain):+ return "aspmx.l.google.com"+ monkeypatch.setattr(ef, "get_mx_host", google_mx)+ monkeypatch.setattr(ef, "_hunter_api_key", lambda: "")+ # No verifier keys configured at all → nothing can confirm.+ result = await find_email("Jane", "Doe", "acme.com", env=Env(), state=state)+ assert result.status == "guess"+ assert not result.verifieddiff --git a/tests/test_email_wiring.py b/tests/test_email_wiring.pynew file mode 100644index 0000000..9beaf0c--- /dev/null+++ b/tests/test_email_wiring.py@@ -0,0 +1,140 @@+"""Tests for email_status persistence and sender/scout wiring."""++import os+import tempfile++import pytest+import pytest_asyncio++from harvey.state import StateManager+from harvey.models.prospect import Prospect+++@pytest_asyncio.fixture+async def state():+ with tempfile.TemporaryDirectory() as tmpdir:+ sm = StateManager(os.path.join(tmpdir, "test.db"))+ await sm.init_db()+ yield sm+++async def test_prospect_email_status_roundtrips(state):+ p = Prospect(+ first_name="Jane", last_name="Doe", email="[email protected]",+ title="VP Sales", email_status="verified", email_verified=True,+ )+ pid = await state.add_prospect(p)+ fetched = await state.get_prospect(pid)+ assert fetched.email_status == "verified"+ assert fetched.email_verified is True+++async def test_update_prospect_email(state):+ p = Prospect(first_name="Jane", last_name="Doe", title="VP", email_status="guess")+ pid = await state.add_prospect(p)++ await state.update_prospect_email(pid, "[email protected]", "verified")+ fetched = await state.get_prospect(pid)+ assert fetched.email == "[email protected]"+ assert fetched.email_status == "verified"+ assert fetched.email_verified is True++ await state.update_prospect_email(pid, "[email protected]", "invalid")+ fetched = await state.get_prospect(pid)+ assert fetched.email_status == "invalid"+ assert fetched.email_verified is False+++async def test_save_email_pattern_keeps_highest_confidence(state):+ await state.save_email_pattern("acme.com", pattern="{f}.{l}", source="default", confidence=0.3)+ await state.save_email_pattern("acme.com", pattern="{fi}{l}", source="hunter", confidence=0.9)+ cached = await state.get_email_pattern("acme.com")+ assert cached["pattern"] == "{fi}{l}"+ assert cached["confidence"] == 0.9++ # A lower-confidence write must not clobber the better pattern+ await state.save_email_pattern("acme.com", pattern="{f}", source="default", confidence=0.2)+ cached = await state.get_email_pattern("acme.com")+ assert cached["pattern"] == "{fi}{l}"+++async def test_save_email_pattern_updates_catch_all_independently(state):+ await state.save_email_pattern("acme.com", pattern="{f}.{l}", confidence=0.6, mx_type="google")+ await state.save_email_pattern("acme.com", is_catch_all=1)+ cached = await state.get_email_pattern("acme.com")+ assert cached["is_catch_all"] == 1+ assert cached["pattern"] == "{f}.{l}" # unchanged+ assert cached["mx_type"] == "google"+++async def test_migration_downgrades_legacy_verified(state):+ """v4 migration must strip the old inflated verified flag to 'guess'."""+ # Simulate a pre-v4 row: email_verified=1 written directly+ import aiosqlite+ async with aiosqlite.connect(state.db_path) as db:+ await db.execute(+ "INSERT INTO prospects (id, first_name, last_name, email, "+ "email_verified, email_status, title, status) "+ "VALUES ('leg1','Old','Row','[email protected]',1,'guess','VP','new')"+ )+ await db.commit()+ p = await state.get_prospect("leg1")+ # Sender must not treat this as sendable+ assert p.email_status == "guess"+++# ── Sender deliverability gate ──+++class _Cfg:+ class channels:+ class email:+ enabled = True+ provider = "instantly"+ max_daily_sends = 50+ send_to_risky = False+++async def test_sender_only_sends_verified(state, monkeypatch):+ from harvey.agents.sender import Sender++ # Three prospects: verified, guess, risky+ ids = {}+ for name, status in [("Ver", "verified"), ("Gue", "guess"), ("Ris", "risky")]:+ p = Prospect(+ first_name=name, last_name="X", title="VP",+ email=f"{name.lower()}@acme.com", email_status=status,+ email_verified=(status == "verified"), status="new",+ )+ ids[status] = await state.add_prospect(p)++ class Env:+ instantly_api_key = "k"+ sender = Sender(brain=None, state=state, config=_Cfg(), env=Env())++ # Filter logic mirrors _deploy_campaign's lead selection.+ from harvey.agents.sender import (+ SENDABLE_EMAIL_STATUSES, SENDABLE_EMAIL_STATUSES_WITH_RISKY,+ )+ allowed = SENDABLE_EMAIL_STATUSES+ sendable = []+ for status, pid in ids.items():+ p = await state.get_prospect(pid)+ if p.email_status in allowed:+ sendable.append(p)+ assert len(sendable) == 1+ assert sendable[0].email_status == "verified"++ # With risky enabled, two become sendable+ allowed = SENDABLE_EMAIL_STATUSES_WITH_RISKY+ sendable = [+ await state.get_prospect(pid) for status, pid in ids.items()+ if (await state.get_prospect(pid)).email_status in allowed+ ]+ assert {p.email_status for p in sendable} == {"verified", "risky"}