Skip to content

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

Add Humanizer pass, company-inbox fallback, and fix Reoon verdicts

Ali Bedelf18749fce2ab
diff --git a/harvey/agents/handler.py b/harvey/agents/handler.py
index cff1ea9..8f2b168 100644
--- a/harvey/agents/handler.py
+++ b/harvey/agents/handler.py
@@ -12,6 +12,7 @@ from datetime import datetime, timezone
from harvey.brain import Brain, BrainUnavailable
from harvey.config import HarveyConfig, EnvConfig
+from harvey.humanize import humanize
from harvey.integrations.instantly import InstantlyClient
from harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_provider
from harvey.models.conversation import Conversation, Message
@@ -669,4 +670,5 @@ Write a reply that:"""
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 response
+ polished = await humanize(self.brain, [{"subject": "", "body": response}], agent="handler")
+ return polished[0]["body"]
diff --git a/harvey/agents/scout.py b/harvey/agents/scout.py
index e0fe194..d437d34 100644
--- a/harvey/agents/scout.py
+++ b/harvey/agents/scout.py
@@ -37,10 +37,10 @@ from bs4 import BeautifulSoup
from harvey.brain import Brain
from harvey.config import HarveyConfig, EnvConfig
-from harvey.integrations.email_finder import find_email
+from harvey.integrations.email_finder import find_email, verify_published_address
from harvey.integrations.linkedin import LinkedInAutomation
from harvey.models.company import Company
-from harvey.models.prospect import Prospect
+from harvey.models.prospect import COMPANY_INBOX_SOURCE, Prospect
from harvey.state import StateManager
logger = logging.getLogger("harvey.scout")
@@ -57,6 +57,18 @@ MAX_RETRIES = 3
BACKOFF_BASE = 1.5 # seconds; grows exponentially per attempt
MAX_RESULTS_PER_QUERY = 20
MAX_COMPANIES_PER_CYCLE = 10
+
+# Company-inbox fallback: pages that publish a general address, the
+# mailboxes most likely read by the owner (best first), and addresses that
+# never reach a decision-maker.
+INBOX_PAGES = ("/contact", "/contact-us")
+INBOX_PREFERRED = ("owner", "office", "info", "contact", "service", "hello",
+ "sales", "admin", "support")
+INBOX_SKIP_LOCALS = {
+ "noreply", "no-reply", "donotreply", "careers", "jobs", "hr", "billing",
+ "accounting", "invoices", "ap", "press", "media", "marketing", "privacy",
+ "webmaster", "abuse", "postmaster", "example", "email", "name", "your",
+}
MAX_PROSPECTS_PER_CYCLE = 25
# Hunter domain-searches per heartbeat. The monthly budget itself is shared
@@ -1446,8 +1458,92 @@ Respond ONLY with the JSON array."""
self._remember_prospect(prospect)
contacts.append(prospect)
+
+ if not contacts:
+ inbox = await self._company_inbox_prospect(
+ company_id, domain, company_name, industry, signal_note,
+ )
+ if inbox:
+ contacts.append(inbox)
return contacts
+ async def _company_inbox_prospect(
+ self, company_id: str, domain: str, company_name: str,
+ industry: str, signal_note: str = "",
+ ) -> Prospect | None:
+ """The company's own published inbox, when its site names nobody.
+
+ Small trade businesses rarely list a team, but most publish an
+ info@ or office@ address that the owner or office manager reads.
+ Only an address printed on the company's own site is used, never a
+ guessed one, and it is verified like any other before sending.
+ """
+ email = await self._find_inbox_address(domain)
+ if not email:
+ return None
+ try:
+ status = await verify_published_address(email, env=self.env)
+ except Exception as e:
+ logger.debug(f"Inbox verification failed for {email}: {e}")
+ status = "guess"
+ prospect = Prospect(
+ email=email,
+ email_status=status,
+ email_verified=(status == "verified"),
+ company=company_name,
+ company_id=company_id,
+ title="General inbox",
+ industry=industry,
+ source=COMPANY_INBOX_SOURCE,
+ source_url=f"https://{domain}",
+ personalization_notes=signal_note,
+ )
+ if not prospect.is_valid() or await self._is_duplicate_prospect(prospect):
+ return None
+ self._remember_prospect(prospect)
+ logger.info(f"Scout: No named owner at {domain}; using its published inbox {email} [{status}]")
+ return prospect
+
+ async def _find_inbox_address(self, domain: str) -> str:
+ """Best general address published on the company's homepage or contact page."""
+ base, home = await self._resolve_base_url(domain)
+ if not base:
+ return ""
+ domain = domain.lower().removeprefix("www.")
+ pages = [home] if home is not None else []
+ for path in INBOX_PAGES:
+ resp = await self._fetch(f"{base}{path}", timeout=SCRAPE_TIMEOUT, retries=1)
+ if resp is not None:
+ pages.append(resp)
+
+ found: list[str] = []
+ for resp in pages:
+ text = getattr(resp, "text", "") or ""
+ soup = self._safe_soup(text)
+ if soup is not None:
+ for a in soup.find_all("a", href=True):
+ href = self._attr_str(a.get("href"))
+ if href.lower().startswith("mailto:"):
+ found.append(href[7:].split("?")[0])
+ found += re.findall(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}", text[:50000])
+
+ candidates = []
+ for addr in found:
+ addr = addr.strip().lower()
+ local, _, adomain = addr.partition("@")
+ if adomain.removeprefix("www.") != domain or local in INBOX_SKIP_LOCALS:
+ continue
+ if addr not in candidates:
+ candidates.append(addr)
+ if not candidates:
+ return ""
+
+ def rank(addr: str) -> int:
+ local = addr.partition("@")[0]
+ return INBOX_PREFERRED.index(local) if local in INBOX_PREFERRED else len(INBOX_PREFERRED)
+
+ return min(candidates, key=rank)
+
# ── Strategy 4: Job boards — companies hiring for signal roles ──
async def _prospect_via_hiring_boards(self) -> int:
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index dc84410..75653ad 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -337,7 +337,8 @@ class Sender:
def _render(self, text: str, prospect) -> str:
"""Fill merge variables. The pre-send gate rejects any leftovers."""
replacements = {
- "first_name": prospect.first_name,
+ # A company inbox has no name; "there" keeps "Hi {{first_name}}," readable.
+ "first_name": prospect.first_name or ("there" if prospect.is_company_inbox else ""),
"last_name": prospect.last_name,
"company": prospect.company,
"title": prospect.title,
diff --git a/harvey/agents/writer.py b/harvey/agents/writer.py
index 2f9c059..637954f 100644
--- a/harvey/agents/writer.py
+++ b/harvey/agents/writer.py
@@ -15,6 +15,7 @@ from datetime import datetime, timezone
from harvey.brain import Brain
from harvey.config import HarveyConfig
+from harvey.humanize import humanize
from harvey.integrations.mail_provider import NATIVE_PROVIDERS
from harvey.models.campaign import Campaign, EmailStep
from harvey.state import StateManager
@@ -139,15 +140,21 @@ class Writer:
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
provider = self.config.channels.email.provider
- drafted = 0
+ pending = []
for prospect in prospects:
try:
draft = await self._write_personal_email(prospect)
except Exception as e:
logger.warning(f"Writer: personal draft failed for {prospect.email}: {e}")
continue
- if not draft:
- continue
+ if draft:
+ pending.append((prospect, draft))
+
+ # One Humanizer pass over the whole batch before anything is staged.
+ polished = await humanize(self.brain, [d for _, d in pending], agent="writer")
+
+ drafted = 0
+ for (prospect, _), draft in zip(pending, polished):
item_id = await self.state.add_outbox_item(
prospect_id=prospect.id,
campaign_id=campaign_id,
@@ -170,11 +177,19 @@ class Writer:
async def _write_personal_email(self, prospect) -> dict | None:
"""One grounded draft for one person. Facts in, one email out."""
- facts = [
- f"- Name: {prospect.full_name()}",
- f"- Title: {prospect.title}",
- f"- Company: {prospect.company}",
- ]
+ if prospect.is_company_inbox:
+ facts = [
+ f"- Name: unknown. This goes to the company's general inbox ({prospect.email}),"
+ " most likely read by the owner or the office manager. Use no first name;"
+ " open with 'Hi there' or address the company's team.",
+ f"- Company: {prospect.company}",
+ ]
+ else:
+ facts = [
+ f"- Name: {prospect.full_name()}",
+ f"- Title: {prospect.title}",
+ f"- Company: {prospect.company}",
+ ]
if prospect.industry:
facts.append(f"- Industry: {prospect.industry}")
@@ -249,6 +264,19 @@ Return ONLY JSON: {{"subject": "...", "body": "..."}}"""
+ (f" | Notes: {p.personalization_notes}" if p.personalization_notes else "")
for p in prospects[:5] # Show sample for context
)
+ inbox_batch = all(p.is_company_inbox for p in prospects)
+ if inbox_batch:
+ merge_rule = (
+ "- These go to each company's general inbox, so no names are known.\n"
+ " Use {{company}} as the merge variable in every email and NEVER\n"
+ " {{first_name}} or {{title}}. Greet with 'Hi there' or the company's team."
+ )
+ else:
+ merge_rule = (
+ "- Use {{first_name}}, {{company}}, {{title}} as merge variables — every email\n"
+ " must use at least one, and email 1 must reference something specific to\n"
+ " these prospects' industry or role (use the notes above)."
+ )
prompt = self.brain.load_prompt(
"writer",
@@ -284,9 +312,7 @@ Requirements:
- 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).
+{merge_rule}
- Never be pushy or salesy. Be consultative and value-driven.
- Subject lines: lowercase, 2-5 words.
- Follow every rule in the STRICT EMAIL RULES above. No exceptions.
@@ -302,7 +328,14 @@ Return ONLY a JSON array (no markdown fences, no commentary):
prompt, session_id="harvey-writer",
agent="writer", task="write_sequence",
)
- return self._parse_sequence(result)
+ steps = self._parse_sequence(result)
+ polished = await humanize(
+ self.brain, [{"subject": s.subject, "body": s.body} for s in steps],
+ agent="writer",
+ )
+ for step, draft in zip(steps, polished):
+ step.subject, step.body = draft["subject"], draft["body"]
+ return steps
def _parse_sequence(self, result) -> list[EmailStep]:
"""Robustly coerce LLM output into a validated EmailStep list.
@@ -361,7 +394,10 @@ Return ONLY a JSON array (no markdown fences, no commentary):
for prospect in prospects:
# Group by industry + rough title category
industry = prospect.industry or "general"
- key = f"{industry}-outreach"
+ # Inbox prospects get their own campaign: their templates can't
+ # greet anyone by name.
+ kind = "inbox-outreach" if prospect.is_company_inbox else "outreach"
+ key = f"{industry}-{kind}"
if key not in batches:
batches[key] = []
diff --git a/harvey/humanize.py b/harvey/humanize.py
new file mode 100644
index 0000000..d04deaa
--- /dev/null
+++ b/harvey/humanize.py
@@ -0,0 +1,115 @@
+"""Humanizer pass — rewrites drafts with the operator's installed Humanizer skill.
+
+Harvey's brain calls run with no tools and no skills (see brain.py), so a
+Claude Code skill can't be invoked directly. Instead the skill's
+instructions are read from the operator's skills folder and sent as a
+second, editing-only call over drafts that are already written.
+
+Fails open: no skill file, a failed call, or a rewrite that breaks a rule
+(lost merge variable, new em dash, much longer) keeps the original draft.
+Every draft still passes the deterministic pre-send gate afterwards.
+"""
+
+import json
+import logging
+import os
+import re
+from pathlib import Path
+
+logger = logging.getLogger("harvey.humanize")
+
+SKILL_PATH = Path(
+ os.getenv(
+ "HARVEY_HUMANIZER_SKILL",
+ str(Path.home() / ".claude" / "skills" / "humanizer" / "SKILL.md"),
+ )
+)
+MERGE_VAR = re.compile(r"\{\{\s*\w+\s*\}\}")
+MAX_GROWTH = 1.2 # a rewrite may not be more than 20% longer than the draft
+
+
+def load_skill(path: Path | None = None) -> str:
+ """The skill's instructions without its YAML frontmatter, or ""."""
+ try:
+ text = (path or SKILL_PATH).read_text(encoding="utf-8")
+ except OSError:
+ return ""
+ if text.startswith("---"):
+ end = text.find("\n---", 3)
+ if end != -1:
+ text = text[end + 4:]
+ return text.strip()
+
+
+def _acceptable(original: dict, rewrite) -> bool:
+ if not isinstance(rewrite, dict):
+ return False
+ body = str(rewrite.get("body") or "").strip()
+ subject = str(rewrite.get("subject") or "").strip()
+ if not body or (original.get("subject") and not subject):
+ return False
+ before = original.get("subject", "") + original["body"]
+ after = subject + body
+ if sorted(MERGE_VAR.findall(before)) != sorted(MERGE_VAR.findall(after)):
+ return False
+ if "—" in after and "—" not in before:
+ return False
+ return len(body.split()) <= len(original["body"].split()) * MAX_GROWTH + 2
+
+
+async def humanize(brain, drafts: list[dict], agent: str, path: Path | None = None) -> list[dict]:
+ """Return ``drafts`` ({"subject", "body"} dicts) rewritten by the skill.
+
+ One brain call for the whole list. Any draft whose rewrite fails a check
+ comes back unchanged, so the result always has the same length and order.
+ """
+ skill = load_skill(path)
+ if not drafts or not skill:
+ return drafts
+
+ payload = [{"subject": d.get("subject", ""), "body": d["body"]} for d in drafts]
+ prompt = f"""{skill}
+
+---
+
+Apply the Humanizer instructions above to the cold-email drafts below. They
+are short plain-text business emails, so return email text only.
+
+Hard limits on the rewrite, on top of the instructions above:
+- Same number of items, same order.
+- Keep every merge variable such as {{{{first_name}}}} or {{{{company}}}} exactly as written.
+- Add no fact, name, number or claim that is not already in the draft.
+- No em dashes, no bullets, no bold, no exclamation marks.
+- Do not make any email longer. Keep exactly one question per email.
+- Subjects stay lowercase, 2-5 words. An empty subject stays empty.
+
+Drafts:
+{json.dumps(payload, ensure_ascii=False, indent=2)}
+
+Return ONLY a JSON array: [{{"subject": "...", "body": "..."}}, ...]"""
+
+ try:
+ result = await brain.think_json(
+ prompt, session_id="harvey-humanizer", agent=agent, task="humanize",
+ )
+ except Exception as e:
+ logger.warning(f"Humanizer pass failed, keeping drafts: {e}")
+ return drafts
+ if not isinstance(result, list) or len(result) != len(drafts):
+ logger.warning("Humanizer pass returned the wrong shape, keeping drafts.")
+ return drafts
+
+ out = []
+ for original, rewrite in zip(drafts, result):
+ if _acceptable(original, rewrite):
+ out.append({
+ **original,
+ "subject": str(rewrite.get("subject") or "").strip(),
+ "body": str(rewrite["body"]).strip(),
+ })
+ else:
+ out.append(original)
+ kept = sum(1 for a, b in zip(drafts, out) if a is b)
+ if kept:
+ logger.info(f"Humanizer: kept {kept} of {len(drafts)} draft(s) unchanged after checks.")
+ return out
diff --git a/harvey/integrations/email_finder.py b/harvey/integrations/email_finder.py
index 733ecd7..f6a3baf 100644
--- a/harvey/integrations/email_finder.py
+++ b/harvey/integrations/email_finder.py
@@ -355,7 +355,10 @@ 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.
+ Reoon power-mode 'status' values: safe / invalid / disabled / disposable /
+ inbox_full / catch_all / role_account / spamtrap / unknown. 'safe' is its
+ deliverable verdict; a 'role_account' (info@, office@) counts as valid
+ only when Reoon also reports it deliverable.
"""
try:
async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:
@@ -375,6 +378,8 @@ async def verify_reoon(email: str, api_key: str) -> Optional[dict]:
if not isinstance(data, dict):
return None
status = str(data.get("status") or "").lower()
+ if status == "role_account":
+ status = "valid" if data.get("is_deliverable") else "unknown"
is_catch_all = bool(data.get("is_catch_all") or status == "catch_all")
return {"status": status, "catch_all": is_catch_all}
@@ -476,9 +481,9 @@ def _status_from_verdict(verdict: dict) -> Optional[str]:
if verdict.get("catch_all"):
return "risky"
status = verdict.get("status", "")
- if status in ("valid", "deliverable"):
+ if status in ("valid", "deliverable", "safe"):
return "verified"
- if status in ("invalid", "undeliverable", "disabled"):
+ if status in ("invalid", "undeliverable", "disabled", "disposable", "spamtrap"):
return "invalid"
if status in ("catch_all", "catch-all", "accept_all"):
return "risky"
@@ -549,6 +554,27 @@ async def _verify_candidate(email: str, mx_type: str, env) -> tuple[Optional[str
return None, catch_all_seen
+async def verify_published_address(email: str, env=None) -> str:
+ """Grade an address the company publishes on its own website.
+
+ Unlike a pattern guess, a published address is known to be used, so a
+ catch-all verdict (the domain accepts every address) doesn't make it
+ risky: it counts as verified. A verifier's invalid verdict still wins,
+ and an inconclusive check stays an honest guess that is never sent.
+ """
+ email = (email or "").strip().lower()
+ domain = email.partition("@")[2]
+ if not domain:
+ return "invalid"
+ mx_host = await get_mx_host(domain)
+ if not mx_host:
+ return "invalid"
+ status, _ = await _verify_candidate(email, classify_mx(mx_host), env)
+ if status == "risky":
+ return "verified"
+ return status or "guess"
+
+
# ── Top-level entry point ──
async def find_email(
diff --git a/harvey/models/prospect.py b/harvey/models/prospect.py
index 3aad1ef..f437b2e 100644
--- a/harvey/models/prospect.py
+++ b/harvey/models/prospect.py
@@ -5,6 +5,10 @@ from datetime import datetime, timezone
from pydantic import BaseModel, Field, field_validator
+# Source tag for a prospect that is a company's general inbox, not a person.
+COMPANY_INBOX_SOURCE = "company_inbox"
+
+
def _utcnow() -> datetime:
"""Naive UTC now (consistent with DB storage; avoids deprecated utcnow)."""
return datetime.now(timezone.utc).replace(tzinfo=None)
@@ -48,9 +52,19 @@ class Prospect(BaseModel):
def _strip_linkedin(cls, v: str) -> str:
return (v or "").strip()
+ @property
+ def is_company_inbox(self) -> bool:
+ """A company's published general address (info@, office@) with no named person."""
+ return self.source == COMPANY_INBOX_SOURCE
+
def full_name(self) -> str:
- return f"{self.first_name} {self.last_name}".strip()
+ name = f"{self.first_name} {self.last_name}".strip()
+ if not name and self.is_company_inbox:
+ return f"{self.company} team" if self.company else "the team"
+ return name
def is_valid(self) -> bool:
- """A contact must have at minimum a name and title."""
+ """A contact must have a name and title — or be a company inbox with an address."""
+ if self.is_company_inbox:
+ return bool(self.email and self.title)
return bool(self.first_name and self.last_name and self.title)
diff --git a/prompts/writer.md b/prompts/writer.md
index 0be75e6..db4f991 100644
--- a/prompts/writer.md
+++ b/prompts/writer.md
@@ -32,6 +32,18 @@ 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.
+SOUNDS-HUMAN CHECKS — the patterns that still give AI away after the rules above. Before returning, reread every email and rewrite any sentence that does one of these:
+- "Not X, but Y" contrasts, including split across two sentences ("It's not about X. It's about Y.") or "less X, more Y". Just state Y.
+- One-line dramatic closers or fragments ("That's the gap." "Every call counts."). End on the question instead.
+- Sayings that sound deep but say nothing ("Busy is a good problem until it isn't").
+- A staged run-up before the point ("Here's the thing:", "The truth is", "Funny enough"). Start with the point.
+- Forced groups of three ("calls, chats, and bookings") when one or two would do.
+- Stacked qualifiers ("really just pretty much") and hyphenated buzz-pairs ("always-on, done-for-you").
+- Inflated significance or sales language ("transform your business", "a whole new level", "crucial", "powerful", "robust", "effortless").
+- Shallow -ing riders tacked onto a sentence ("..., helping you grow"). Cut them.
+- Curly quotes or fancy punctuation. Straight quotes only.
+- Every sentence the same length. Mix short sentences with longer ones, the way people write when they type fast.
+
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.
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..f678523
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,9 @@
+import pytest
+
+import harvey.humanize
+
+
[email protected](autouse=True)
+def _no_installed_humanizer(monkeypatch, tmp_path):
+ """Tests never pick up the operator's real ~/.claude Humanizer skill."""
+ monkeypatch.setattr(harvey.humanize, "SKILL_PATH", tmp_path / "no-humanizer.md")
diff --git a/tests/test_company_inbox.py b/tests/test_company_inbox.py
new file mode 100644
index 0000000..1c0379f
--- /dev/null
+++ b/tests/test_company_inbox.py
@@ -0,0 +1,142 @@
+"""Company-inbox fallback: a business that names nobody is reached at its published inbox."""
+
+from types import SimpleNamespace
+
+import pytest
+
+import harvey.agents.scout as scout_mod
+import harvey.integrations.email_finder as ef
+from harvey.agents.scout import Scout
+from harvey.agents.sender import Sender
+from harvey.models.prospect import COMPANY_INBOX_SOURCE, Prospect
+
+
+def inbox(**kw):
+ base = dict(email="[email protected]", company="Acme Roofing", title="General inbox",
+ source=COMPANY_INBOX_SOURCE)
+ return Prospect(**{**base, **kw})
+
+
+# ── model ──
+
+def test_inbox_prospect_is_valid_without_a_name():
+ p = inbox()
+ assert p.is_company_inbox and p.is_valid()
+ assert p.full_name() == "Acme Roofing team"
+
+
+def test_inbox_needs_an_address_and_named_people_still_need_names():
+ assert not inbox(email="").is_valid()
+ assert not Prospect(email="[email protected]", title="Owner").is_valid()
+
+
+def test_render_greets_an_inbox_as_there():
+ sender = Sender.__new__(Sender)
+ assert sender._render("Hi {{first_name}}, {{company}}", inbox()) == "Hi there, Acme Roofing"
+ named = Prospect(first_name="Jo", last_name="Li", title="Owner", company="Acme")
+ assert sender._render("Hi {{first_name}}", named) == "Hi Jo"
+
+
+# ── verification ──
+
[email protected]("verdict, expected", [
+ ({"status": "safe"}, "verified"),
+ ({"status": "valid"}, "verified"),
+ ({"status": "spamtrap"}, "invalid"),
+ ({"status": "disposable"}, "invalid"),
+ ({"status": "unknown"}, None),
+ ({"status": "safe", "catch_all": True}, "risky"),
+])
+def test_reoon_verdicts(verdict, expected):
+ assert ef._status_from_verdict(verdict) == expected
+
+
[email protected]("graded, expected", [
+ ("verified", "verified"),
+ ("risky", "verified"), # published on their site, so catch-all is fine
+ ("invalid", "invalid"),
+ (None, "guess"), # inconclusive stays a guess: never sent
+])
+async def test_published_address_grading(monkeypatch, graded, expected):
+ async def mx(domain):
+ return "smtp.google.com"
+
+ async def check(email, mx_type, env):
+ return graded, graded == "risky"
+
+ monkeypatch.setattr(ef, "get_mx_host", mx)
+ monkeypatch.setattr(ef, "_verify_candidate", check)
+ assert await ef.verify_published_address("[email protected]") == expected
+
+
+async def test_published_address_without_mail_server_is_invalid(monkeypatch):
+ async def no_mx(domain):
+ return None
+
+ monkeypatch.setattr(ef, "get_mx_host", no_mx)
+ assert await ef.verify_published_address("[email protected]") == "invalid"
+
+
+# ── scout ──
+
+PAGES = {
+ "https://acme.com": '<a href="mailto:[email protected]">Jobs</a> <a href="mailto:[email protected]">Email us</a>',
+ "https://acme.com/contact": "Write to [email protected] or [email protected]",
+}
+
+
+def make_scout(pages, verdict="verified"):
+ scout = Scout.__new__(Scout)
+ scout.env = None
+ scout._seen_prospect_keys = set()
+
+ async def resolve(domain, retries=1):
+ home = pages.get("https://acme.com")
+ return ("https://acme.com", SimpleNamespace(text=home)) if home is not None else ("", None)
+
+ async def fetch(url, **kw):
+ text = pages.get(url)
+ return SimpleNamespace(text=text) if text is not None else None
+
+ async def not_dup(prospect):
+ return False
+
+ scout._resolve_base_url = resolve
+ scout._fetch = fetch
+ scout._is_duplicate_prospect = not_dup
+ return scout
+
+
+async def test_finds_the_most_owner_like_on_domain_address():
+ assert await make_scout(PAGES)._find_inbox_address("acme.com") == "[email protected]"
+
+
+async def test_no_usable_address_means_no_inbox():
+ pages = {"https://acme.com": '<a href="mailto:[email protected]">x</a> [email protected]'}
+ assert await make_scout(pages)._find_inbox_address("acme.com") == ""
+
+
+async def test_inbox_prospect_carries_its_verification(monkeypatch):
+ async def graded(email, env=None):
+ return "verified"
+
+ monkeypatch.setattr(scout_mod, "verify_published_address", graded)
+ p = await make_scout(PAGES)._company_inbox_prospect("c1", "acme.com", "Acme Roofing", "Roofing")
+ assert p.email == "[email protected]" and p.email_status == "verified"
+ assert p.is_company_inbox and p.company_id == "c1"
+
+
+# ── writer ──
+
+def test_inbox_prospects_get_their_own_campaign():
+ from harvey.agents.writer import Writer
+ writer = Writer.__new__(Writer)
+ writer.config = SimpleNamespace(channels=SimpleNamespace(email=SimpleNamespace(provider="gmail")))
+ named = Prospect(first_name="Jo", last_name="Li", title="Owner", industry="Roofing", email="[email protected]")
+ batches = writer._group_prospects([named, inbox(industry="Roofing")])
+ assert set(batches) == {"Roofing-outreach", "Roofing-inbox-outreach"}
diff --git a/tests/test_humanize.py b/tests/test_humanize.py
new file mode 100644
index 0000000..98ee2b9
--- /dev/null
+++ b/tests/test_humanize.py
@@ -0,0 +1,78 @@
+"""The Humanizer pass rewrites drafts but never lets a bad rewrite through."""
+
+import pytest
+
+from harvey.humanize import humanize, load_skill
+
+
+class FakeBrain:
+ def __init__(self, reply):
+ self.reply = reply
+ self.prompts = []
+
+ async def think_json(self, prompt, **kwargs):
+ self.prompts.append(prompt)
+ if isinstance(self.reply, Exception):
+ raise self.reply
+ return self.reply
+
+
+def skill(tmp_path):
+ path = tmp_path / "SKILL.md"
+ path.write_text("---\nname: humanizer\n---\n\n# Humanizer\nCut the tells.\n")
+ return path
+
+
+DRAFT = {"subject": "missed calls", "body": "Hi {{first_name}}, it's not about calls. It's about jobs. Who answers after five?"}
+
+
+def test_load_skill_strips_frontmatter(skill):
+ assert load_skill(skill) == "# Humanizer\nCut the tells."
+
+
+def test_missing_skill_is_a_no_op(tmp_path):
+ assert load_skill(tmp_path / "nope.md") == ""
+
+
+async def test_no_skill_makes_no_call(tmp_path):
+ brain = FakeBrain([])
+ assert await humanize(brain, [DRAFT], "writer", path=tmp_path / "nope.md") == [DRAFT]
+ assert brain.prompts == []
+
+
+async def test_good_rewrite_is_used(skill):
+ rewrite = {"subject": "after five", "body": "Hi {{first_name}}, who picks up the phone after five?"}
+ brain = FakeBrain([rewrite])
+ out = await humanize(brain, [DRAFT], "writer", path=skill)
+ assert out == [rewrite]
+ assert "Cut the tells." in brain.prompts[0]
+
+
+ {"subject": "after five", "body": "Hi there, who picks up after five?"}, # lost merge var
+ {"subject": "after five", "body": "Hi {{first_name}} — who picks up after five?"}, # new em dash
+ {"subject": "", "body": "Hi {{first_name}}, who picks up after five?"}, # dropped subject
+ {"subject": "after five", "body": "Hi {{first_name}}, " + "word " * 40}, # much longer
+ "not a dict",
+])
+async def test_bad_rewrite_keeps_original(skill, bad):
+ out = await humanize(FakeBrain([bad]), [DRAFT], "writer", path=skill)
+ assert out == [DRAFT]
+
+
+async def test_wrong_shape_or_failure_keeps_all(skill):
+ assert await humanize(FakeBrain([]), [DRAFT], "writer", path=skill) == [DRAFT]
+ assert await humanize(FakeBrain(None), [DRAFT], "writer", path=skill) == [DRAFT]
+ assert await humanize(FakeBrain(RuntimeError("down")), [DRAFT], "writer", path=skill) == [DRAFT]
+
+
+async def test_reply_without_subject(skill):
+ reply = {"subject": "", "body": "Sure, Thursday works. What time suits you?"}
+ out = await humanize(FakeBrain([reply]), [{"subject": "", "body": "Sure! Thursday works for me. What time suits you best?"}], "handler", path=skill)
+ assert out == [reply]