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 anything we sent, not just today's footer; phrase-bound opt-outs

Ethan5ae1de727237
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 417e7fc..c1828e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,18 +13,21 @@ minor versions can still change behaviour.
Set `compliance.postal_address` in `harvey.yaml`; `compliance.opt_out_line`
defaults to *Not interested? Reply "no thanks" and I won't email again.*
Both are added when the email sends (native providers and Instantly), never
- to replies, and the Outbox shows them under each draft. Without an address,
- cold email still sends, with the opt-out line, and `harvey run`,
- `harvey status` and the Outbox tab warn until it's set. Based on #13 by
- Camilo Cruz.
+ to replies, and the Outbox shows them under each draft; "Open in Gmail"
+ includes them too. Without an address (or with the opt-out line turned
+ off), cold email still sends, and `harvey run`, `harvey status` and the
+ Outbox tab warn until it's set. The opt-out line must ask for a reply
+ Harvey recognises and can't contain a link. Based on #13 by Camilo Cruz.
### Fixed
- Replies are read without the email they quote. The model, the stored thread
- and the answer see only what the person wrote, so quoted text from Harvey's
- own email can't skew how a reply is understood. Opt-out and escalation words
- are still found anywhere they wrote them, including between or under
- quoted lines; "no thanks" and "no thank you" now count as opt-outs.
+ and the answer get the reply without the quoted email, and any line that
+ repeats what Harvey sent that person is set aside, so Harvey's own words
+ (its footer, or an escalation word like "attorney" in its pitch) don't count
+ as theirs. Opt-out and escalation words the person wrote are still found
+ anywhere, including between or under quoted lines. "No thanks" / "no thank
+ you" as a phrase, and a reply of just "STOP", now count as opt-outs.
- The Sender claims each email right before sending it. A reply, bounce, hand
send or rejection that cancels an approved email while the Sender is working
diff --git a/README.md b/README.md
index 8ef8ea9..c3ce9fa 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 it's written. 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. Replies are read without the quoted email they answer, so quoting Harvey's own footer never counts as an opt-out.
+**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.
**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 2b5d61c..1ef3003 100644
--- a/harvey/agents/handler.py
+++ b/harvey/agents/handler.py
@@ -64,10 +64,39 @@ OPT_OUT_PATTERNS = (
"never contact",
"delete my info",
"delete my data",
- # The wording cold email's footer asks for (compliance.opt_out_line)
- "no thanks",
- "no thank you",
)
+# "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").
+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.
+OWN_TEXT_MIN_CHARS = 20
+
+
+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)
+ 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))
+
+
+def _is_opt_out(keyword_text: str, own_words: str) -> bool:
+ 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
# Phrases that mean a human must take over. Never auto-reply to these.
ESCALATION_PATTERNS = (
@@ -203,28 +232,15 @@ class Handler:
await self.state.mark_reply_processed(reply_uuid)
return True
- def _keyword_text(self, reply_text: str) -> str:
- """The whole reply, flattened for the opt-out and escalation checks.
-
- Quote markers are dropped rather than the quoted lines, so an opt-out
- written anywhere is found. What we sent ourselves (the postal address
- and opt-out line, which say "no thanks") is removed, however the
- client re-wrapped or re-quoted it, so quoting it isn't an opt-out.
- """
- def flat(text: str) -> str:
- text = re.sub(r"^[ \t>]+", "", html.unescape(text or ""), flags=re.MULTILINE)
- text = (text.replace("\u201c", '"').replace("\u201d", '"')
- .replace("\u2018", "'").replace("\u2019", "'"))
- return " ".join(text.lower().split())
-
- text = flat(reply_text)
+ async def _our_text(self, prospect) -> str:
+ """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)."""
compliance = compliance_of(self.config)
- for ours in (compliance.opt_out_line, DEFAULT_OPT_OUT_LINE,
- compliance.postal_address):
- ours = flat(ours)
- if ours:
- text = text.replace(ours, " ")
- return text
+ 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)
async def _process_reply(
self,
@@ -235,19 +251,23 @@ class Handler:
reply_meta: dict | None = None,
):
"""Classify, record, and respond to a single reply."""
- # The keyword checks below look at everything they wrote, even under
- # or between quoted lines, minus our own footer. Everything else (the
- # model, the stored thread, the answer) reads only their reply, not
- # the quoted email it answers.
- keyword_text = self._keyword_text(reply_text)
- reply_text = strip_quoted_reply(reply_text) or reply_text
-
# Find the prospect by email (indexed lookup)
prospect = await self.state.get_prospect_by_email(lead_email)
if not prospect:
logger.warning(f"Handler: No prospect found for {lead_email}")
return
+ # Their words, without what we sent them. The keyword checks below
+ # read every line they wrote, even under or between quoted lines;
+ # the model, the stored thread and the answer read their reply
+ # 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"))
+ stripped = strip_quoted_reply(reply_text) or reply_text
+ reply_text = _drop_our_text(stripped, ours).strip() or stripped
+
# Update prospect status + stop-on-reply: a human answered, so every
# queued sequence email for them is now wrong to send.
await self.state.update_prospect_status(prospect.id, "replied")
@@ -263,7 +283,7 @@ class Handler:
# 1. Classify intent. Hard keyword checks run FIRST and override
# the LLM — opt-outs and legal threats must never be missed.
- if any(p in keyword_text for p in OPT_OUT_PATTERNS):
+ if _is_opt_out(keyword_text, reply_text):
intent = "unsubscribe"
elif any(p in keyword_text for p in ESCALATION_PATTERNS):
intent = "escalate"
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index 18ed26f..4f6707b 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -450,10 +450,12 @@ class Sender:
def _with_footer(self, body: str) -> str:
"""A cold email as it leaves: the postal address and opt-out line
underneath (CAN-SPAM). Added at send time, so a changed address
- applies to mail already queued; never added twice."""
- footer = "\n".join(
- line for line in compliance_footer_lines(self.config) if line not in body)
- return body.rstrip() + "\n\n" + footer if footer else body
+ applies to mail already queued; not added again when the body already
+ ends with it."""
+ footer = "\n".join(compliance_footer_lines(self.config))
+ if not footer or body.rstrip().endswith(footer):
+ return body
+ return body.rstrip() + "\n\n" + footer
def _outgoing_body(self, item: dict) -> str:
"""The exact body that goes out: cold email gets the footer, replies don't."""
diff --git a/harvey/config.py b/harvey/config.py
index 227b6fd..e1ce364 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -208,6 +208,9 @@ 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.
+OPT_OUT_WORDS = ("no thanks", "no thank you", "unsubscribe", "stop", "remove me",
+ "opt out", "opt-out")
class ComplianceConfig(BaseModel):
@@ -216,10 +219,34 @@ class ComplianceConfig(BaseModel):
# CAN-SPAM requires a postal address you receive mail at (a street
# address, PO box or virtual mailbox) and a working way to opt out.
postal_address: str = ""
- # Keep wording Harvey recognises as an opt-out ("no thanks",
- # "unsubscribe", "remove me"). "" leaves it off.
+ # Must ask for wording Harvey recognises as an opt-out (OPT_OUT_WORDS).
+ # "" leaves it off (and harvey warns).
opt_out_line: str = DEFAULT_OPT_OUT_LINE
+ @field_validator("postal_address", "opt_out_line", mode="before")
+ @classmethod
+ def _blank_is_empty(cls, v):
+ return "" if v is None else v
+
+ @field_validator("opt_out_line")
+ @classmethod
+ def _recognisable_opt_out(cls, v: str) -> str:
+ v = v.strip()
+ lowered = v.lower()
+ if not v:
+ return v
+ if "http" in lowered or "www." in lowered or "click" in lowered:
+ raise ValueError(
+ "opt_out_line can't contain a link: 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):
+ 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]) + "."
+ )
+ return v
+
def compliance_of(config) -> ComplianceConfig:
"""The compliance section, or the defaults when a config has none."""
@@ -240,13 +267,19 @@ def compliance_notice(config) -> str:
email = getattr(getattr(config, "channels", None), "email", None)
if not getattr(email, "enabled", False):
return ""
- if compliance_of(config).postal_address.strip():
+ compliance = compliance_of(config)
+ missing = []
+ if not compliance.postal_address.strip():
+ missing.append("a postal address (compliance.postal_address: a street "
+ "address, PO box or virtual mailbox)")
+ if not compliance.opt_out_line.strip():
+ missing.append("a way to opt out (compliance.opt_out_line)")
+ if not missing:
return ""
return (
- "Cold emails are going out without a postal address. US law (CAN-SPAM) "
- "requires one in every cold email. Set compliance.postal_address in "
- "harvey.yaml (or harvey.local.yaml if you trained Harvey) to a street "
- "address, PO box or virtual mailbox."
+ "Cold emails are going out without " + " or ".join(missing) + ". US law "
+ "(CAN-SPAM) requires both in every cold email. Set them in harvey.yaml "
+ "(or harvey.local.yaml if you trained Harvey)."
)
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index d1a3a0d..1c2537d 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -923,7 +923,11 @@ async def outbox_edit(item_id: str, request: Request):
# instead of failing quietly at send time. Content rules only: the
# recipient isn't something an edit can change.
from harvey.gate import pre_send_check
- gate = pre_send_check("[email protected]", subject, text)
+ checked = text
+ footer = _compliance_view()["footer"]
+ if item.get("kind") == "sequence" and footer and not text.rstrip().endswith(footer):
+ checked = text.rstrip() + "\n\n" + footer # as the Sender will send it
+ gate = pre_send_check("[email protected]", subject, checked)
if not gate:
return JSONResponse({"success": False,
"message": "The sender would have blocked this: "
@@ -1177,6 +1181,7 @@ async def get_campaigns():
rows = await query_db("SELECT * FROM campaigns ORDER BY created_at DESC LIMIT 100")
harvey_sends = _harvey_can_send()
send_as = "" if harvey_sends else _send_as()
+ footer = _compliance_view()["footer"]
committed = await _harvey_committed_ids()
hand_sent = await _hand_sent_ids()
for row in rows:
@@ -1197,6 +1202,8 @@ async def get_campaigns():
tuple(ids),
) if ids else []
row["send_as"] = send_as
+ # A cold email sent by hand needs the same footer Harvey adds.
+ row["footer"] = footer
for r in row["recipients"]:
r["sent_by_hand"] = r["id"] in hand_sent
# "I already emailed them": always recordable before Harvey commits.
diff --git a/harvey/integrations/mail_provider.py b/harvey/integrations/mail_provider.py
index 3c0ea95..5f62d54 100644
--- a/harvey/integrations/mail_provider.py
+++ b/harvey/integrations/mail_provider.py
@@ -57,37 +57,53 @@ BOUNCE_SUBJECTS = (
# Where a reply starts quoting the email it answers. Clients wrap the
# "On ... wrote:" line, so one line break is allowed inside it.
-_QUOTE_HEADERS = (
+# After these, the quoted email is usually marked with ">", so any unmarked
+# lines under them are the person's own inline answers.
+_ATTRIBUTION_HEADERS = (
# Gmail / Apple Mail, and the Spanish, German and French equivalents
re.compile(r"^[ \t]*On\b[^\n]{0,300}(?:\n[^\n]{0,300})?\bwrote:[ \t]*$", re.MULTILINE),
re.compile(r"^[ \t]*El\b[^\n]{0,300}(?:\n[^\n]{0,300})?\bescribi[oó]:[ \t]*$", re.MULTILINE),
re.compile(r"^[ \t]*Am\b[^\n]{0,300}(?:\n[^\n]{0,300})?\bschrieb[^\n]{0,100}:[ \t]*$", re.MULTILINE),
re.compile(r"^[ \t]*Le\b[^\n]{0,300}(?:\n[^\n]{0,300})?\ba [ée]crit[ \t]*:[ \t]*$", re.MULTILINE),
- # Outlook
+)
+# Outlook-style blocks: the quoted email follows unmarked, so everything
+# from here on is cut.
+_BLOCK_HEADERS = (
re.compile(r"^[ \t]*-{2,}[ \t]*Original Message[ \t]*-{2,}", re.MULTILINE | re.IGNORECASE),
- re.compile(r"^[ \t]*From:[^\n]*\n[ \t]*(?:Sent|Date):", re.MULTILINE),
- re.compile(r"^[ \t]*_{10,}[ \t]*$", re.MULTILINE),
+ re.compile(r"^[ \t]*(?:_{10,}[ \t]*\n[ \t]*)?(?:From|Von|De):[^\n]*\n[ \t]*"
+ r"(?:Sent|Date|Gesendet|Enviado|Envoy[ée]):", re.MULTILINE),
)
+def _unquoted(text: str) -> str:
+ return "\n".join(l for l in text.split("\n") if not l.lstrip().startswith(">"))
+
+
def strip_quoted_reply(body: str) -> str:
"""What the sender wrote, without the email they're answering.
- ">" lines are dropped wherever they are, so answers written between
- quoted lines are kept; everything from the first quote header ("On ...
- wrote:", Outlook's From:/Sent: block) is cut. When that would leave
- nothing (they answered under the header), their unquoted lines are kept.
- Used for reading a reply; opt-out detection looks wider (see handler).
+ ">" lines are dropped wherever they are. An "On ... wrote:" line is
+ dropped too, and the unmarked lines under it are kept when the quote
+ below it is ">"-marked (inline answers); when it isn't, everything from
+ it on is the quote. An Outlook From:/Sent: block cuts the rest. Never
+ returns nothing for a non-empty reply. The Handler also drops any line
+ that repeats what Harvey sent, which catches quotes no header marks.
"""
text = (body or "").replace("\r\n", "\n")
- text = "\n".join(
- line for line in text.split("\n") if not line.lstrip().startswith(">"))
cut = len(text)
- for pattern in _QUOTE_HEADERS:
+ for pattern in _BLOCK_HEADERS:
m = pattern.search(text)
if m and m.start() < cut:
cut = m.start()
- kept = text[:cut].strip() or text.strip()
+ head, tail = text[:cut], ""
+ for pattern in _ATTRIBUTION_HEADERS:
+ m = pattern.search(head)
+ if not m:
+ continue
+ below = head[m.end():]
+ marked = any(l.lstrip().startswith(">") for l in below.split("\n"))
+ head = head[:m.start()] + ("\n" + below if marked else "")
+ kept = _unquoted(head).strip() or _unquoted(text).strip()
return re.sub(r"\n{3,}", "\n\n", kept)
diff --git a/harvey/state.py b/harvey/state.py
index 44448fd..f4040f6 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -912,6 +912,17 @@ 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 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 ?",
+ (prospect_id, int(limit)),
+ ) as cursor:
+ return [r[0] or "" for r in await cursor.fetchall()]
+
async def get_outbox_item(self, item_id: str) -> dict | None:
async with self._connect() as db:
db.row_factory = aiosqlite.Row
diff --git a/harvey/web/app.js b/harvey/web/app.js
index 95142f6..d1e8be9 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -1377,9 +1377,9 @@ function renderDesk(items, i) {
: '<div class="subject">' + escHtml(cur.subject || '(no subject)') + '</div>' +
'<div class="body">' + escHtml(cur.body) + '</div>';
// Cold email leaves with the footer underneath; show it as it will go out.
- // Lines already in the body aren't added again, as in the Sender.
- const added = cur.kind === 'sequence'
- ? _desk.footer.split('\n').filter(l => l && !(cur.body || '').includes(l)).join('\n') : '';
+ // Not added again when the body already ends with it, as in the Sender.
+ const added = cur.kind === 'sequence' && !(cur.body || '').trimEnd().endsWith(_desk.footer)
+ ? _desk.footer : '';
const footer = added
? '<div class="desk-footer" title="Added when it sends (compliance in harvey.yaml)">' +
escHtml(added) + '</div>' : '';
@@ -1625,13 +1625,15 @@ async function openInGmail(ci, si, ri) {
const step = c && (c.sequence || [])[si];
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 : '');
// 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' +
(c.send_as ? '&authuser=' + encodeURIComponent(c.send_as) : '') +
'&to=' + encodeURIComponent(r.email) +
'&su=' + encodeURIComponent(fillMergeVars(step.subject, r)) +
- '&body=' + encodeURIComponent(fillMergeVars(step.body, r));
+ '&body=' + encodeURIComponent(body);
const left = /\{\{\s*\w+\s*\}\}/.test(fillMergeVars(step.subject, r) + fillMergeVars(step.body, r));
// No 'noopener' feature string: with it window.open always returns null,
// so a blocked pop-up could not be told apart from a successful one. The
diff --git a/tests/test_compliance_footer.py b/tests/test_compliance_footer.py
index 4d85e9d..7e10305 100644
--- a/tests/test_compliance_footer.py
+++ b/tests/test_compliance_footer.py
@@ -268,3 +268,153 @@ def test_an_unreadable_config_still_shows_the_outbox(client, monkeypatch):
monkeypatch.setattr(harvey.config, "load_config", broken)
data = client.get("/api/outbox").json()
assert data["footer"] == "" and "pending" in data
+
+
+# ── Review round 1: false opt-outs, missed opt-outs ──
+
+async def _reply_after_sending(state, body, sent_bodies=(), intent="interested",
+ line=LINE):
+ """A reply from someone Harvey already emailed `sent_bodies`."""
+ pid = await seed_prospect(state, status="contacted")
+ for n, sent in enumerate(sent_bodies, start=1):
+ oid = await state.add_outbox_item(
+ prospect_id=pid, to_email="[email protected]", subject="hello there",
+ body=sent, send_at=_now_iso(), status="approved", campaign_id="c1", step=n)
+ await state.update_outbox_item(oid, status="sent", sent_at=_now_iso())
+ provider = FakeProvider()
+ provider.inbound = [InboundMessage(
+ provider_id="in1", from_email="[email protected]", subject="Re: hello there", body=body)]
+ handler = make_handler(state, provider, intent=intent)
+ handler.config.compliance = ComplianceConfig(postal_address=ADDRESS, opt_out_line=line)
+ handler.brain = RecordingBrain(intent)
+ await handler._run_native()
+ return (await state.get_prospect(pid)).status, handler.brain.prompts
+
+
+ "Do you offer a monthly plan, yes or no\nThanks,\nBob",
+ "Sounds good, call me.\n\nMario Bruno\nThanks for reaching out",
+ "Interested! Can we talk next month? No Thanksgiving week though.",
+], ids=["yes-or-no", "signature", "thanksgiving"])
+async def test_no_thanks_only_counts_as_the_phrase_itself(state, body):
+ status, _ = await _reply(state, body)
+ assert status != "opted_out"
+
+
[email protected]("body", ["No, thanks.", "STOP", "Stop.", " unsubscribe "],
+ ids=["comma", "stop", "stop-dot", "bare-unsubscribe"])
+async def test_short_opt_out_replies_are_caught_without_the_model(state, body):
+ status, prompts = await _reply(state, body)
+ assert status == "opted_out" and prompts == []
+
+
+async def test_quoting_an_old_opt_out_line_is_not_an_opt_out(state):
+ # Emails went out with a custom line; the line was changed afterwards.
+ old = 'Reply "unsubscribe" to stop hearing from me.'
+ sent = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + old
+ status, _ = await _reply_after_sending(
+ state, "Yes, let's talk Tuesday.\n\nOn Tue Harvey wrote:\n> " + sent.replace("\n", "\n> "),
+ sent_bodies=[sent], line="Not for you? Reply no thanks.")
+ assert status != "opted_out"
+
+
+# Dutch Outlook: a header strip_quoted_reply doesn't know.
+DUTCH_OUTLOOK = (
+ "Klinkt goed, stuur me de prijzen.\n\n"
+ "Van: Harvey <[email protected]>\nVerzonden: dinsdag 14 oktober 2026 15:02\n\n"
+ "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE
+)
+
+
+async def test_our_quoted_email_never_reaches_the_model_even_unrecognised(state):
+ sent = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE
+ status, prompts = await _reply_after_sending(state, DUTCH_OUTLOOK, sent_bodies=[sent])
+ assert status != "opted_out"
+ assert prompts and all("no thanks" not in p.lower() for p in prompts)
+ assert any("Klinkt goed" in p for p in prompts)
+
+
+async def test_a_footer_cut_off_by_the_length_limit_is_not_an_opt_out(state):
+ sent = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE
+ body = ("Interested, tell me more.\n\nOn Tue Harvey wrote:\n> A short, plain note. Question?\n> "
+ + ADDRESS + '\n> Not interested? Reply "no thanks"') # truncated here
+ status, _ = await _reply_after_sending(state, body, sent_bodies=[sent])
+ assert status != "opted_out"
+
+
+async def test_escalation_words_in_our_own_quoted_email_dont_escalate(state):
+ sent = "We help attorney offices fill their calendar. Worth a chat?"
+ status, prompts = await _reply_after_sending(
+ state, "Yes please.\n\nOn Tue Harvey wrote:\n> " + sent, sent_bodies=[sent])
+ assert prompts # classified by the model, not escalated by keyword
+
+
+def test_inline_answers_under_a_quote_header_are_kept():
+ text = strip_quoted_reply(
+ "Answers inline below.\n\nOn Tue, Oct 14 Harvey wrote:\n"
+ "> Would a call work?\nYes, Thursday 2pm.\n> CRM?\nHubSpot.")
+ assert "Thursday 2pm" in text and "HubSpot" in text and "Would a call" not in text
+
+
+def test_an_underscore_line_of_their_own_is_not_a_quote():
+ assert "pricing" in strip_quoted_reply("Hi Ethan,\n____________\nSend pricing please.")
+
+
+# ── Review round 1: the footer itself ──
+
+async def test_a_short_address_mentioned_in_the_body_still_gets_the_footer(state):
+ pid = await seed_prospect(state, status="contacted")
+ await _approved(state, pid, body="Saw you're in Austin, TX. Question?")
+ provider = FakeProvider()
+ await _sender(state, provider, address="Austin, TX")._drain_due()
+ assert provider.sent[0]["body"].endswith("\n\nAustin, TX\n" + LINE)
+
+
+def test_opt_out_line_must_be_recognisable_and_link_free():
+ import pydantic
+ for bad in ("To unsubscribe, visit https://acme.com/u", "Click here to leave",
+ "Thanks for reading!"):
+ with pytest.raises(pydantic.ValidationError):
+ ComplianceConfig(opt_out_line=bad)
+ assert ComplianceConfig(opt_out_line="Reply STOP to opt out.").opt_out_line
+ assert ComplianceConfig(opt_out_line="").opt_out_line == ""
+ # Left blank in YAML (null) means empty, not a crash.
+ assert ComplianceConfig(postal_address=None, opt_out_line=None).opt_out_line == ""
+
+
+def test_no_opt_out_line_is_warned_about_too():
+ cfg = SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(enabled=True)),
+ compliance=ComplianceConfig(postal_address=ADDRESS, opt_out_line=""))
+ assert "opt_out_line" in compliance_notice(cfg)
+
+
+def test_an_edit_the_footer_would_push_over_the_limit_is_refused(client, monkeypatch, env):
+ import sqlite3
+ import harvey.config
+ monkeypatch.setattr(harvey.config, "load_config", lambda: SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(enabled=True)),
+ compliance=ComplianceConfig(postal_address=ADDRESS)))
+ with sqlite3.connect(env["db"]) as db:
+ db.execute("INSERT INTO outbox (id, prospect_id, campaign_id, step, kind, to_email, "
+ "subject, body, send_at, status) VALUES ('o1', 'p1', 'c1', 1, 'sequence', "
+ "'[email protected]', 's', 'b', '2026-01-01T00:00:00', 'pending_review')")
+ body = " ".join(["word"] * 215) # fits alone, not with the footer
+ r = client.post("/api/outbox/o1/edit", json={"subject": "s", "body": body})
+ assert r.status_code == 400 and "too long" in r.json()["message"]
+
+
+def test_campaigns_carry_the_footer_for_sending_by_hand(client, monkeypatch, env):
+ import harvey.config
+ monkeypatch.setattr(harvey.config, "load_config", lambda: _config(ADDRESS))
+ from tests.test_dashboard_manual_send import _campaign, _prospect
+ _prospect(env, "p1", "[email protected]", status="queued")
+ _campaign(env, "c1", ["p1"])
+ assert client.get("/api/campaigns").json()[0]["footer"] == ADDRESS + "\n" + LINE