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.

Never count an outage as a bad draft; add harvey retry-writes

Ethan3ff4031a4056
diff --git a/README.md b/README.md
index b90c60c..b9e54cb 100644
--- a/README.md
+++ b/README.md
@@ -326,6 +326,7 @@ The dashboard's Outbox is a decisions desk: one email fills the pane, the rest w
harvey outbox # review from the terminal
harvey outbox --approve-all
harvey sending pause # kill switch, stops everything mid-flight
+harvey retry-writes # retry prospects the Writer gave up on after 3 unusable drafts
```
Before anything leaves, a **deterministic pre-send gate** — no model involved — rejects: unrendered merge tags, banned phrases, emails over the length cap, too many links, HTML bodies, non-deliverable addresses, and any mismatch between the recipient and the database record.
@@ -441,6 +442,7 @@ harvey usage # active provider's quota + per-agent tokens
harvey outbox # review queued email
harvey export # deliverable prospects → CSV
harvey sending pause|resume # kill switch
+harvey retry-writes # retry prospects the Writer gave up on
harvey gmail auth # one-time Gmail OAuth
harvey microsoft auth|test # one-time Microsoft 365 sign-in (docs/microsoft365.md)
```
diff --git a/harvey/agents/writer.py b/harvey/agents/writer.py
index 9597b18..05b6efa 100644
--- a/harvey/agents/writer.py
+++ b/harvey/agents/writer.py
@@ -94,12 +94,15 @@ class Writer:
)
# Generate the email sequence
+ self._no_reply = False
sequence = await self._write_sequence(prospects)
if not sequence:
- paused = getattr(self.brain, "paused_reason", "")
+ paused = getattr(self.brain, "paused_reason", "") or (
+ "no reply from the model" if self._no_reply else "")
if paused:
- # The provider is down, not the draft bad: no attempt is
- # counted, and the other batches would fail the same way.
+ # The provider failed (outage, logout, rate limit,
+ # timeout), not the draft: no attempt is counted, and the
+ # other batches would fail the same way.
logger.warning(f"Writer: {paused}; leaving '{batch_name}' for later.")
return
logger.warning(f"Writer: Failed to generate sequence for {batch_name}")
@@ -380,6 +383,8 @@ Return ONLY a JSON array (no markdown fences, no commentary):
prompt, session_id="harvey-writer",
agent="writer", task="write_sequence",
)
+ # Read right after the call, before anything else can use the brain.
+ self._no_reply = result is None and bool(getattr(self.brain, "last_reply_empty", False))
steps = self._parse_sequence(result)
if inbox_batch and any(
PERSON_VAR.search(s.subject + s.body) for s in steps
diff --git a/harvey/brain.py b/harvey/brain.py
index e97cd38..75aebf6 100644
--- a/harvey/brain.py
+++ b/harvey/brain.py
@@ -87,6 +87,10 @@ class Brain:
self.provider = self.config.provider
self.model = self.config.model
self.codex = None
+ # Whether the last think_json got no reply at all (an outage, logout,
+ # rate limit or timeout), as opposed to a reply that wasn't valid
+ # JSON. Callers that count model failures must not count outages.
+ self.last_reply_empty = False
# Codex health (unused for Claude, whose behaviour is unchanged).
self.unavailable = ""
self._unavailable_at = 0.0
@@ -573,6 +577,7 @@ class Brain:
response = await self.think(
full_prompt, session_id=session_id, agent=agent, task=task
)
+ self.last_reply_empty = not response
if not response:
return None
parsed = self._extract_json(response)
diff --git a/harvey/cli.py b/harvey/cli.py
index c494f88..06a56ee 100644
--- a/harvey/cli.py
+++ b/harvey/cli.py
@@ -205,6 +205,10 @@ def cmd_status(args):
print(f" Prospects: {summary['prospects']}")
print(f" Ready to write for: {summary.get('writable_prospects', 0)} "
"(new, with a verified or catch-all email)")
+ write_failed = (summary.get("prospects") or {}).get("write_failed", 0)
+ if write_failed:
+ print(f" Couldn't write for: {write_failed} (the model's drafts kept coming back "
+ "unusable; `harvey retry-writes` tries again)")
print(f" Draft campaigns: {summary['draft_campaigns']}")
print(f" Active campaigns: {summary['active_campaigns']}")
print(f" Open conversations: {summary['open_conversations']}")
@@ -663,6 +667,24 @@ def cmd_signals(args):
asyncio.run(_signals())
+def cmd_retry_writes(args):
+ """Put prospects the Writer gave up on back in line for another try."""
+ from harvey.agents.writer import MAX_WRITE_ATTEMPTS
+ from harvey.state import StateManager
+
+ async def _run():
+ state = StateManager()
+ await state.init_db()
+ count = await state.retry_write_failed()
+ if count:
+ print(f"\n {count} prospect(s) are back in line. The Writer will try each "
+ f"up to {MAX_WRITE_ATTEMPTS} more times.\n")
+ else:
+ print("\n No prospects are waiting on a retry.\n")
+
+ asyncio.run(_run())
+
+
def cmd_sending(args):
"""Pause/resume the sending kill switch."""
from harvey.state import StateManager
@@ -816,6 +838,10 @@ def main():
help="Comma-separated codes to turn off")
sub.set_defaults(func=cmd_signals)
+ sub = subparsers.add_parser(
+ "retry-writes", help="Retry prospects the Writer couldn't write an email for")
+ sub.set_defaults(func=cmd_retry_writes)
+
sub = subparsers.add_parser("sending", help="Kill switch: pause/resume sending")
sub.add_argument("sending_action", nargs="?", default="status",
choices=["pause", "resume", "status"])
diff --git a/harvey/state.py b/harvey/state.py
index addc8e8..3d1fe91 100644
--- a/harvey/state.py
+++ b/harvey/state.py
@@ -1410,6 +1410,17 @@ class StateManager:
row = await cursor.fetchone()
return row[0] if row else default
+ async def retry_write_failed(self) -> int:
+ """Give every 'write_failed' prospect another try. Returns how many."""
+ async with self._connect() as db:
+ cursor = await db.execute(
+ "UPDATE prospects SET status = 'new', updated_at = ? "
+ "WHERE status = 'write_failed'",
+ (_utcnow().isoformat(),),
+ )
+ await db.commit()
+ return cursor.rowcount
+
async def delete_setting(self, key: str):
async with self._connect() as db:
await db.execute("DELETE FROM settings WHERE key = ?", (key,))
diff --git a/harvey/web/app.js b/harvey/web/app.js
index 817dee2..bc7a9d3 100644
--- a/harvey/web/app.js
+++ b/harvey/web/app.js
@@ -67,7 +67,7 @@ const STATUS = {
meeting: ['Meeting booked', 'note'],
not_interested: ['Not interested', 'bad'],
bounced: ['Bounced', 'bad'],
- write_failed: ["Couldn't write", 'waiting'],
+ write_failed: ["Couldn't write", 'bad'],
// campaigns
draft: ['Draft', 'waiting'],
active: ['Active', 'good'],
diff --git a/tests/test_writer_retry.py b/tests/test_writer_retry.py
index 9575924..e9ac5ed 100644
--- a/tests/test_writer_retry.py
+++ b/tests/test_writer_retry.py
@@ -113,3 +113,46 @@ async def test_attempts_are_counted_per_prospect(state):
await writer.run()
assert await status(state, early) == "write_failed"
assert await status(state, late) == "new"
+
+
+async def test_an_empty_reply_is_an_outage_not_a_bad_draft(state):
+ # On Claude a logout, rate limit, timeout or missing CLI returns "" without
+ # pausing the brain. Only a reply that came back unusable may count.
+ pid = await add(state, 1)
+ brain = FakeBrain(reply=None)
+ brain.last_reply_empty = True
+ writer = Writer(brain, state, CONFIG, None)
+ for _ in range(MAX_WRITE_ATTEMPTS + 2):
+ await writer.run()
+ assert await status(state, pid) == "new"
+
+
+async def test_the_real_brain_reports_whether_the_model_replied(state, monkeypatch):
+ from harvey.brain import Brain
+ from harvey.config import BrainConfig
+ brain = Brain(state, BrainConfig())
+
+ async def silent(*a, **kw):
+ return ""
+
+ async def chatty(*a, **kw):
+ return "Sorry, here are some thoughts instead of JSON."
+
+ monkeypatch.setattr(brain, "think", silent)
+ assert await brain.think_json("x") is None and brain.last_reply_empty is True
+ monkeypatch.setattr(brain, "think", chatty)
+ assert await brain.think_json("x") is None and brain.last_reply_empty is False
+
+
+async def test_given_up_prospects_can_be_retried(state, capsys):
+ pid = await add(state, 1)
+ writer = Writer(FakeBrain(reply="not a sequence"), state, CONFIG, None)
+ for _ in range(MAX_WRITE_ATTEMPTS):
+ await writer.run()
+ assert await status(state, pid) == "write_failed"
+ assert await state.retry_write_failed() == 1
+ assert await status(state, pid) == "new"
+ assert await state.retry_write_failed() == 0