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.

Set aside our text inside long lines too; templates count as ours; tighter opt-out rules

Ethan4ce1d6f26925
diff --git a/README.md b/README.md
index c3ce9fa..b584568 100644
--- a/README.md
+++ b/README.md
@@ -485,7 +485,7 @@ What to know:
Harvey automates outreach, but **you are the sender.** Cold email is legal in most places when done right and expensive when done wrong — CAN-SPAM penalties run to $53,088 per email. Harvey ships with compliant defaults. Keep them.
-**CAN-SPAM (US).** Truthful subject line and accurate from-address — Harvey's copywriting rules forbid fake "re:" threads and impersonation. A working opt-out, honored fast: every cold email ends with an opt-out line (`compliance.opt_out_line`, default *Not interested? Reply "no thanks" and I won't email again.*), and Harvey treats any opt-out wording as immediate and permanent, wherever in the reply the person wrote it (including a bare "STOP" or "No thanks"). Your physical mailing address in the footer: set `compliance.postal_address` in `harvey.yaml` before your first campaign. Harvey adds both lines under every cold email when it sends (replies don't get them), shows them under each draft in the Outbox, and warns on `harvey run`, `harvey status` and the Outbox tab until the address is set. Any line of a reply that repeats what Harvey sent that person is treated as quoted, not as their words, so quoting Harvey's own footer isn't an opt-out; the model also reads replies without the quoted email. The opt-out line must ask for a reply Harvey recognises ("no thanks", "unsubscribe", "stop", "remove me", "opt out") and can't contain a link.
+**CAN-SPAM (US).** Truthful subject line and accurate from-address — Harvey's copywriting rules forbid fake "re:" threads and impersonation. A working opt-out, honored fast: every cold email ends with an opt-out line (`compliance.opt_out_line`, default *Not interested? Reply "no thanks" and I won't email again.*), and Harvey treats any opt-out wording as immediate and permanent, wherever in the reply the person wrote it (including a bare "STOP" or "No thanks"). Your physical mailing address in the footer: set `compliance.postal_address` in `harvey.yaml` before your first campaign. Harvey adds both lines under every cold email when it sends (replies don't get them), shows them under each draft in the Outbox, and warns on `harvey run`, `harvey status` and the Outbox tab until the address is set. Text in a reply that repeats what Harvey wrote for that person (its emails, footers as sent, campaign templates) is set aside as quoted, not read as their words, so quoting Harvey's own footer isn't an opt-out; the model also reads replies without the quoted email. The opt-out line must ask for a reply Harvey recognises (`Reply "no thanks"`, `Reply STOP`, also "unsubscribe", "remove me", "opt out") and can't contain a link or email address.
**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.
diff --git a/harvey/agents/handler.py b/harvey/agents/handler.py
index 1ef3003..bf77824 100644
--- a/harvey/agents/handler.py
+++ b/harvey/agents/handler.py
@@ -65,38 +65,82 @@ OPT_OUT_PATTERNS = (
"delete my info",
"delete my data",
)
-# "No thanks" (what cold email's footer asks for) as a phrase on one line,
-# not "yes or no / Thanks," or "no Thanksgiving".
-NO_THANKS_RE = re.compile(r"\bno,?[ \t]+thank(?:s|[ \t]+you)\b")
-# A reply that says only this is an opt-out ("Reply STOP to opt out").
+# "No thanks" (what cold email's footer asks for) as a phrase: not "no
+# Thanksgiving", "Bruno / Thanks," or "yes or no, thanks".
+NO_THANKS_RE = re.compile(r"(?<!\bor )\bno,?[ \t]+thank(?:s|[ \t]+you)\b")
+# A reply that says only this (signature aside) is an opt-out ("Reply STOP").
BARE_OPT_OUTS = {"stop", "unsubscribe", "remove", "remove me", "opt out",
"no thanks", "no thank you"}
-# A line at least this long that repeats what Harvey sent this person is our
-# quoted email, not their words. Shorter lines are always theirs, so a reply
-# of "No thanks" or "STOP" is never mistaken for a quote of our footer.
+_MOBILE_SIGNATURE_RE = re.compile(
+ r"^[ \t]*(?:sent from my \w[^\n]*|get outlook for \w[^\n]*|sent from \w+ mail[^\n]*)$",
+ re.IGNORECASE | re.MULTILINE)
+# A line of their reply at least this long that repeats what Harvey wrote
+# for this person is our text, not theirs. Shorter unmarked lines are always
+# theirs, so a reply of "No thanks" or "STOP" is never taken for a quote.
OWN_TEXT_MIN_CHARS = 20
+# Outlook's plain-text quotes add "<mailto:...>" / "<https://...>" after links.
+_LINK_ANNOTATION_RE = re.compile(r"<(?:mailto:|https?://)[^>\s]*>", re.IGNORECASE)
+_MERGE_TAG_RE = re.compile(r"\{\{\s*\w+\s*\}\}")
def _flat(text: str) -> str:
- """Lowercase, quote markers, HTML entities, curly quotes and spacing
- evened out, so text compares however a mail client re-quoted it."""
- text = re.sub(r"^[ \t>]+", "", html.unescape(text or ""), flags=re.MULTILINE)
+ """Lowercase, with quote markers, HTML entities, link annotations, curly
+ quotes and spacing evened out, so text compares however a mail client
+ re-quoted it."""
+ text = _LINK_ANNOTATION_RE.sub("", html.unescape(text or ""))
+ text = re.sub(r"^[ \t>]+", "", text, flags=re.MULTILINE)
text = (text.replace("\u201c", '"').replace("\u201d", '"')
.replace("\u2018", "'").replace("\u2019", "'"))
return " ".join(text.lower().split())
-def _drop_our_text(text: str, ours: str) -> str:
- """The reply without lines that repeat what we sent (`ours`, flattened)."""
- return "\n".join(
- line for line in (text or "").split("\n")
- if not (len(_flat(line)) >= OWN_TEXT_MIN_CHARS and _flat(line) in ours))
+class OurText:
+ """What Harvey wrote for one person, to tell their words from our quote."""
+
+ def __init__(self, texts):
+ self.lines = set()
+ for text in texts:
+ # Merge tags weren't filled in templates: compare the parts around them.
+ for part in _MERGE_TAG_RE.split(text or ""):
+ for line in part.split("\n"):
+ line = _flat(line)
+ if len(line) >= OWN_TEXT_MIN_CHARS:
+ self.lines.add(line)
+ self.joined = "\n".join(sorted(self.lines))
+
+ def _is_ours(self, line: str) -> bool:
+ flat = _flat(line)
+ if not flat or flat not in self.joined:
+ return False
+ # A ">" line is quoted anyway; an unmarked one must be long enough
+ # that it can't be their own short "No thanks".
+ return line.lstrip().startswith(">") or len(flat) >= OWN_TEXT_MIN_CHARS
+
+ def remove(self, text: str) -> str:
+ """Their reply without our text: lines that repeat ours are dropped,
+ and any of our lines inside a longer line (an HTML reply flattened to
+ one line) is cut out of it."""
+ kept = []
+ for line in (text or "").split("\n"):
+ if self._is_ours(line):
+ continue
+ flat = _flat(line)
+ hits = [ours for ours in self.lines if ours in flat]
+ if hits:
+ for ours in sorted(hits, key=len, reverse=True):
+ flat = flat.replace(ours, " ")
+ line = " ".join(flat.split())
+ kept.append(line)
+ return "\n".join(kept)
def _is_opt_out(keyword_text: str, own_words: str) -> bool:
+ """keyword_text: everything they wrote, flattened (phrases can span a
+ line wrap). own_words: their reply without the quote."""
if any(p in keyword_text for p in OPT_OUT_PATTERNS) or NO_THANKS_RE.search(keyword_text):
return True
- return re.sub(r"[^\w\s-]", "", _flat(own_words)).strip() in BARE_OPT_OUTS
+ bare = _flat(_MOBILE_SIGNATURE_RE.sub("", own_words or ""))
+ return re.sub(r"[^\w\s-]", "", bare).strip() in BARE_OPT_OUTS
# Phrases that mean a human must take over. Never auto-reply to these.
ESCALATION_PATTERNS = (
@@ -232,15 +276,14 @@ class Handler:
await self.state.mark_reply_processed(reply_uuid)
return True
- async def _our_text(self, prospect) -> str:
+ async def _our_text(self, prospect) -> OurText:
"""Everything a reply from this person might quote back from us: what
- we actually sent them (footer included, whatever it said then) and
- today's footer (Instantly sends aren't in the outbox)."""
+ Harvey wrote for them (footers as sent) and today's footer."""
compliance = compliance_of(self.config)
- sent = await self.state.get_sent_outbox_bodies(prospect.id)
- return "\n".join(_flat(t) for t in (
- *sent, compliance.postal_address, compliance.opt_out_line,
- DEFAULT_OPT_OUT_LINE) if t)
+ return OurText([
+ *await self.state.get_texts_for_prospect(prospect.id),
+ compliance.postal_address, compliance.opt_out_line, DEFAULT_OPT_OUT_LINE,
+ ])
async def _process_reply(
self,
@@ -263,10 +306,9 @@ class Handler:
# without the quoted email. Either way, a line repeating what we
# sent (our footer says "no thanks") is ours, not theirs.
ours = await self._our_text(prospect)
- keyword_text = "\n".join(
- _flat(line) for line in _drop_our_text(reply_text, ours).split("\n"))
+ keyword_text = _flat(ours.remove(reply_text))
stripped = strip_quoted_reply(reply_text) or reply_text
- reply_text = _drop_our_text(stripped, ours).strip() or stripped
+ reply_text = ours.remove(stripped).strip() or stripped
# Update prospect status + stop-on-reply: a human answered, so every
# queued sequence email for them is now wrong to send.
diff --git a/harvey/config.py b/harvey/config.py
index e1ce364..5148535 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -208,9 +208,13 @@ class PreclearedConfig(BaseModel):
DEFAULT_OPT_OUT_LINE = 'Not interested? Reply "no thanks" and I won\'t email again.'
-# Opt-out wording the Handler always honours; an opt_out_line must ask for one.
+# The replies the Handler always honours as an opt-out on their own; an
+# opt_out_line must ask for one of them ("Reply STOP", 'reply "no thanks"').
OPT_OUT_WORDS = ("no thanks", "no thank you", "unsubscribe", "stop", "remove me",
- "opt out", "opt-out")
+ "opt out")
+_ASKS_FOR_OPT_OUT_RE = re.compile(
+ r"\breply(?:\s+with)?\s*[\"'\u201c\u2018]?\s*(?:"
+ + "|".join(re.escape(w) for w in OPT_OUT_WORDS) + r")\b", re.IGNORECASE)
class ComplianceConfig(BaseModel):
@@ -235,15 +239,16 @@ class ComplianceConfig(BaseModel):
lowered = v.lower()
if not v:
return v
- if "http" in lowered or "www." in lowered or "click" in lowered:
+ if any(bit in lowered for bit in ("http", "www.", "click", "@")):
raise ValueError(
- "opt_out_line can't contain a link: cold email allows one link, and "
- "opting out must be as simple as replying."
+ "opt_out_line can't contain a link or an email address: cold email "
+ "allows one link, and opting out must be as simple as replying."
)
- if not any(word in lowered for word in OPT_OUT_WORDS):
+ if not _ASKS_FOR_OPT_OUT_RE.search(v):
raise ValueError(
- "opt_out_line must ask for a reply Harvey recognises as an opt-out: "
- + ", ".join(f'"{w}"' for w in OPT_OUT_WORDS[:5]) + "."
+ "opt_out_line must ask for a reply Harvey recognises as an opt-out, "
+ 'e.g. Reply "no thanks" / Reply STOP. Recognised: '
+ + ", ".join(f'"{w}"' for w in OPT_OUT_WORDS) + "."
)
return v
diff --git a/harvey/state.py b/harvey/state.py
index f4040f6..63083f8 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -912,16 +912,34 @@ class StateManager:
async with db.execute(sql, params) as cursor:
return [dict(r) for r in await cursor.fetchall()]
- async def get_sent_outbox_bodies(self, prospect_id: str, limit: int = 10) -> list[str]:
- """What Harvey actually sent this person (footer included), newest
- first: the text a reply may quote back."""
+ async def get_texts_for_prospect(self, prospect_id: str, limit: int = 20) -> list[str]:
+ """Everything Harvey wrote for this person, which a reply may quote
+ back: their Outbox emails (a sent one with its footer, whatever it
+ said then) and the templates of campaigns they're in (Instantly and
+ hand sends never pass through the Outbox; merge tags unfilled)."""
+ texts: list[str] = []
async with self._connect() as db:
async with db.execute(
- "SELECT body FROM outbox WHERE prospect_id = ? AND status = 'sent' "
- "ORDER BY sent_at DESC LIMIT ?",
+ "SELECT body FROM outbox WHERE prospect_id = ? "
+ "ORDER BY created_at DESC LIMIT ?",
(prospect_id, int(limit)),
) as cursor:
- return [r[0] or "" for r in await cursor.fetchall()]
+ texts += [r[0] or "" for r in await cursor.fetchall()]
+ async with db.execute(
+ "SELECT sequence_json, prospect_ids_json FROM campaigns "
+ "WHERE prospect_ids_json LIKE ? ORDER BY created_at DESC LIMIT ?",
+ ("%" + prospect_id + "%", int(limit)),
+ ) as cursor:
+ rows = await cursor.fetchall()
+ for sequence_json, ids_json in rows:
+ try:
+ if prospect_id not in json.loads(ids_json or "[]"):
+ continue
+ texts += [str(step.get("body") or "") for step in json.loads(sequence_json or "[]")
+ if isinstance(step, dict)]
+ except (json.JSONDecodeError, TypeError, AttributeError):
+ continue
+ return texts
async def get_outbox_item(self, item_id: str) -> dict | None:
async with self._connect() as db:
diff --git a/harvey/web/app.js b/harvey/web/app.js
index d1e8be9..a8df742 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -1626,7 +1626,8 @@ async function openInGmail(ci, si, ri) {
const r = c && (c.recipients || [])[ri];
if (!step || !r) return;
// Cold email carries the postal address and opt-out line, sent by hand too.
- const body = fillMergeVars(step.body, r).trimEnd() + (c.footer ? '\n\n' + c.footer : '');
+ const filled = fillMergeVars(step.body, r).trimEnd();
+ const body = filled + (c.footer && !filled.endsWith(c.footer) ? '\n\n' + c.footer : '');
// authuser picks the Google account Harvey sends as, not just whichever
// one the browser happens to be signed into.
const url = 'https://mail.google.com/mail/?view=cm&fs=1' +
diff --git a/tests/test_compliance_footer.py b/tests/test_compliance_footer.py
index 7e10305..a7157d5 100644
--- a/tests/test_compliance_footer.py
+++ b/tests/test_compliance_footer.py
@@ -418,3 +418,95 @@ def test_campaigns_carry_the_footer_for_sending_by_hand(client, monkeypatch, env
_prospect(env, "p1", "[email protected]", status="queued")
_campaign(env, "c1", ["p1"])
assert client.get("/api/campaigns").json()[0]["footer"] == ADDRESS + "\n" + LINE
+
+
+# ── Review round 2 ──
+
+SENT = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE
+
+
+async def test_an_html_only_reply_quoting_our_footer_is_not_an_opt_out(state):
+ # Tags become spaces: their words and our quote end up on one line.
+ body = ("Yes, interested. Tuesday works. On Tue, Oct 14, 2026 Harvey wrote: "
+ "A short, plain note. Question? " + ADDRESS + " "
+ "Not interested? Reply &quot;no thanks&quot; and I won&#39;t email again.")
+ status, prompts = await _reply_after_sending(state, body, sent_bodies=[SENT])
+ assert status != "opted_out"
+ assert prompts and all("no thanks" not in p.lower() for p in prompts)
+
+
+async def test_short_wrapped_fragments_of_our_quote_are_ours(state):
+ body = ("Sure, call me.\n\nOn Tue Harvey wrote:\n> A short, plain note. Question?\n"
+ "> Not interested? Reply\n> \"no thanks\"\n> and I won't email again.")
+ status, _ = await _reply_after_sending(state, body, sent_bodies=[SENT])
+ assert status != "opted_out"
+
+
+async def test_outlook_mailto_annotations_dont_hide_our_line(state):
+ line = "To opt out, reply STOP to this email."
+ sent = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + line
+ body = ("Yes please, send pricing.\n\nFrom: Harvey <[email protected]<mailto:[email protected]>>\n"
+ "Sent: Tuesday\n\nA short, plain note. Question?\n" + ADDRESS + "\n"
+ "To opt out, reply STOP to this email<https://x.co/a>.")
+ status, _ = await _reply_after_sending(state, body, sent_bodies=[sent], line=line)
+ assert status != "opted_out"
+
+
+async def test_campaign_text_counts_as_ours_without_an_outbox_row(state):
+ # Instantly sends and hand sends never pass through the Outbox.
+ import json
+ import sqlite3
+ old = 'Reply "unsubscribe" to stop hearing from me.'
+ pid = await seed_prospect(state, status="contacted")
+ with sqlite3.connect(state.db_path) as db:
+ db.execute(
+ "INSERT INTO campaigns (id, name, channel, sequence_json, prospect_ids_json, status) "
+ "VALUES ('c9', 'x', 'email', ?, ?, 'active')",
+ (json.dumps([{"step": 1, "subject": "hi", "delay_days": 0,
+ "body": "Hi {{first_name}}, we help attorney offices grow.\n\n" + old}]),
+ json.dumps([pid])))
+ provider = FakeProvider()
+ provider.inbound = [InboundMessage(
+ provider_id="in1", from_email="[email protected]", subject="Re: hi",
+ body="Yes let's talk.\n\nOn Tue Harvey wrote:\n> Hi Jane, we help attorney offices grow.\n> " + old)]
+ handler = make_handler(state, provider, intent="interested")
+ handler.config.compliance = ComplianceConfig(opt_out_line="Reply no thanks to stop.")
+ handler.brain = RecordingBrain("interested")
+ await handler._run_native()
+ assert (await state.get_prospect(pid)).status != "opted_out"
+ assert handler.brain.prompts # not escalated over our own "attorney"
+
+
+ "Is it month to month, yes or no, thanks",
+], ids=["yes-or-no-comma"])
+async def test_a_question_ending_in_or_no_thanks_is_not_an_opt_out(state, body):
+ status, _ = await _reply(state, body)
+ assert status != "opted_out"
+
+
+ "STOP\n\nSent from my iPhone",
+ "Stop\n\nGet Outlook for iOS",
+ "I'd ask that you do not\ncontact me again.",
+ "Appreciate it, but we're set, so no\nthanks.",
+], ids=["stop-iphone", "stop-outlook-ios", "wrapped-do-not-contact", "wrapped-no-thanks"])
+async def test_opt_outs_with_signatures_or_wrapped_lines_are_caught(state, body):
+ status, prompts = await _reply(state, body)
+ assert status == "opted_out" and prompts == []
+
+
+def test_opt_out_line_must_ask_for_a_reply_harvey_catches():
+ import pydantic
+ for bad in ('Reply "pass" and I\'ll stop.', "To opt out email [email protected]"):
+ with pytest.raises(pydantic.ValidationError):
+ ComplianceConfig(opt_out_line=bad)
+ for good in (LINE, "Reply STOP to opt out.", "Not a fit? Just reply with unsubscribe.",
+ "Reply 'remove me' and you won't hear from me again."):
+ assert ComplianceConfig(opt_out_line=good).opt_out_line == good