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.
Address review: cache fingerprint, reply starvation, response checks
Gabe AO2458842fa3d2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c1e6136..73137aa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,10 +14,11 @@ minor versions can still change behaviour.have each new recipient checked before the first cold email against UKPECR, US CAN-SPAM, Canada's CASL, Germany's UWG and France's rules. Anyverdict but `ok_to_email` fails that outbox item with the rule and the next- step. If the check can't be made (daily allowance used up, network down),- cold emails wait for a later cycle while replies still go out. One check per- address, cached for 30 days, and the receipt id is logged with each send.- Native providers only. Off by default.+ step. If the check can't be made (daily allowance used up, network down, a+ malformed response), cold emails wait for a later cycle while replies still+ go out. One check per address, cached for 30 days; changing the sender+ country, address source or product description triggers a fresh check. The+ receipt id is logged with each send. Native providers only. Off by default.## [0.3.0] — 2026-10-13diff --git a/README.md b/README.mdindex 5bcbb10..7dfabfe 100644--- a/README.md+++ b/README.md@@ -461,7 +461,7 @@ Harvey automates outreach, but **you are the sender.** Cold email is legal in mo**GDPR / PECR (EU & UK).** B2B cold email needs a defensible legitimate interest: the pitch must be genuinely relevant to that person's role, you must know where the data came from, and objecting must be effortless. If you can't say why a specific person would care, Harvey shouldn't email them — and its qualification rules say so.-**Per-recipient check (optional).** Those rules turn on facts about each recipient: a UK sole trader needs consent where a limited company doesn't, Germany wants prior consent even for business email, and Canada's CASL depends on whether the address was published. With `compliance.precleared.enabled: true`, Harvey asks [Precleared](https://precleared.dev) about each new recipient before the first cold email. Anything other than `ok_to_email` holds that email back, with the rule and the next step shown in the Outbox, and the signed receipt id is logged with every send. One check per address, cached for 30 days; replies are never checked; native providers (Gmail, SMTP) only. Precleared receives the recipient's address, your sender country, the address source and your product description. Without a key it allows 10 checks a day, and a free key (`PRECLEARED_API_KEY`) allows 25. Put the setting in `harvey.yaml`, or in `harvey.local.yaml` if you trained Harvey, since that file wins.+**Per-recipient check (optional).** Those rules turn on facts about each recipient: a UK sole trader needs consent where a limited company doesn't, Germany wants prior consent even for business email, and Canada's CASL depends on whether the address was published. With `compliance.precleared.enabled: true`, Harvey asks [Precleared](https://precleared.dev) about each new recipient before the first cold email. Anything other than `ok_to_email` holds that email back, with the rule and the next step shown in the Outbox, and the signed receipt id is logged with every send. One check per address, cached for 30 days (changing the sender country, address source or product description triggers a fresh check); replies are never checked; native providers (Gmail, SMTP) only. Precleared receives the recipient's address, your sender country, the address source and your product description. Without a key it allows 10 checks a day, and a free key (`PRECLEARED_API_KEY`) allows 25. Put the setting in `harvey.yaml`, or in `harvey.local.yaml` if you trained Harvey, since that file wins.**Bot disclosure.** Some jurisdictions require disclosing automation. Harvey is instructed to answer truthfully, always, if a prospect asks whether they're talking to an AI. Never configure it otherwise.diff --git a/harvey/agents/sender.py b/harvey/agents/sender.pyindex 5343bae..dc84410 100644--- a/harvey/agents/sender.py+++ b/harvey/agents/sender.py@@ -440,6 +440,22 @@ class Sender:due = await self.state.get_outbox(status="approved", due_before=now, limit=budget * 3)+ if self.precleared is not None:+ # Cold emails held by an unavailable compliance check stay+ # approved at the front of the queue and could fill the page+ # above, so fetch replies (and any other unchecked kind) on their+ # own too. Bounded: one extra query of the same size.+ seen = {item["id"] for item in due}+ unchecked = await self.state.get_outbox(+ status="approved", due_before=now, limit=budget * 3,+ exclude_kind="sequence",+ )+ extra = [item for item in unchecked if item["id"] not in seen]+ if extra:+ due = sorted(+ due + extra,+ key=lambda i: (i.get("send_at") or "", i.get("created_at") or ""),+ )if not due:returndiff --git a/harvey/integrations/precleared.py b/harvey/integrations/precleared.pyindex 38faf1c..bfdef68 100644--- a/harvey/integrations/precleared.py+++ b/harvey/integrations/precleared.py@@ -8,15 +8,23 @@ CAN-SPAM, Canada's CASL, Germany's UWG or France's rules? Anything other thanid is logged with the send so the decision can be shown later.One check per address: a definite verdict is cached in the settings table for-CACHE_DAYS, so a three-step sequence costs one check. Replies are never-checked. Precleared receives the recipient's address, your sender country,-the address source you configure and your product description (used to judge-relevance under CASL and French rules).+CACHE_DAYS, together with a fingerprint of the facts it was decided on (sender+country, address source, product description). A cached verdict is reused only+while those facts are unchanged, so a three-step sequence costs one check but a+config change forces a fresh one. Replies are never checked. Precleared+receives the recipient's address, your sender country, the address source you+configure and your product description (used to judge relevance under CASL and+French rules).++A response Precleared can't vouch for (network trouble, daily allowance used+up, a bad key, or a malformed body) holds cold email for a later cycle instead+of failing it.Without an API key Precleared allows 10 checks a day; a free key(https://precleared.dev/get-key, PRECLEARED_API_KEY) allows 25 a day."""+import hashlibimport jsonimport loggingfrom dataclasses import dataclass@@ -31,7 +39,11 @@ API_URL = "https://precleared.dev/api/v1/check"# lookup is slow), so the read timeout sits just above that.TIMEOUT = httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0)CACHE_DAYS = 30+# Bump when the facts in _fingerprint change, so older cache entries are+# ignored rather than reused.+CACHE_VERSION = 2SETTINGS_PREFIX = "precleared:"+VERDICTS = {"ok_to_email", "consent_needed", "blocked", "unknown"}DEFINITE_VERDICTS = {"ok_to_email", "consent_needed", "blocked"}ADDRESS_SOURCES = ("published", "bought", "scraped", "given", "unknown")SENDER_COUNTRIES = ("GB", "US")@@ -42,9 +54,9 @@ class Clearance:"""Precleared's answer for one address.``allowed``: send it. ``held``: the check could not be made right now- (network trouble, daily allowance used up, bad key), so the email stays- queued and is tried again on a later cycle. Otherwise the email is- blocked and ``reason`` says why.+ (network trouble, daily allowance used up, bad key, malformed response),+ so the email stays queued and is tried again on a later cycle. Otherwise+ the email is blocked and ``reason`` says why."""allowed: bool@@ -89,21 +101,40 @@ class PreclearedClient:return text.replace(self.api_key, "***REDACTED***")return text or ""+ def _fingerprint(self) -> str:+ """Hash of the facts Precleared decides on, apart from the address.++ These are exactly the fields _check sends with the address, so a+ cached verdict is only reused for the same question.+ """+ facts = {+ "v": CACHE_VERSION,+ "sender_country": self.sender_country,+ "address_source": self.address_source,+ "pitch": self.pitch,+ "existing_customer": False,+ }+ return hashlib.sha256(json.dumps(facts, sort_keys=True).encode()).hexdigest()+async def clear(self, to_email: str, state) -> Clearance:"""Return the verdict for one address, from the cache when possible."""email = (to_email or "").strip().lower()key = SETTINGS_PREFIX + email- cached = _from_cache(await state.get_setting(key))+ inputs = self._fingerprint()+ cached = _from_cache(await state.get_setting(key), inputs)if cached is not None:return cachedresult = await self._check(email)if not result.held and result.verdict in DEFINITE_VERDICTS:+ # One entry per address: a fresh verdict replaces any earlier+ # one, including legacy entries written without a fingerprint.await state.set_setting(key, json.dumps({"verdict": result.verdict,"reason": result.reason,"receipt_id": result.receipt_id,"checked_at": _utcnow().isoformat(),+ "inputs": inputs,}))return result@@ -148,57 +179,85 @@ class PreclearedClient:except ValueError:return Clearance(allowed=False, held=True, reason="Precleared returned invalid JSON")- verdict = str(data.get("verdict") or "")- receipt = data.get("receipt") or {}- receipt_id = str(receipt.get("id") or "") if isinstance(receipt, dict) else ""+ # Only a JSON object with a known verdict counts as an answer.+ # Anything else is treated like an unavailable check, so cold email+ # is held, not failed, and the rest of the cycle carries on.+ if not isinstance(data, dict):+ return Clearance(allowed=False, held=True,+ reason="Precleared returned an unexpected response (not a JSON object)")+ verdict = data.get("verdict")+ if not isinstance(verdict, str) or verdict not in VERDICTS:+ return Clearance(allowed=False, held=True,+ reason="Precleared returned a response without a known verdict")++ receipt = data.get("receipt")+ receipt_id = _text(receipt.get("id")) if isinstance(receipt, dict) else ""if verdict == "ok_to_email":return Clearance(allowed=True, verdict=verdict, receipt_id=receipt_id)return Clearance(allowed=False,- verdict=verdict or "unknown",+ verdict=verdict,reason=_reason(data),receipt_id=receipt_id,)+def _text(value) -> str:+ """A stripped string, or "" for anything that isn't one."""+ return value.strip() if isinstance(value, str) else ""++def _reason(data: dict) -> str:"""One readable line: the rule that decided it (or the note), then the next step.Precleared's ``reasons`` lead with the matching rule as``{"rule_key", "text", "source_title", "source_url"}``, or with a- ``{"note": ...}`` when no rule could be applied.+ ``{"note": ...}`` when no rule could be applied. Fields with an+ unexpected shape are skipped."""+ reasons = data.get("reasons")+ first = reasons[0] if isinstance(reasons, list) and reasons and isinstance(reasons[0], dict) else {}+ text = _text(first.get("text")) or _text(first.get("note"))+ source = _text(first.get("source_title"))parts = []- reasons = data.get("reasons") or []- first = reasons[0] if reasons and isinstance(reasons[0], dict) else {}- text = str(first.get("text") or first.get("note") or "").strip()- source = str(first.get("source_title") or "").strip()if text:parts.append(f"{text} ({source})" if source else text)- next_step = str(data.get("next_step") or "").strip()+ next_step = _text(data.get("next_step"))if next_step:parts.append(next_step)return " ".join(parts)[:240]-def _from_cache(raw: str) -> Clearance | None:+def _from_cache(raw: str, inputs: str) -> Clearance | None:+ """A cached verdict, or None when there is none to trust.++ Entries decided on different facts, legacy entries without a+ fingerprint, expired or malformed entries all count as missing.+ """if not raw:return Nonetry:data = json.loads(raw)- checked_at = datetime.fromisoformat(data["checked_at"])- except (ValueError, KeyError, TypeError):+ except (ValueError, TypeError):+ return None+ if not isinstance(data, dict) or data.get("inputs") != inputs:+ return None+ verdict = data.get("verdict")+ if not isinstance(verdict, str) or verdict not in DEFINITE_VERDICTS:+ return None+ try:+ checked_at = datetime.fromisoformat(str(data["checked_at"]))+ except (KeyError, ValueError, TypeError):return Noneif checked_at.tzinfo is None:checked_at = checked_at.replace(tzinfo=timezone.utc)if _utcnow() - checked_at > timedelta(days=CACHE_DAYS):return None- verdict = data.get("verdict", "")return Clearance(allowed=verdict == "ok_to_email",verdict=verdict,- reason=data.get("reason", ""),- receipt_id=data.get("receipt_id", ""),+ reason=_text(data.get("reason")),+ receipt_id=_text(data.get("receipt_id")),)diff --git a/harvey/state.py b/harvey/state.pyindex d0f9d88..a82b4c6 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -853,6 +853,7 @@ class StateManager:status: str | None = None,due_before: str | None = None,limit: int = 200,+ exclude_kind: str | None = None,) -> list[dict]:where, params = [], []if status:@@ -861,6 +862,9 @@ class StateManager:if due_before:where.append("(send_at IS NULL OR send_at <= ?)")params.append(due_before)+ if exclude_kind:+ where.append("(kind IS NULL OR kind != ?)")+ params.append(exclude_kind)sql = "SELECT * FROM outbox"if where:sql += " WHERE " + " AND ".join(where)diff --git a/tests/test_precleared.py b/tests/test_precleared.pyindex 1080977..2cda8b0 100644--- a/tests/test_precleared.py+++ b/tests/test_precleared.py@@ -6,6 +6,7 @@ checked. No network: every Precleared call goes to an httpx.MockTransport."""import jsonimport osimport tempfile+from datetime import datetime, timezonefrom types import SimpleNamespaceimport aiosqlite@@ -282,3 +283,96 @@ async def test_replies_are_never_checked(state):assert calls == []assert len(provider.sent) == 1+++# ── review regressions (PR #8) ──+++async def test_changed_decision_inputs_require_a_new_check(state):+ calls = []+ initial = PreclearedClient("US", address_source="published", pitch="Delivery software",+ transport=mock_precleared(calls, OK_BODY))+ assert (await initial.clear("[email protected]", state)).allowed++ updated = PreclearedClient("GB", address_source="unknown", pitch="Unrelated offer",+ transport=mock_precleared(calls, CONSENT_BODY))+ result = await updated.clear("[email protected]", state)++ assert not result.allowed, f"Stale approval reused; upstream calls={len(calls)}"+ assert result.verdict == "consent_needed"+ assert result.receipt_id == "cc_rcpt_NO0000000001"+ assert len(calls) == 2+ # The new verdict replaced the old one, so asking again with the new facts is cached.+ assert not (await updated.clear("[email protected]", state)).allowed+ assert len(calls) == 2+++async def test_legacy_address_only_cache_entry_is_not_reused(state):+ await state.set_setting(SETTINGS_PREFIX + "[email protected]", json.dumps({+ "verdict": "ok_to_email", "reason": "", "receipt_id": "cc_rcpt_OLD0000000001",+ "checked_at": datetime.now(timezone.utc).isoformat(),+ }))+ calls = []+ client = PreclearedClient("GB", transport=mock_precleared(calls, CONSENT_BODY))++ result = await client.clear("[email protected]", state)++ assert not result.allowed+ assert len(calls) == 1+++async def test_held_cold_backlog_does_not_starve_replies(state):+ pid = await seed_prospect(state)+ for step in range(24):+ await queue(state, pid, step=step + 1)+ reply_pid = await seed_prospect(state, email="[email protected]", status="replied")+ await queue(state, reply_pid, kind="reply", to="[email protected]")+ provider = FakeProvider()+ sender = with_check(make_sender(state, provider), mock_precleared([], status=429))++ await sender._drain_due()+ await sender._drain_due()++ assert [m["to"] for m in provider.sent] == ["[email protected]"]+ assert len(await state.get_outbox(status="approved")) == 24+ assert await state.get_outbox(status="failed") == []++[email protected]("body", [[], "ok_to_email", {"verdict": "maybe"}, {"reasons": []}])+async def test_malformed_response_holds_cold_email_and_reply_still_sends(state, body):+ pid = await seed_prospect(state)+ await queue(state, pid)+ reply_pid = await seed_prospect(state, email="[email protected]", status="replied")+ await queue(state, reply_pid, kind="reply", to="[email protected]")+ provider = FakeProvider()+ sender = with_check(make_sender(state, provider), mock_precleared([], body=body))++ await sender._drain_due()++ assert [m["to"] for m in provider.sent] == ["[email protected]"]+ assert await state.get_outbox(status="failed") == []+ assert [i["to_email"] for i in await state.get_outbox(status="approved")] == ["[email protected]"]+ # Nothing cached from a malformed answer, so the next cycle asks again.+ assert await state.get_setting(SETTINGS_PREFIX + "[email protected]") == ""+++async def test_unexpected_optional_field_shapes_are_ignored(state):+ body = {+ "verdict": "consent_needed",+ "reasons": {"text": "not a list"},+ "next_step": 5,+ "receipt": "cc_rcpt_not_an_object",+ }+ client = PreclearedClient("GB", transport=mock_precleared([], body=body))++ result = await client.clear("[email protected]", state)++ assert not result.allowed and not result.held+ assert result.verdict == "consent_needed"+ assert result.reason == ""+ assert result.receipt_id == ""