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.

Postal address and opt-out line under every cold email; read replies without the quote

Ethan76f08e0ed9ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc14812..417e7fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,8 +7,25 @@ minor versions can still change behaviour.
## [Unreleased]
+### Added
+
+- **A postal address and opt-out line under every cold email** (CAN-SPAM).
+ 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.
+
### 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.
+
- 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
through its queue now stops it, instead of the Sender sending its earlier
diff --git a/README.md b/README.md
index b9e54cb..8ef8ea9 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: Harvey treats any opt-out wording as immediate and permanent. Your physical mailing address in the footer — configure this before your first campaign.
+**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.
**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.yaml b/harvey.yaml
index 9929ad8..9eeeef2 100644
--- a/harvey.yaml
+++ b/harvey.yaml
@@ -74,6 +74,12 @@ usage:
# are in one country, set prospect_country: Precleared uses it only when it can't
# tell the country from the address, company records or the company's website.
compliance:
+ # Added under every cold email (never replies). US law (CAN-SPAM) requires a
+ # postal address you receive mail at: a street address, PO box or virtual
+ # mailbox. Until it's set, cold email still sends, with a warning.
+ postal_address: ""
+ # Keep wording Harvey recognises as an opt-out ("no thanks", "unsubscribe").
+ opt_out_line: 'Not interested? Reply "no thanks" and I won''t email again.'
precleared:
enabled: false
sender_country: "" # GB or US: where your business is based
diff --git a/harvey/agents/handler.py b/harvey/agents/handler.py
index cdb17cb..2b5d61c 100644
--- a/harvey/agents/handler.py
+++ b/harvey/agents/handler.py
@@ -7,14 +7,20 @@ threshold — flips the global kill switch so a bad list can't torch the
sending domain while nobody's watching.
"""
+import html
import logging
+import re
from datetime import datetime, timezone
from harvey.brain import Brain, BrainUnavailable
-from harvey.config import HarveyConfig, EnvConfig, legacy_sending_held
+from harvey.config import (
+ DEFAULT_OPT_OUT_LINE, HarveyConfig, EnvConfig, compliance_of, legacy_sending_held,
+)
from harvey.humanize import humanize, humanizer_enabled
from harvey.integrations.instantly import InstantlyClient
-from harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_provider
+from harvey.integrations.mail_provider import (
+ NATIVE_PROVIDERS, get_mail_provider, strip_quoted_reply,
+)
from harvey.models.conversation import Conversation, Message
from harvey.state import StateManager
@@ -58,6 +64,9 @@ 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",
)
# Phrases that mean a human must take over. Never auto-reply to these.
@@ -194,6 +203,29 @@ 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)
+ 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
+
async def _process_reply(
self,
lead_email: str,
@@ -203,6 +235,13 @@ 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:
@@ -224,10 +263,9 @@ class Handler:
# 1. Classify intent. Hard keyword checks run FIRST and override
# the LLM — opt-outs and legal threats must never be missed.
- text_lower = reply_text.lower()
- if any(p in text_lower for p in OPT_OUT_PATTERNS):
+ if any(p in keyword_text for p in OPT_OUT_PATTERNS):
intent = "unsubscribe"
- elif any(p in text_lower for p in ESCALATION_PATTERNS):
+ elif any(p in keyword_text for p in ESCALATION_PATTERNS):
intent = "escalate"
else:
intent = await self._classify_intent(reply_text, prospect)
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index 7ced9f2..18ed26f 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -17,7 +17,9 @@ import re
from datetime import date, datetime, timedelta, timezone
from harvey.brain import Brain
-from harvey.config import HarveyConfig, EnvConfig
+from harvey.config import (
+ HarveyConfig, EnvConfig, compliance_footer_lines, compliance_notice, compliance_of,
+)
from harvey.gate import pre_send_check
from harvey.integrations.instantly import InstantlyClient
from harvey.integrations.mail_provider import NATIVE_PROVIDERS, get_mail_provider
@@ -173,7 +175,7 @@ class Sender:
sequences = [
{
"subject": step.subject.strip(),
- "body": step.body.strip(),
+ "body": self._with_footer(step.body.strip()),
"wait": step.delay_days,
}
for step in campaign.sequence
@@ -445,6 +447,20 @@ class Sender:
details={"campaign": campaign.name, "staged": staged, "mode": mode},
)
+ 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
+
+ def _outgoing_body(self, item: dict) -> str:
+ """The exact body that goes out: cold email gets the footer, replies don't."""
+ if item["kind"] == "sequence":
+ return self._with_footer(item["body"])
+ return item["body"]
+
async def _blocked(self, item: dict, prospect, allow_risky: bool) -> tuple[str, str] | None:
"""Why this email must not go out, as (status, error), or None."""
if prospect is None:
@@ -461,8 +477,9 @@ class Sender:
if item["step"] == 1 and prospect.status == "contacted":
return "cancelled", "already contacted"
gate = pre_send_check(
- item["to_email"], item["subject"], item["body"],
+ item["to_email"], item["subject"], self._outgoing_body(item),
prospect=prospect, allow_risky=allow_risky, kind=item["kind"],
+ postal_address=compliance_of(self.config).postal_address,
)
if not gate:
logger.warning(
@@ -513,6 +530,7 @@ class Sender:
allow_risky = getattr(self.config.channels.email, "send_to_risky", False)
sent = 0
+ sent_cold = 0
# Set when Precleared can't be asked (allowance used up, network):
# cold emails wait for a later cycle, replies still go out.
compliance_paused = False
@@ -571,9 +589,10 @@ class Sender:
item["id"], status=blocked[0], error=blocked[1])
continue
+ body = self._outgoing_body(item)
try:
result = await self.provider.send_email(
- item["to_email"], item["subject"], item["body"],
+ item["to_email"], item["subject"], body,
thread_ref=item.get("thread_ref", ""),
in_reply_to=item.get("in_reply_to", ""),
)
@@ -592,9 +611,11 @@ class Sender:
continue
sent += 1
+ if item["kind"] == "sequence":
+ sent_cold += 1
now_iso = datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
await self.state.update_outbox_item(
- item["id"], status="sent", sent_at=now_iso,
+ item["id"], status="sent", sent_at=now_iso, body=body,
message_id=result.message_id, thread_ref=result.thread_ref,
)
if prospect.status in ("new", "queued"):
@@ -634,6 +655,10 @@ class Sender:
if self.send_pacing and sent < budget:
await asyncio.sleep(random.uniform(*SEND_JITTER_SECONDS))
+ if sent_cold:
+ notice = compliance_notice(self.config)
+ if notice:
+ logger.warning(f"Sender: {notice}")
if sent:
logger.info(f"Sender: {sent} email(s) sent this cycle "
f"({sent_today + sent}/{max_daily} today).")
diff --git a/harvey/agents/writer.py b/harvey/agents/writer.py
index e4f34e6..da34abe 100644
--- a/harvey/agents/writer.py
+++ b/harvey/agents/writer.py
@@ -295,6 +295,7 @@ Requirements:
question. No pitch, no product name.
- Write the actual text (no merge variables — you know their name/company).
- Subject: lowercase, 2-5 words.
+- No postal address, unsubscribe or opt-out line: Harvey adds them when it sends.
- Follow every STRICT EMAIL RULE above.
Return ONLY JSON: {{"subject": "...", "body": "..."}}"""
@@ -370,6 +371,7 @@ Requirements:
{merge_rule}
- Never be pushy or salesy. Be consultative and value-driven.
- Subject lines: lowercase, 2-5 words.
+- No postal address, unsubscribe or opt-out line: Harvey adds them when it sends.
- Follow every rule in the STRICT EMAIL RULES above. No exceptions.
Return ONLY a JSON array (no markdown fences, no commentary):
diff --git a/harvey/cli.py b/harvey/cli.py
index a79d7f8..c46361f 100644
--- a/harvey/cli.py
+++ b/harvey/cli.py
@@ -215,13 +215,15 @@ def cmd_status(args):
by_provider = summary.get("usage_today_by_provider", {})
print(f" Claude calls today: {by_provider.get('claude', summary['usage_today'])}")
print(f" Codex calls today: {by_provider.get('codex', 0)}")
- from harvey.config import load_config, sending_notice
+ from harvey.config import compliance_notice, load_config, sending_notice
try:
- notice = sending_notice(load_config())
+ loaded = load_config()
+ notice = sending_notice(loaded)
+ address_notice = compliance_notice(loaded)
except Exception:
# Status must still print when harvey.yaml is broken; that's
# when people run it. The --check path reports config errors.
- notice = ""
+ notice = address_notice = ""
from harvey.main import unusable_backlog_notice
backlog = unusable_backlog_notice(summary)
if backlog:
@@ -232,6 +234,10 @@ def cmd_status(args):
print(" Sending: HELD")
print(textwrap.fill(notice, width=72, initial_indent=" ",
subsequent_indent=" "))
+ if address_notice:
+ print(" Postal address: MISSING")
+ print(textwrap.fill(address_notice, width=72, initial_indent=" ",
+ subsequent_indent=" "))
from harvey.brain import BRAIN_STATUS_KEY, Brain, active_brain_status
from harvey.config import ConfigError, load_brain_config
try:
diff --git a/harvey/config.py b/harvey/config.py
index 3822555..227b6fd 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -207,8 +207,47 @@ class PreclearedConfig(BaseModel):
return self
+DEFAULT_OPT_OUT_LINE = 'Not interested? Reply "no thanks" and I won\'t email again.'
+
+
class ComplianceConfig(BaseModel):
precleared: PreclearedConfig = PreclearedConfig()
+ # Added under every cold (sequence) email at send time; never to replies.
+ # 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.
+ opt_out_line: str = DEFAULT_OPT_OUT_LINE
+
+
+def compliance_of(config) -> ComplianceConfig:
+ """The compliance section, or the defaults when a config has none."""
+ found = getattr(config, "compliance", None)
+ return found if isinstance(found, ComplianceConfig) else ComplianceConfig()
+
+
+def compliance_footer_lines(config) -> list[str]:
+ """The lines added under every cold email: address, then opt-out line."""
+ compliance = compliance_of(config)
+ return [line for line in (compliance.postal_address.strip(),
+ compliance.opt_out_line.strip()) if line]
+
+
+def compliance_notice(config) -> str:
+ """A plain-language warning when cold email goes out without a postal
+ address, or "". Sending isn't held for it: this is the nudge."""
+ email = getattr(getattr(config, "channels", None), "email", None)
+ if not getattr(email, "enabled", False):
+ return ""
+ if compliance_of(config).postal_address.strip():
+ 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."
+ )
class QuietHoursConfig(BaseModel):
diff --git a/harvey/dashboard.py b/harvey/dashboard.py
index 239d158..d1a3a0d 100644
--- a/harvey/dashboard.py
+++ b/harvey/dashboard.py
@@ -850,6 +850,7 @@ async def get_outbox_api():
# isn't running.
await state.fail_stale_sending_outbox()
return {
+ **_compliance_view(),
"paused": await state.get_setting("sending_paused"),
"pending": await _with_context(
await state.get_outbox(status="pending_review", limit=100)),
@@ -979,6 +980,18 @@ def _send_as() -> str:
return ""
+def _compliance_view() -> dict:
+ """What the Sender adds under each cold email, so a reviewer sees the
+ email as it will leave, and the warning when the address is missing."""
+ try:
+ from harvey.config import compliance_footer_lines, compliance_notice, load_config
+ config = load_config()
+ return {"footer": "\n".join(compliance_footer_lines(config)),
+ "compliance_notice": compliance_notice(config)}
+ except Exception:
+ return {"footer": "", "compliance_notice": ""}
+
+
async def _harvey_committed_ids() -> set[str]:
"""Everyone Harvey has approved or sent mail for (Outbox or Instantly).
diff --git a/harvey/gate.py b/harvey/gate.py
index 319f4ed..81ca1df 100644
--- a/harvey/gate.py
+++ b/harvey/gate.py
@@ -53,8 +53,12 @@ def pre_send_check(
prospect=None,
allow_risky: bool = False,
kind: str = "sequence",
+ postal_address: str = "",
) -> GateResult:
- """Run every deterministic check. Returns ok=False with reasons on any hit."""
+ """Run every deterministic check. Returns ok=False with reasons on any hit.
+
+ postal_address: when set, a cold (sequence) email must carry it (CAN-SPAM).
+ """
reasons: list[str] = []
subject = (subject or "").strip()
body = (body or "").strip()
@@ -100,6 +104,9 @@ def pre_send_check(
if len(links) > MAX_LINKS:
reasons.append(f"too many links ({len(links)} > {MAX_LINKS})")
+ if kind == "sequence" and postal_address.strip() and postal_address.strip() not in body:
+ reasons.append("postal address footer missing")
+
# No HTML — Harvey sends plain text only
if re.search(r"<\s*(html|body|div|table|img|a)\b", body, re.IGNORECASE):
reasons.append("HTML markup in body (plain text only)")
diff --git a/harvey/integrations/mail_provider.py b/harvey/integrations/mail_provider.py
index 24b3f7c..3c0ea95 100644
--- a/harvey/integrations/mail_provider.py
+++ b/harvey/integrations/mail_provider.py
@@ -16,6 +16,7 @@ it isn't a MailProvider because Instantly owns sequencing/sending itself.
"""
import logging
+import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@@ -54,6 +55,42 @@ 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 = (
+ # 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
+ 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),
+)
+
+
+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).
+ """
+ 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:
+ m = pattern.search(text)
+ if m and m.start() < cut:
+ cut = m.start()
+ kept = text[:cut].strip() or text.strip()
+ return re.sub(r"\n{3,}", "\n\n", kept)
+
+
def looks_like_bounce(from_email: str, subject: str) -> bool:
f = (from_email or "").lower()
s = (subject or "").lower()
diff --git a/harvey/main.py b/harvey/main.py
index 3d7d139..cf1b0dd 100644
--- a/harvey/main.py
+++ b/harvey/main.py
@@ -11,6 +11,7 @@ import pytz
from harvey.brain import Brain
from harvey.config import (
ConfigError, load_config, load_env, HarveyConfig, legacy_sending_held, sending_notice,
+ compliance_notice,
)
from harvey.pipeline import run_profile_stage
from harvey.state import StateManager
@@ -220,11 +221,11 @@ async def heartbeat(stop_event: asyncio.Event | None = None):
+ (f" ({brain.model})" if brain.model else "")
+ ". Change brain.provider in harvey.yaml to switch."
)
- notice = sending_notice(config)
- if notice:
- logger.warning("=" * 60)
- logger.warning(notice)
- logger.warning("=" * 60)
+ for notice in (sending_notice(config), compliance_notice(config)):
+ if notice:
+ logger.warning("=" * 60)
+ logger.warning(notice)
+ logger.warning("=" * 60)
await state.init_db()
logger.info("Database initialized.")
diff --git a/harvey/web/app.css b/harvey/web/app.css
index 2d4d3e9..fb28050 100644
--- a/harvey/web/app.css
+++ b/harvey/web/app.css
@@ -428,6 +428,10 @@ td a:hover { text-decoration: underline; }
font-size: 14.5px; line-height: 1.75; white-space: pre-wrap; max-width: 64ch;
padding: 18px 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border);
}
+.desk-footer {
+ font-size: 13px; line-height: 1.6; white-space: pre-wrap; max-width: 64ch;
+ color: var(--text-3); padding: 10px 0; border-bottom: 1px solid var(--border);
+}
.desk-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }
.desk-context {
display: grid; grid-template-columns: 110px minmax(0,1fr); gap: 6px 14px;
diff --git a/harvey/web/app.js b/harvey/web/app.js
index b97d9c2..95142f6 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -1250,6 +1250,7 @@ async function loadOutbox() {
const pending = data.pending || [];
_desk.items = pending;
+ _desk.footer = data.footer || '';
// Keep the desk on the draft being edited even if the list shifted.
const editingAt = _desk.editing ? pending.findIndex(p => p.id === _desk.editing) : -1;
if (editingAt >= 0) _desk.i = editingAt;
@@ -1278,6 +1279,12 @@ async function loadOutbox() {
'<p style="color:var(--text-2);font-size:13px">' + escHtml(data.paused) +
'. Approved mail stays queued until you resume.</p></div>'
: '';
+ if (data.compliance_notice) {
+ banner.innerHTML +=
+ '<div class="card" style="border-color:var(--s-wait-line);background:var(--s-wait-bg);margin-bottom:16px">' +
+ '<h2 style="color:var(--s-wait)">Add your postal address</h2>' +
+ '<p style="color:var(--text-2);font-size:13px">' + escHtml(data.compliance_notice) + '</p></div>';
+ }
desk.innerHTML = pending.length ? renderDesk(pending, _desk.i) :
'<div class="card">' + emptyState('&#10003;', 'Nothing to review',
@@ -1369,6 +1376,13 @@ function renderDesk(items, i) {
escHtml(unsaved.body) + '</textarea>'
: '<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') : '';
+ const footer = added
+ ? '<div class="desk-footer" title="Added when it sends (compliance in harvey.yaml)">' +
+ escHtml(added) + '</div>' : '';
const actions = editing
? '<button class="btn btn-primary" onclick="deskSave(\'' + cur.id + '\')">Save</button>' +
'<button class="btn btn-secondary" onclick="deskEdit(null)">Cancel</button>'
@@ -1386,7 +1400,7 @@ function renderDesk(items, i) {
cur.step + ' (' + escHtml(cur.kind) + ') &middot; sends ' +
formatDate(cur.send_at) + '</div>' +
renderDeskContext(cur.context) +
- draft +
+ draft + footer +
'<div class="desk-actions">' + actions +
'<span class="muted" style="font-size:12px;margin-left:auto">' +
(i + 1) + ' of ' + items.length + '</span>' +
diff --git a/tests/test_compliance_footer.py b/tests/test_compliance_footer.py
new file mode 100644
index 0000000..4d85e9d
--- /dev/null
+++ b/tests/test_compliance_footer.py
@@ -0,0 +1,270 @@
+"""Cold email carries a postal address and an opt-out line (CAN-SPAM), and
+replies are read without the quoted email they answer.
+
+Based on community PR #13 by Camilo Cruz.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from harvey.agents.sender import Sender
+from harvey.config import ComplianceConfig, EnvConfig, compliance_notice
+from harvey.gate import pre_send_check
+from harvey.integrations.mail_provider import InboundMessage, strip_quoted_reply
+from harvey.models.campaign import Campaign, EmailStep
+from tests.test_outbox_native import ( # noqa: F401 (state is a fixture)
+ FakeProvider, StubBrain, make_handler, make_sender, seed_prospect, state,
+)
+
+ADDRESS = "Acme Co, 100 Main St, Austin, TX 78701"
+LINE = ComplianceConfig().opt_out_line
+
+
+def _now_iso():
+ from datetime import datetime, timezone
+ return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
+
+
+async def _approved(state, pid, kind="sequence", body="A short, plain note. Question?"):
+ return await state.add_outbox_item(
+ prospect_id=pid, to_email="[email protected]", subject="hello there",
+ body=body, send_at=_now_iso(), status="approved",
+ campaign_id="c1" if kind == "sequence" else "", step=2, kind=kind,
+ )
+
+
+def _sender(state, provider, address=ADDRESS, line=LINE):
+ sender = make_sender(state, provider)
+ sender.config.compliance = ComplianceConfig(postal_address=address, opt_out_line=line)
+ return sender
+
+
+# ── The footer ──
+
+async def test_cold_email_goes_out_with_the_address_and_opt_out_line(state):
+ pid = await seed_prospect(state, status="contacted")
+ item_id = await _approved(state, pid)
+ provider = FakeProvider()
+ await _sender(state, provider)._drain_due()
+ assert provider.sent[0]["body"] == (
+ "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE)
+ # The Outbox keeps what actually went out.
+ assert (await state.get_outbox_item(item_id))["body"] == provider.sent[0]["body"]
+
+
+async def test_replies_get_no_footer(state):
+ pid = await seed_prospect(state, status="replied")
+ await _approved(state, pid, kind="reply", body="Sure, Tuesday works. Talk then?")
+ provider = FakeProvider()
+ await _sender(state, provider)._drain_due()
+ assert provider.sent[0]["body"] == "Sure, Tuesday works. Talk then?"
+
+
+async def test_without_an_address_cold_email_still_goes_with_the_opt_out_line(state, caplog):
+ pid = await seed_prospect(state, status="contacted")
+ await _approved(state, pid)
+ provider = FakeProvider()
+ await _sender(state, provider, address="")._drain_due()
+ assert provider.sent[0]["body"] == "A short, plain note. Question?\n\n" + LINE
+ assert "postal_address" in caplog.text
+
+
+async def test_both_lines_can_be_turned_off(state):
+ pid = await seed_prospect(state, status="contacted")
+ await _approved(state, pid)
+ provider = FakeProvider()
+ await _sender(state, provider, address="", line="")._drain_due()
+ assert provider.sent[0]["body"] == "A short, plain note. Question?"
+
+
+async def test_a_footer_already_in_the_body_is_not_added_twice(state):
+ pid = await seed_prospect(state, status="contacted")
+ body = "A short, plain note. Question?\n\n" + ADDRESS + "\n" + LINE
+ await _approved(state, pid, body=body)
+ provider = FakeProvider()
+ await _sender(state, provider)._drain_due()
+ assert provider.sent[0]["body"] == body
+
+
+async def test_old_configs_without_a_compliance_section_still_send(state):
+ # Test configs (and any hand-built config) may lack the section entirely.
+ pid = await seed_prospect(state, status="contacted")
+ await _approved(state, pid)
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent[0]["body"].endswith(LINE)
+
+
+def test_the_gate_refuses_cold_email_missing_its_configured_address():
+ ok = pre_send_check("[email protected]", "hello there", "A note. Question?",
+ postal_address=ADDRESS)
+ assert not ok and any("postal address" in r for r in ok.reasons)
+ assert pre_send_check("[email protected]", "hello there",
+ "A note. Question?\n\n" + ADDRESS, postal_address=ADDRESS)
+ # Replies never need it.
+ assert pre_send_check("[email protected]", "hello there", "Sure, Tuesday works.",
+ kind="reply", postal_address=ADDRESS)
+
+
+async def test_instantly_sequences_carry_the_footer(state):
+ config = SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(
+ enabled=True, provider="instantly", require_approval=False,
+ max_daily_sends=50, send_to_risky=False)),
+ compliance=ComplianceConfig(postal_address=ADDRESS),
+ )
+ sender = Sender(None, state, config, EnvConfig())
+ sender.instantly = AsyncMock()
+ sender.instantly.set_campaign_emails.return_value = None # stop after the upload
+ campaign = Campaign(id="c", name="Draft", instantly_campaign_id="existing",
+ sequence=[EmailStep(step=1, subject="a note", body="Would this help?")])
+ await sender._deploy_campaign(campaign)
+ uploaded = sender.instantly.set_campaign_emails.await_args.args[1]
+ assert uploaded[0]["body"] == "Would this help?\n\n" + ADDRESS + "\n" + LINE
+
+
+def test_the_notice_asks_for_an_address_only_when_email_is_on():
+ def cfg(address, enabled=True):
+ return SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(enabled=enabled)),
+ compliance=ComplianceConfig(postal_address=address))
+ assert "compliance.postal_address" in compliance_notice(cfg(""))
+ assert compliance_notice(cfg(ADDRESS)) == ""
+ assert compliance_notice(cfg("", enabled=False)) == ""
+ assert compliance_notice(cfg(" ")) != ""
+
+
+# ── Reading replies ──
+
+GMAIL_QUOTE = (
+ "Sounds interesting, send me pricing.\n\n"
+ "On Tue, Oct 14, 2026 at 3:02 PM Harvey <[email protected]> wrote:\n"
+ "> A short, plain note. Question?\n>\n> " + ADDRESS + "\n> " + LINE
+)
+OUTLOOK_QUOTE = (
+ "Sounds interesting, send me pricing.\n\n"
+ "From: Harvey <[email protected]>\nSent: Tuesday, October 14, 2026 3:02 PM\n"
+ "To: Jane\nSubject: hello there\n\n"
+ "A short, plain note. Question?\n\n" + ADDRESS + "\n"
+ # Outlook re-wraps lines and uses curly quotes.
+ "Not interested? Reply “no\nthanks” and I won’t email again."
+)
+
+
+def test_strip_keeps_only_what_they_wrote():
+ assert strip_quoted_reply(GMAIL_QUOTE) == "Sounds interesting, send me pricing."
+ assert strip_quoted_reply(OUTLOOK_QUOTE) == "Sounds interesting, send me pricing."
+ assert strip_quoted_reply(
+ "Thanks.\n\n-----Original Message-----\nFrom: x") == "Thanks."
+ # Answers written between quoted lines are theirs too.
+ assert strip_quoted_reply(
+ "Hi Harvey,\n\n> Would you be open to a call?\n\nNo. Remove me please."
+ ) == "Hi Harvey,\n\nNo. Remove me please."
+ # Everything under a quote header: keep their lines, never return nothing.
+ assert "Remove me" in strip_quoted_reply(
+ "On Tue Harvey wrote:\n> Open to a call?\nRemove me")
+ assert strip_quoted_reply("") == ""
+
+
+class RecordingBrain(StubBrain):
+ def __init__(self, intent):
+ super().__init__(intent=intent)
+ self.prompts = []
+
+ async def think(self, prompt, session_id=None, agent="", task=""):
+ self.prompts.append(prompt)
+ return await super().think(prompt, session_id=session_id, agent=agent, task=task)
+
+
+async def _reply(state, body, intent="interested"):
+ pid = await seed_prospect(state, status="contacted")
+ 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)
+ handler.brain = RecordingBrain(intent)
+ await handler._run_native()
+ return (await state.get_prospect(pid)).status, handler.brain.prompts
+
+
+ GMAIL_QUOTE, OUTLOOK_QUOTE,
+ # An HTML-only reply converted to text keeps its entities.
+ "Sounds interesting.\n\nOn Tue Harvey wrote:\nNot interested? Reply &quot;no thanks&quot; "
+ "and I won&#39;t email again.",
+ # Gmail re-wraps long quoted lines.
+ "Sounds interesting.\n\nOn Tue Harvey wrote:\n> Not interested? Reply \"no\n> thanks\" "
+ "and I won't email again.",
+], ids=["gmail", "outlook", "html-entities", "gmail-wrapped"])
+async def test_our_own_quoted_footer_never_reads_as_an_opt_out(state, body):
+ status, prompts = await _reply(state, body)
+ assert status != "opted_out"
+ # The model reads their words, not our quoted email.
+ assert prompts and all(ADDRESS not in p for p in prompts)
+
+
+ "No thanks.",
+ "no thank you\n\nOn Tue Harvey wrote:\n> A short, plain note.",
+ # Answered inline, below and between our quoted lines.
+ "> Would you be open to a quick call?\nNo. Please remove me from your list.",
+ "Hi Harvey,\n\n> Would you be open to a quick call?\n\nNo. Remove me from your list.",
+ "On Tue Harvey wrote:\n> Open to a call?\nunsubscribe",
+], ids=["no-thanks", "above-quote", "below-quote", "between-quotes", "under-header"])
+async def test_an_opt_out_is_honoured_wherever_they_wrote_it(state, body):
+ status, _ = await _reply(state, body)
+ assert status == "opted_out"
+
+
+async def test_a_legal_threat_under_the_quote_still_escalates(state):
+ status, prompts = await _reply(
+ state, "> A short, plain note.\nMy attorney will be in touch.")
+ assert status != "opted_out"
+ assert prompts == [] # escalated by keyword, no model call, no auto-reply
+
+
+# ── Dashboard ──
+
+from tests.test_dashboard_manual_send import client, env # noqa: E402,F401
+
+
+def _config(address):
+ return SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(enabled=True)),
+ compliance=ComplianceConfig(postal_address=address))
+
+
+def test_the_outbox_shows_the_footer_and_asks_for_a_missing_address(client, monkeypatch):
+ import harvey.config
+ monkeypatch.setattr(harvey.config, "load_config", lambda: _config(""))
+ data = client.get("/api/outbox").json()
+ assert data["footer"] == LINE
+ assert "postal_address" in data["compliance_notice"]
+
+ monkeypatch.setattr(harvey.config, "load_config", lambda: _config(ADDRESS))
+ data = client.get("/api/outbox").json()
+ assert data["footer"] == ADDRESS + "\n" + LINE
+ assert data["compliance_notice"] == ""
+
+
+def test_an_unreadable_config_still_shows_the_outbox(client, monkeypatch):
+ import harvey.config
+
+ def broken():
+ raise harvey.config.ConfigError("bad yaml")
+ monkeypatch.setattr(harvey.config, "load_config", broken)
+ data = client.get("/api/outbox").json()
+ assert data["footer"] == "" and "pending" in data
diff --git a/tests/test_outbox_claim.py b/tests/test_outbox_claim.py
index cb98c1f..1447d41 100644
--- a/tests/test_outbox_claim.py
+++ b/tests/test_outbox_claim.py
@@ -195,7 +195,7 @@ async def test_the_send_uses_the_text_as_it_is_when_claimed(state, monkeypatch):
provider = FakeProvider()
await make_sender(state, provider)._drain_due()
- assert [(m["subject"], m["body"]) for m in provider.sent] == [
+ assert [(m["subject"], m["body"].split("\n\n")[0]) for m in provider.sent] == [
("edited subject", "Edited, plain note. Question?")]
diff --git a/tests/test_outbox_review.py b/tests/test_outbox_review.py
index 93c9ffc..52486bc 100644
--- a/tests/test_outbox_review.py
+++ b/tests/test_outbox_review.py
@@ -15,6 +15,7 @@ import pytest
from fastapi.testclient import TestClient
import harvey.dashboard as dash
+from harvey.config import DEFAULT_OPT_OUT_LINE as LINE
from harvey.models import Company
from harvey.models.campaign import Campaign
from harvey.models.prospect import Prospect
@@ -212,5 +213,6 @@ def test_an_approved_edit_is_what_gets_sent(client):
await make_sender(state, provider)._drain_due()
return provider.sent
sent = asyncio.run(send())
- assert [(m["subject"], m["body"]) for m in sent] == [
+ # The edit as saved, with the compliance footer the Sender adds underneath.
+ assert [(m["subject"], m["body"].split("\n\n" + LINE)[0]) for m in sent] == [
("your portal", "Hello Proven Resource team,\n\nHaris")]