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.
Pause prospecting for a day, never for good, on unusable prospects
Ethan903fc03e5cfb
diff --git a/harvey/main.py b/harvey/main.pyindex c1b2be1..8092790 100644--- a/harvey/main.py+++ b/harvey/main.py@@ -75,10 +75,12 @@ def seconds_until_quiet_hours_end(config: HarveyConfig) -> int:return max(int(delta.total_seconds()), 60)-# Stop prospecting once this many 'new' prospects are waiting. Past it, more-# leads only add to a backlog the Writer can't work through, or (when none-# has a usable email) spend search and verifier credits on people Harvey-# can never email.+# When nothing is writable, prospecting pauses for the rest of the day once+# this many unusable prospects (a guessed, invalid or missing email) were+# found in the last 24 hours. Without a working verifier every address is a+# guess, and prospecting every cycle would spend search and verifier credits+# on people Harvey can never email. Nothing re-checks a guess, so the window+# is a day, never all time: an all-time count would stop Scout for good.PROSPECT_BACKLOG = 20@@ -92,16 +94,17 @@ def _new_counts(summary: dict) -> tuple[int, int]:def unusable_backlog_notice(summary: dict) -> str:- """Why Harvey is idling on a full backlog of unusable prospects, or ""."""- new, writable = _new_counts(summary)- if writable or new < PROSPECT_BACKLOG:+ """Why Harvey paused prospecting for the day, or ""."""+ _, writable = _new_counts(summary)+ recent = summary.get("recent_unusable_prospects", 0) or 0+ if writable or recent < PROSPECT_BACKLOG:return ""return (- f"{new} new prospects are waiting, but none has a verified or catch-all "- "email, so Harvey has stopped prospecting to save search and verifier "- "credits. Add an email verifier key (REOON_API_KEY, ZEROBOUNCE_API_KEY or "- "HUNTER_API_KEY in .env) or check it still has credits, or export the list "- "with `harvey export --all`."+ f"Harvey found {recent} prospects in the last day, but none has a verified "+ "or catch-all email, so it paused prospecting until tomorrow to save search "+ "and verifier credits. Add an email verifier key (REOON_API_KEY, "+ "ZEROBOUNCE_API_KEY or HUNTER_API_KEY in .env) or check it still has credits. "+ "`harvey export --all` exports the list as it is.")@@ -137,13 +140,11 @@ async def decide_next_action(action, reason = "send_campaign", f"{draft_campaigns} draft campaign(s) ready to deploy"elif writable > 0:action, reason = "write_campaign", f"{writable} new prospect(s) with no drafts ready"- elif new_prospects < PROSPECT_BACKLOG:- action, reason = "prospect", f"only {new_prospects} new prospect(s); pipeline needs leads"+ elif unusable_backlog_notice(summary):+ action, reason = "idle", "a day's worth of prospects with no usable email"+ logger.warning(unusable_backlog_notice(summary))else:- action, reason = "idle", "backlog full; running analysis"- notice = unusable_backlog_notice(summary)- if notice:- logger.warning(notice)+ action, reason = "prospect", f"{new_prospects} new prospect(s), none ready to write for"logger.info(f"Decision: {action} ({reason})")return actiondiff --git a/harvey/state.py b/harvey/state.pyindex 128c782..d11b7b2 100644--- a/harvey/state.py+++ b/harvey/state.py@@ -12,7 +12,7 @@ upgrade cleanly in place.import jsonimport uuidfrom contextlib import asynccontextmanager-from datetime import datetime, date, timezone+from datetime import datetime, date, timedelta, timezonefrom pathlib import Pathimport aiosqlite@@ -1472,6 +1472,21 @@ class StateManager:) as cursor:return (await cursor.fetchone())[0]+ async def count_recent_unusable_prospects(self, hours: int = 24) -> int:+ """New prospects found in the last ``hours`` that the Writer can't use."""+ since = (_utcnow() - timedelta(hours=hours)).isoformat()+ marks = ",".join("?" for _ in WRITABLE_EMAIL_STATUSES)+ async with self._connect() as db:+ async with db.execute(+ f"""SELECT COUNT(*) FROM prospects+ WHERE status = 'new'+ AND NOT (COALESCE(email, '') != ''+ AND COALESCE(email_status, '') IN ({marks}))+ AND datetime(created_at) >= datetime(?)""",+ (*WRITABLE_EMAIL_STATUSES, since),+ ) as cursor:+ return (await cursor.fetchone())[0]+async def count_prospects_by_status(self) -> dict[str, int]:async with self._connect() as db:async with db.execute(@@ -1900,6 +1915,9 @@ class StateManager:# address stays 'new' forever, so deciding from the raw count# would keep choosing write_campaign with nothing to write."writable_prospects": await self.count_writable_prospects(),+ # Unusable ones found in the last day: the heartbeat pauses+ # prospecting for the day when these alone fill the backlog.+ "recent_unusable_prospects": await self.count_recent_unusable_prospects(),"draft_campaigns": draft_campaigns,"active_campaigns": active_campaigns,"open_conversations": open_conversations,diff --git a/tests/test_prospecting_stall.py b/tests/test_prospecting_stall.pyindex 3b3957c..f16ea0b 100644--- a/tests/test_prospecting_stall.py+++ b/tests/test_prospecting_stall.py@@ -53,18 +53,55 @@ async def test_guessed_emails_alone_lead_back_to_prospecting(state):assert await decide_next_action(None, state, CONFIG, summary=summary) == "prospect"+async def age_all(state, days):+ """Pretend every prospect was found ``days`` ago."""+ import aiosqlite+ from datetime import datetime, timedelta, timezone+ then = (datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=days)).isoformat()+ async with aiosqlite.connect(state.db_path) as db:+ await db.execute("UPDATE prospects SET created_at = ?", (then,))+ await db.commit()++@pytest.mark.asyncio-async def test_a_backlog_of_unusable_prospects_stops_spending_and_says_why(state):+async def test_a_day_of_unusable_prospects_pauses_spending_and_says_why(state):# With no usable email at all (say, no verifier key), prospecting every# cycle would burn search and verifier credits on people Harvey can- # never email. At the backlog cap it idles, and status explains why.+ # never email. A day's worth pauses it, and status explains why.from harvey.main import PROSPECT_BACKLOG, unusable_backlog_noticefor n in range(PROSPECT_BACKLOG):await add(state, n, f"p{n}@co{n}.test", "guess")summary = await state.get_state_summary()assert await decide_next_action(None, state, CONFIG, summary=summary) == "idle"notice = unusable_backlog_notice(summary)- assert str(PROSPECT_BACKLOG) in notice and "verifier" in notice+ assert str(PROSPECT_BACKLOG) in notice and "verifier" in notice and "tomorrow" in notice+++async def test_the_pause_never_becomes_permanent(state):+ # Nothing re-checks a guessed address, so an all-time count would stop+ # Scout for good. Once the guesses are a day old, prospecting resumes.+ from harvey.main import PROSPECT_BACKLOG, unusable_backlog_notice+ for n in range(PROSPECT_BACKLOG + 10):+ await add(state, n, f"p{n}@co{n}.test", "guess")+ await age_all(state, days=2)+ summary = await state.get_state_summary()+ assert await decide_next_action(None, state, CONFIG, summary=summary) == "prospect"+ assert unusable_backlog_notice(summary) == ""+++async def test_old_guesses_do_not_stop_a_mixed_setup_returning_to_prospecting(state):+ for n in range(25):+ await add(state, n, f"p{n}@co{n}.test", "guess")+ await age_all(state, days=3)+ await add(state, 100, "[email protected]", "verified")+ summary = await state.get_state_summary()+ assert await decide_next_action(None, state, CONFIG, summary=summary) == "write_campaign"+ [verified] = [p for p in await state.get_prospects_by_status("new") if p.email_status == "verified"]+ await state.update_prospect_status(verified.id, "queued") # what the Writer does+ summary = await state.get_state_summary()+ assert await decide_next_action(None, state, CONFIG, summary=summary) == "prospect"@pytest.mark.asyncio