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.

Warmup review: waiting follow-ups can't clog the queue; config and checker fixes

Ethanf123a185c7fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5429655..1729cb1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,9 +18,9 @@ minor versions can still change behaviour.
- **A cold-email ramp for new domains** (`channels.email.warmup`). From
`start_date`, no cold email goes out for `min_days`; then the cold cap starts
at `start_sends` and climbs by `daily_increase` a day up to
- `max_daily_sends`. It applies to native providers and Instantly lead
- uploads. Replies are never held. Off unless `start_date` is set. Both
- based on #18 by Tariz Shahid.
+ `max_daily_sends`, counted per local day. Gmail, Microsoft and SMTP only:
+ Instantly has its own warmup and per-account limits. Replies are never
+ held. Off unless `start_date` is set. Both based on #18 by Tariz Shahid.
- **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.*
diff --git a/README.md b/README.md
index fa0f596..203ee14 100644
--- a/README.md
+++ b/README.md
@@ -505,7 +505,7 @@ your explicit choice.
1. Buy a **dedicated sending domain** (`getacme.com`, not `acme.com`).
2. Set up **SPF, DKIM and DMARC** on it. Without all three, Gmail junks you. `harvey warmup` checks them, plus domain age, blocklists, your warmup progress and bounce rate, and ends with READY / NOT READY. It only reads public DNS and Harvey's own records.
3. **Warm up for 2–4 weeks** before real volume.
-4. **Ramp slowly** — 10–20/day per inbox, adding ~5/day. The `max_daily_sends: 50` default is a ceiling, not a target. Set `channels.email.warmup.start_date` and Harvey does this for you: no cold email for `min_days`, then a cold-email cap that climbs by `daily_increase` a day. Replies always go out.
+4. **Ramp slowly** — 10–20/day per inbox, adding ~5/day. The `max_daily_sends: 50` default is a ceiling, not a target. Set `channels.email.warmup.start_date` and Harvey does this for you (Gmail, Microsoft, SMTP; Instantly has its own warmup): no cold email for `min_days`, then a cold-email cap that climbs by `daily_increase` a day. Replies always go out.
5. **Watch bounces.** Above ~3%, stop and fix list quality. Harvey trips its own kill switch past your configured threshold.
*None of this is legal advice. Sending at scale or into regulated industries? Talk to a lawyer.*
diff --git a/harvey.yaml b/harvey.yaml
index 040812e..cfeb912 100644
--- a/harvey.yaml
+++ b/harvey.yaml
@@ -55,7 +55,8 @@ channels:
# New sending domain? Set start_date to the day your warmup service went
# on: no cold email for min_days, then the cold cap climbs from
# start_sends by daily_increase a day up to max_daily_sends. Replies are
- # never held. Check readiness any time with `harvey warmup`.
+ # never held. Gmail/Microsoft/SMTP only (Instantly has its own warmup).
+ # Check readiness any time with `harvey warmup`.
warmup:
start_date: "" # YYYY-MM-DD; blank = no ramp
min_days: 14
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index cf8a99f..cb4c4c6 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -101,7 +101,7 @@ class Sender:
return
# Enforce daily send limit
- max_sends = cold_daily_cap(self.config.channels.email)
+ max_sends = self.config.channels.email.max_daily_sends
sends_today = await self._count_sends_today()
remaining = max_sends - sends_today
if remaining <= 0:
@@ -258,7 +258,7 @@ class Sender:
return
# Check remaining daily send budget
- max_sends = cold_daily_cap(self.config.channels.email)
+ max_sends = self.config.channels.email.max_daily_sends
sends_today = await self._count_sends_today()
remaining = max_sends - sends_today
if remaining <= 0:
@@ -493,14 +493,21 @@ class Sender:
return datetime.fromisoformat(str(value))
except (TypeError, ValueError):
return None
- planned, prev_planned, sent_at = _at(item["send_at"]), _at(prev["send_at"]), _at(prev["sent_at"])
- gap = MIN_FOLLOW_UP_GAP
- if planned and prev_planned:
- gap = max(gap, planned - prev_planned)
+ sent_at = _at(prev["sent_at"])
if sent_at is None:
return None
- now = datetime.now(timezone.utc).replace(tzinfo=None)
- return "wait" if now < sent_at + gap else None
+ delay = await self.state.get_step_delay_days(item.get("campaign_id"), item["step"])
+ if delay is None: # campaign unknown: fall back to the planned spacing
+ planned, prev_planned = _at(item["send_at"]), _at(prev["send_at"])
+ gap = (planned - prev_planned) if planned and prev_planned else MIN_FOLLOW_UP_GAP
+ else:
+ gap = timedelta(days=delay)
+ ready_at = sent_at + max(MIN_FOLLOW_UP_GAP, gap)
+ if datetime.now(timezone.utc).replace(tzinfo=None) >= ready_at:
+ return None
+ # Reschedule it for then, so it leaves the due queue until it's ready.
+ await self.state.update_outbox_item(item["id"], send_at=ready_at.isoformat())
+ return "wait"
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."""
@@ -546,29 +553,34 @@ class Sender:
logger.info(f"Sender: daily send cap reached ({sent_today}/{max_daily}).")
return
# Cold email has its own cap under the warmup ramp; replies don't.
+ # Counted from local midnight, the day the ramp counts in.
cold_cap = cold_daily_cap(self.config.channels.email)
- cold_left = cold_cap - await self.state.count_outbox_sent_today(kind="sequence")
+ midnight = datetime.now().astimezone().replace(hour=0, minute=0, second=0, microsecond=0)
+ cold_left = cold_cap - await self.state.count_outbox_sent_today(
+ kind="sequence",
+ since=midnight.astimezone(timezone.utc).replace(tzinfo=None).isoformat())
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
due = await self.state.get_outbox(
- status="approved", due_before=now, limit=budget * 3
+ status="approved", due_before=now, limit=budget * 3,
+ skip_unready_follow_ups=True,
)
- if self.precleared is not None or cold_left <= 0:
- # Cold emails held (by an unavailable compliance check, or the
- # cold cap) stay approved at the front of the queue and could
- # fill the page above, so fetch replies (and any other 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",
+ # Cold emails held (by an unavailable compliance check, the cold
+ # cap, a follow-up's spacing) stay approved and could fill the
+ # page above, so replies (and any other kind) are fetched on
+ # their own too and never wait behind them. 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 ""),
)
- 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:
return
diff --git a/harvey/cli.py b/harvey/cli.py
index e584b47..20c9cd2 100644
--- a/harvey/cli.py
+++ b/harvey/cli.py
@@ -710,8 +710,8 @@ def cmd_warmup(args):
print(f"\n {e}\n")
raise SystemExit(1)
email = config.channels.email
- sender = (os.getenv("SMTP_USERNAME", "").strip() if email.provider == "smtp" else "") \
- or config.persona.email
+ smtp_user = os.getenv("SMTP_USERNAME", "").strip() if email.provider == "smtp" else ""
+ sender = smtp_user if "@" in smtp_user else config.persona.email
domain = (args.domain or sender.rpartition("@")[2]).strip().lower().rstrip(".")
if not d.DOMAIN_RE.match(domain):
print("\n No valid sending domain found. Pass one: harvey warmup yourdomain.com\n")
@@ -736,17 +736,20 @@ def cmd_warmup(args):
d.check_send_history(*asyncio.run(_history()))]),
]
icons = {d.OK: "OK ", d.WARN: "WARN", d.FAIL: "FAIL", d.INFO: "info"}
- failed = warned = 0
+ failed = warned = unknown = 0
for title, checks in sections:
print(f"\n {title}")
for c in checks:
failed += c.status == d.FAIL
warned += c.status == d.WARN
+ unknown += c.unknown and title == "Authentication"
print(f" [{icons[c.status]}] {c.name:<26} {c.detail}")
print("\n " + "=" * 56)
if failed:
print(f" NOT READY - fix the {failed} FAIL item(s) before any cold email.")
+ elif unknown:
+ print(f" NOT CHECKED - {unknown} authentication lookup(s) failed; run again.")
elif warned:
print(f" READY WITH CAVEATS - {warned} warning(s); keep volume low.")
else:
@@ -757,7 +760,7 @@ def cmd_warmup(args):
print(" - Inbox placement: send one email to a seed test (mail-tester.com is free)")
print(" and aim for 9/10+. Your warmup service's dashboard shows its inbox rate;")
print(" wait for ~95%+ inbox for a week before relying on cold sends.\n")
- if failed:
+ if failed or unknown:
raise SystemExit(1)
diff --git a/harvey/config.py b/harvey/config.py
index 6b736b8..feefec9 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -88,8 +88,16 @@ class WarmupConfig(BaseModel):
@field_validator("start_date", "dkim_selector", mode="before")
@classmethod
def _blank_is_empty(cls, v):
+ # YAML reads an unquoted 2026-10-01 as a date.
+ if isinstance(v, _date):
+ return v.isoformat()
return "" if v is None else v
+ @field_validator("min_days", "start_sends", "daily_increase", mode="before")
+ @classmethod
+ def _blank_is_default(cls, v, info):
+ return cls.model_fields[info.field_name].default if v is None else v
+
@field_validator("start_date")
@classmethod
def _valid_date(cls, v: str) -> str:
@@ -142,9 +150,15 @@ class EmailChannelConfig(BaseModel):
# Kill switch: pause all sending when bounces exceed this fraction of
# sent mail (measured over the trailing sends). 0 disables the switch.
max_bounce_rate: float = 0.05
- # New domain? Ramp cold email up slowly (see WarmupConfig).
+ # New domain? Ramp cold email up slowly (see WarmupConfig). Native
+ # providers only: Instantly has its own warmup and per-account limits.
warmup: WarmupConfig = WarmupConfig()
+ @field_validator("warmup", mode="before")
+ @classmethod
+ def _blank_warmup(cls, v):
+ return WarmupConfig() if v is None else v
+
@field_validator("max_daily_sends")
@classmethod
def _sends_non_negative(cls, v: int) -> int:
diff --git a/harvey/deliverability.py b/harvey/deliverability.py
index 2f3f9be..4f64578 100644
--- a/harvey/deliverability.py
+++ b/harvey/deliverability.py
@@ -56,9 +56,11 @@ class Check:
name: str
status: str
detail: str
+ unknown: bool = False # the lookup itself failed: no verdict either way
-DOMAIN_RE = re.compile(r"^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")
+DOMAIN_RE = re.compile(
+ r"^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$")
class LookupFailed(Exception):
@@ -84,7 +86,8 @@ def _a(name: str) -> list[str]:
def _unknown(name: str, e: LookupFailed) -> Check:
- return Check(name, INFO, f"Couldn't look this up ({e}). Check your connection and run again.")
+ return Check(name, INFO, f"Couldn't look this up ({e}). Check your connection and run again.",
+ unknown=True)
def check_mx(domain: str) -> Check:
@@ -110,13 +113,15 @@ def check_spf(domain: str) -> Check:
terms = spf.lower().split()
if "+all" in terms or "all" in terms:
return Check("SPF", FAIL, f"'+all' lets anyone send as you: {spf}")
- lookups = sum(t.lstrip("+-~?").split(":")[0].split("=")[0] in
+ lookups = sum(t.lstrip("+-~?").split(":")[0].split("=")[0].split("/")[0] in
("include", "a", "mx", "ptr", "exists", "redirect") for t in terms)
if lookups > 10:
# Top-level terms only; includes add their own lookups on top.
return Check("SPF", FAIL, f"{lookups} DNS lookups (limit is 10) - SPF will permerror.")
if "?all" in terms:
return Check("SPF", WARN, f"'?all' is neutral; use '~all' or '-all': {spf}")
+ if not any(t.lstrip("+-~?") == "all" or t.startswith("redirect=") for t in terms):
+ return Check("SPF", WARN, f"No 'all' at the end, so it ends neutral; add '~all': {spf}")
return Check("SPF", OK, spf)
@@ -128,10 +133,13 @@ def check_dmarc(domain: str) -> Check:
if not records:
return Check("DMARC", FAIL, "No DMARC record. Gmail and Yahoo require one for bulk senders. "
f"Start with TXT _dmarc.{domain} = \"v=DMARC1; p=none; rua=mailto:you@{domain}\"")
- tags = dict(
- part.strip().split("=", 1) for part in records[0].split(";") if "=" in part
- )
+ if len(records) > 1:
+ return Check("DMARC", FAIL, f"{len(records)} DMARC records - receivers ignore them all. Keep one.")
+ tags = {k.strip().lower(): v for k, v in (
+ part.strip().split("=", 1) for part in records[0].split(";") if "=" in part)}
policy = tags.get("p", "").strip().lower()
+ if not policy:
+ return Check("DMARC", WARN, f"No p= policy tag - add p=none to start: {records[0]}")
if policy == "none":
return Check("DMARC", WARN, f"p=none (monitoring only) - fine while warming; "
f"move to quarantine once reports look clean. {records[0]}")
@@ -219,8 +227,16 @@ def check_warmup(warmup, ceiling: int, today: date | None = None) -> Check:
return Check("Warmup", FAIL, f"Day {days} of {warmup.min_days} - warming only, no cold email "
f"until {warmup.min_days - days} more day(s) pass.")
cap = warmup.daily_cap(ceiling, today)
- full_on = warmup.min_days + max(0, -(-(ceiling - warmup.start_sends) // max(warmup.daily_increase, 1)))
- ramp = "full volume" if cap >= ceiling else f"reaches {ceiling}/day on day {full_on}"
+ if cap <= 0:
+ return Check("Warmup", WARN, "Today's cold cap is 0 and won't grow: raise start_sends "
+ "or daily_increase.")
+ if cap >= ceiling:
+ ramp = "full volume"
+ elif warmup.daily_increase <= 0:
+ ramp = f"stays at {cap}/day (daily_increase is 0)"
+ else:
+ full_on = warmup.min_days + -(-(ceiling - warmup.start_sends) // warmup.daily_increase)
+ ramp = f"reaches {ceiling}/day on day {full_on}"
return Check("Warmup", OK, f"Day {days}: today's cap is {cap}/day ({ramp}). "
"Keep the warmup service running alongside Harvey.")
diff --git a/harvey/state.py b/harvey/state.py
index ebb9d0d..c440acf 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -891,7 +891,10 @@ class StateManager:
due_before: str | None = None,
limit: int = 200,
exclude_kind: str | None = None,
+ skip_unready_follow_ups: bool = False,
) -> list[dict]:
+ """skip_unready_follow_ups: leave out sequence follow-ups whose
+ previous step hasn't gone out yet, so they can't fill the page."""
where, params = [], []
if status:
where.append("status = ?")
@@ -902,7 +905,14 @@ class StateManager:
if exclude_kind:
where.append("(kind IS NULL OR kind != ?)")
params.append(exclude_kind)
- sql = "SELECT * FROM outbox"
+ if skip_unready_follow_ups:
+ where.append(
+ "NOT (o.kind = 'sequence' AND o.step > 1 AND EXISTS ("
+ "SELECT 1 FROM outbox p WHERE p.prospect_id = o.prospect_id "
+ "AND p.campaign_id = o.campaign_id AND p.kind = 'sequence' "
+ "AND p.step = o.step - 1 "
+ "AND p.status IN ('pending_review', 'approved', 'sending')))")
+ sql = "SELECT * FROM outbox o"
if where:
sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY send_at ASC, created_at ASC LIMIT ?"
@@ -1105,17 +1115,40 @@ class StateManager:
) as cursor:
return (await cursor.fetchone())[0]
- async def count_outbox_sent_today(self, kind: str | None = None) -> int:
- """Emails sent today; only one kind ("sequence", "reply") if given."""
- sql = "SELECT COUNT(*) FROM outbox WHERE status = 'sent' AND date(sent_at) = date('now')"
- params: tuple = ()
+ async def count_outbox_sent_today(self, kind: str | None = None,
+ since: str | None = None) -> int:
+ """Emails sent today (the UTC day, or since `since`, a naive UTC
+ ISO time); only one kind ("sequence", "reply") if given."""
+ if since:
+ sql = "SELECT COUNT(*) FROM outbox WHERE status = 'sent' AND sent_at >= ?"
+ params: tuple = (since,)
+ else:
+ sql = ("SELECT COUNT(*) FROM outbox WHERE status = 'sent' "
+ "AND date(sent_at) = date('now')")
+ params = ()
if kind:
sql += " AND kind = ?"
- params = (kind,)
+ params += (kind,)
async with self._connect() as db:
async with db.execute(sql, params) as cursor:
return (await cursor.fetchone())[0]
+ async def get_step_delay_days(self, campaign_id: str, step: int) -> int | None:
+ """The campaign's planned wait before `step` (days after the step
+ before it), or None when the campaign or step isn't known."""
+ async with self._connect() as db:
+ async with db.execute(
+ "SELECT sequence_json FROM campaigns WHERE id = ?", (campaign_id or "",)
+ ) as cursor:
+ row = await cursor.fetchone()
+ try:
+ for s in json.loads((row[0] if row else None) or "[]"):
+ if isinstance(s, dict) and int(s.get("step", 0)) == int(step):
+ return max(0, int(s.get("delay_days") or 0))
+ except (json.JSONDecodeError, TypeError, ValueError):
+ pass
+ return None
+
async def get_previous_step(self, item: dict) -> dict | None:
"""The email a sequence follow-up follows (same campaign and person,
one step earlier), or None."""
diff --git a/tests/test_followup_spacing.py b/tests/test_followup_spacing.py
index 20ef451..747e1f9 100644
--- a/tests/test_followup_spacing.py
+++ b/tests/test_followup_spacing.py
@@ -52,3 +52,89 @@ async def test_a_follow_up_whose_first_email_never_went_out_waits(state):
provider = FakeProvider()
await make_sender(state, provider)._drain_due()
assert provider.sent == []
+
+
+async def _sequence(state, pid, step, status, send_at, campaign="c1", to="[email protected]"):
+ return await state.add_outbox_item(
+ prospect_id=pid, to_email=to, subject=f"s{step}", body=f"Step {step}. Question?",
+ send_at=send_at.isoformat(), status=status, campaign_id=campaign, step=step)
+
+
+async def _sent(state, item_id, at):
+ await state.update_outbox_item(item_id, status="sent", sent_at=at.isoformat())
+
+
+async def test_a_follow_up_goes_once_its_gap_has_passed(state):
+ pid = await seed_prospect(state, status="contacted")
+ one = await _sequence(state, pid, 1, "approved", _now() - timedelta(days=5))
+ await _sent(state, one, _now() - timedelta(days=4))
+ await _sequence(state, pid, 2, "approved", _now() - timedelta(days=2))
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert [m["subject"] for m in provider.sent] == ["s2"]
+
+
+async def test_a_waiting_follow_up_is_rescheduled_for_when_it_can_go(state):
+ pid = await seed_prospect(state, status="contacted")
+ one = await _sequence(state, pid, 1, "approved", _now() - timedelta(days=7))
+ await _sent(state, one, _now() - timedelta(hours=1))
+ two = await _sequence(state, pid, 2, "approved", _now() - timedelta(days=4))
+ await make_sender(state, FakeProvider())._drain_due()
+ send_at = datetime.fromisoformat((await state.get_outbox_item(two))["send_at"])
+ assert send_at > _now() + timedelta(hours=20) # out of the due queue until then
+
+
+async def test_the_campaign_delay_sets_the_gap_not_a_late_staging_time(state):
+ # Step 2 was staged late (sending was paused), so its planned time is far
+ # after step 1's: the campaign's 3 days still decide when it may go.
+ pid = await seed_prospect(state, status="contacted")
+ await seed_campaign(state, [pid]) # step 2 delay_days=3
+ campaign = (await state.get_campaigns_by_status("draft"))[0]
+ one = await _sequence(state, pid, 1, "approved", _now() - timedelta(days=20), campaign=campaign.id)
+ await _sent(state, one, _now() - timedelta(days=4))
+ await _sequence(state, pid, 2, "approved", _now() - timedelta(minutes=5), campaign=campaign.id)
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert [m["subject"] for m in provider.sent] == ["s2"]
+
+
[email protected]("prev_status", ["rejected", "failed", "cancelled"])
+async def test_a_follow_up_to_an_email_that_never_went_out_is_cancelled(state, prev_status):
+ pid = await seed_prospect(state, status="contacted")
+ await _sequence(state, pid, 1, prev_status, _now() - timedelta(days=5))
+ two = await _sequence(state, pid, 2, "approved", _now() - timedelta(days=1))
+ provider = FakeProvider()
+ await make_sender(state, provider)._drain_due()
+ assert provider.sent == []
+ item = await state.get_outbox_item(two)
+ assert item["status"] == "cancelled" and "wasn't sent" in item["error"]
+
+
[email protected]("first", ["just sent", "still pending"])
+async def test_a_page_of_waiting_follow_ups_never_holds_up_a_reply_or_new_email(state, first):
+ # 30 follow-ups older than everything else, all waiting on their step 1.
+ for n in range(30):
+ pid = await seed_prospect(state, email=f"p{n}@acme.com", status="contacted")
+ one = await _sequence(state, pid, 1,
+ "approved" if first == "just sent" else "pending_review",
+ _now() - timedelta(days=9), to=f"p{n}@acme.com")
+ if first == "just sent":
+ await _sent(state, one, _now() - timedelta(hours=1))
+ await _sequence(state, pid, 2, "approved", _now() - timedelta(days=6), to=f"p{n}@acme.com")
+ warm = await seed_prospect(state, email="[email protected]", status="replied")
+ await state.add_outbox_item(
+ prospect_id=warm, to_email="[email protected]", subject="Re: hi", body="Tuesday works.",
+ send_at=_now().isoformat(), status="approved", kind="reply")
+ fresh = await seed_prospect(state, email="[email protected]", status="queued")
+ await _sequence(state, fresh, 1, "approved", _now() - timedelta(minutes=1),
+ campaign="c2", to="[email protected]")
+
+ provider = FakeProvider()
+ for _ in range(2): # the first cycle may reschedule; nothing waits twice
+ await make_sender(state, provider)._drain_due()
+ assert {m["to"] for m in provider.sent} == {"[email protected]", "[email protected]"}
diff --git a/tests/test_warmup.py b/tests/test_warmup.py
index bd12def..0cb45a5 100644
--- a/tests/test_warmup.py
+++ b/tests/test_warmup.py
@@ -52,15 +52,17 @@ async def _approved(state, pid, kind, step=1, campaign="c1"):
status="approved", campaign_id=campaign if kind == "sequence" else "", step=step, kind=kind)
-def _ramped_sender(state, provider, days_in, **ramp):
+def _ramped_sender(state, provider, monkeypatch, days_in, **ramp):
sender = make_sender(state, provider)
start = (date.today() - timedelta(days=days_in)).isoformat()
- sender.config.channels.email.warmup = WarmupConfig(start_date=start, **ramp)
+ # The test config is a shared class: monkeypatch restores it afterwards.
+ monkeypatch.setattr(sender.config.channels.email, "warmup",
+ WarmupConfig(start_date=start, **ramp), raising=False)
return sender
@pytest.mark.asyncio
-async def test_while_warming_cold_email_waits_but_replies_go(state):
+async def test_while_warming_cold_email_waits_but_replies_go(state, monkeypatch):
cold = await seed_prospect(state, email="[email protected]", status="queued")
await _approved(state, cold, "sequence")
warm = await seed_prospect(state, email="[email protected]", status="replied")
@@ -68,16 +70,13 @@ async def test_while_warming_cold_email_waits_but_replies_go(state):
prospect_id=warm, to_email="[email protected]", subject="Re: hi",
body="Sure, Tuesday works.", send_at=_now_iso(), status="approved", kind="reply")
provider = FakeProvider()
- try:
- await _ramped_sender(state, provider, days_in=3, min_days=14)._drain_due()
- finally:
- make_sender(state, provider).config.channels.email.warmup = WarmupConfig()
+ await _ramped_sender(state, provider, monkeypatch, days_in=3, min_days=14)._drain_due()
assert [m["to"] for m in provider.sent] == ["[email protected]"]
assert len(await state.get_outbox(status="approved")) == 1 # the cold one waits
@pytest.mark.asyncio
-async def test_after_warming_cold_email_is_capped_at_todays_ramp(state):
+async def test_after_warming_cold_email_is_capped_at_todays_ramp(state, monkeypatch):
for n in range(4):
pid = await seed_prospect(state, email=f"p{n}@acme.com", status="queued")
await state.add_outbox_item(
@@ -85,17 +84,16 @@ async def test_after_warming_cold_email_is_capped_at_todays_ramp(state):
body="A short, plain note. Question?", send_at=_now_iso(), status="approved",
campaign_id="c1", step=1)
provider = FakeProvider()
- try:
- # Day 15 of a 14-day warmup: start_sends + one day's increase = 2.
- await _ramped_sender(state, provider, days_in=15, min_days=14, start_sends=1,
- daily_increase=1)._drain_due()
- finally:
- make_sender(state, provider).config.channels.email.warmup = WarmupConfig()
+ # Day 15 of a 14-day warmup: start_sends + one day's increase = 2.
+ await _ramped_sender(state, provider, monkeypatch, days_in=15, min_days=14,
+ start_sends=1, daily_increase=1)._drain_due()
assert len(provider.sent) == 2
@pytest.mark.asyncio
-async def test_instantly_adds_no_more_leads_than_todays_ramp(state, monkeypatch):
+async def test_the_ramp_leaves_instantly_alone(state, monkeypatch):
+ # Instantly runs its own warmup and per-account limits; capping uploads
+ # here would strand the rest of a campaign's prospects.
from harvey.agents.sender import Sender
from harvey.config import EnvConfig
from harvey.models.campaign import Campaign, EmailStep
@@ -112,7 +110,7 @@ async def test_instantly_adds_no_more_leads_than_todays_ramp(state, monkeypatch)
id="c", name="Draft", instantly_campaign_id="existing", prospect_ids=ids,
sequence=[EmailStep(step=1, subject="a note", body="Would this help?")]))
leads = sender.instantly.add_leads.await_args.args[1]
- assert len(leads) == 3
+ assert len(leads) == 6
# ── The checks (DNS stubbed) ──
@@ -176,3 +174,43 @@ def test_warmup_check_reports_progress():
])
def test_only_real_domain_names_are_checked(domain, ok):
assert bool(d.DOMAIN_RE.match(domain)) is ok
+
+
+def test_an_unquoted_yaml_date_and_blank_values_load():
+ import yaml
+ email = EmailChannelConfig(**yaml.safe_load(
+ "warmup:\n start_date: 2026-10-01\n min_days:\n dkim_selector:\n"))
+ assert email.warmup.start_date == "2026-10-01" and email.warmup.min_days == 14
+ assert EmailChannelConfig(**yaml.safe_load("warmup:\n")).warmup == WarmupConfig()
+
+
+def test_failed_lookups_are_flagged_unknown(monkeypatch):
+ def timeout(*a, **k):
+ raise dns.exception.Timeout()
+ monkeypatch.setattr(d.dns.resolver, "resolve", timeout)
+ assert d.check_spf("a.com").unknown and not d.check_warmup(WarmupConfig(), 30).unknown
+
+
+def test_spf_without_all_and_duplicate_dmarc(monkeypatch):
+ monkeypatch.setattr(d, "_txt", _txt({
+ "a.com": ["v=spf1 include:_spf.google.com"],
+ "_dmarc.a.com": ["v=DMARC1; p=none", "v=DMARC1; p=reject"],
+ "_dmarc.b.com": ["v=DMARC1; rua=mailto:[email protected]"],
+ "c.com": ["v=spf1 a/24 mx/24 " + " ".join(f"include:i{n}.com" for n in range(9)) + " -all"],
+ }))
+ assert d.check_spf("a.com").status == d.WARN
+ assert d.check_dmarc("a.com").status == d.FAIL
+ assert d.check_dmarc("b.com").status == d.WARN
+ assert d.check_spf("c.com").status == d.FAIL # a/24 and mx/24 are lookups too
+
+
+def test_a_ramp_that_never_grows_says_so():
+ w = WarmupConfig(start_date="2026-10-01", min_days=0, start_sends=5, daily_increase=0)
+ assert "stays at 5/day" in d.check_warmup(w, 30, date(2026, 10, 5)).detail
+ w = WarmupConfig(start_date="2026-10-01", min_days=0, start_sends=0, daily_increase=0)
+ assert d.check_warmup(w, 30, date(2026, 10, 5)).status == d.WARN
+
+
[email protected]("domain", ["xn--mnchen-3ya.de", "shop.xn--p1ai"])
+def test_punycode_domains_are_checked(domain):
+ assert d.DOMAIN_RE.match(domain)