The dataset is currently empty. Upload or create new data files. Then, you will be able to explore them in the Dataset Viewer.
- The Problem with Single-Agent Email Loops
- The Pattern
- Implementation
- Task Dependencies: Basic DAG
- Idempotency: Handling Re-delivered Emails
- Per-Task Progress Logging
- Crash Recovery
- Atomic Writes
- Timing and Concurrency
- Session Resumption
- Why Two Agents Instead of One?
- Spending Limits
- Complete Flow Diagram
- Implementation in ClonAgent
- Conclusion
Planner-Executor: A Two-Agent Pattern for Reliable Email-Driven Automation
This pattern is implemented in ClonAgent (clonagent.utopiaia.com) and has been running in production since July 2025.
Source: github.com/KikoCisBot/clonagent
The Problem with Single-Agent Email Loops
The naive approach to email-driven AI automation looks like this:
email arrives → launch agent → agent reads, thinks, acts, replies → done
This breaks down quickly in production:
- Long tasks block the inbox: while Claude is deploying code (which can take minutes), new emails pile up unread
- Context collapse: a single agent session mixes "what should I do?" with "how do I do it?" — two very different cognitive modes
- No retry logic: if the action fails mid-way, the whole session is lost
- No priority: email #3 might be urgent but gets queued behind email #1
The Planner-Executor pattern solves all of this.
The Pattern
┌─────────────────────────────────────────────────────────────┐
│ Email Arrives │
└──────────────────────────┬──────────────────────────────────┘
│ (poller tick, every 60s)
▼
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULER (Planner) │
│ │
│ Role: understand + plan │
│ Input: email thread │
│ Output: agent-tasks.json (list of structured tasks) │
│ Duration: seconds │
│ Blocks: nothing │
└──────────────────────────┬──────────────────────────────────┘
│ writes agent-tasks.json
│ (async — Scheduler exits)
▼
[2 min executor tick]
│
▼
┌─────────────────────────────────────────────────────────────┐
│ EXECUTOR │
│ │
│ Role: execute pending tasks, one by one │
│ Input: agent-tasks.json │
│ Output: task results + email replies │
│ Duration: seconds to minutes │
│ Blocks: only itself (never the Scheduler) │
└─────────────────────────────────────────────────────────────┘
Two separate Claude CLI sessions. Two separate prompts. One shared state file.
Implementation
The State File: agent-tasks.json
The only communication channel between Planner and Executor is a JSON file that lives in the agent's workspace:
{
"agentId": "btc-signals",
"plan": "User requested BTC price analysis for the week. One task: generate report and reply.",
"tasks": [
{
"id": "a1b2c3d4-...",
"title": "Generate weekly BTC analysis",
"description": "Fetch price data, compute indicators, write summary, reply to thread",
"priority": 1,
"status": "pending",
"threadId": "18f3a2b...",
"from": "kikocisneros@gmail.com",
"createdAt": "2026-05-31T09:12:00.000Z",
"retries": 0,
"log": [],
"dependsOn": []
}
],
"updatedAt": "2026-05-31T09:12:05.123Z"
}
Task statuses: pending → in-progress → done | failed | skipped
Priority: 1 = urgent, 2 = normal, 3 = lowretries: auto-incremented on failure and recoverylog[]: timestamped progress entries written by the Executor during executiondependsOn[]: IDs of tasks that must be done before this one is eligible
This file is readable by humans, inspectable at any time, and survives process crashes.
The Planner Prompt
The Scheduler receives a tightly scoped prompt that constrains it to planning only:
ROL: PLANIFICADOR
Nueva comunicación recibida:
De: kikocisneros@gmail.com
Asunto: Weekly BTC report please
ThreadId: 18f3a2b...
Tu tarea (sé rápido y concreto):
1. Lee el email: python3 mail_client.py get-thread "18f3a2b..."
2. Lee el fichero de tareas actual: cat agent-tasks.json
3. Decide qué tareas hay que hacer. Por cada tarea, añádela con esta forma:
{
"id": "<uuid4>", "title": "...", "description": "...",
"priority": 1, "status": "pending",
"threadId": "...", "from": "...", "createdAt": "<iso>",
"retries": 0, "log": [],
"dependsOn": [] ← IDs of other tasks that must be done first
}
- priority: 1=urgent, 2=normal, 3=low
- dependsOn: list task IDs in this file that must be "done" before this one runs
- Do NOT add tasks if threadId already exists with any status other than "failed"
- If threadId exists with status "failed", add nothing — the Executor will retry automatically
4. Actualiza el campo "plan" con tu análisis breve
5. Escribe el fichero actualizado
6. Sal cuando hayas terminado de planificar.
Key constraints on the Planner:
- It never executes. It only reads and writes
agent-tasks.json - It deduplicates: checks existing tasks by
threadIdbefore adding new ones - It models dependencies: can express "deploy after tests pass" with
dependsOn - It exits immediately after writing the plan
The Executor Prompt
The Executor picks up agent-tasks.json and works through it, respecting dependencies and logging progress:
ROL: EJECUTOR
Ejecuta las tareas pendientes de agent-tasks.json.
Proceso (repite hasta que no haya más tareas ejecutables):
1. Lee agent-tasks.json
2. Toma la tarea con status="pending" de mayor prioridad (1=urgente)
cuyo dependsOn[] esté vacío o todas sus deps estén "done".
Si ninguna cumple esto, sal.
3. Actualiza status a "in-progress"; añade al log[]: { "ts": "<iso>", "msg": "Iniciando: <título>" }
4. Ejecuta la tarea; añade entradas al log[] con progreso real durante la ejecución
5. Al terminar:
- status: "done" o "failed"
- result: descripción breve del resultado
- updatedAt: <iso>
- Si retries >= 3: status="failed", result="Max retries reached: <reason>"
6. Si quedan tareas pending ejecutables, vuelve al paso 1
7. Cuando no haya ninguna tarea pending ejecutable, sal
Reglas:
- Marca "failed" (no crashees) si algo falla, continúa con la siguiente
- El campo log[] es visible al usuario — úsalo para reflejar progreso real
- Usa mail_client.py para enviar respuestas de email
Task Dependencies: Basic DAG
The dependsOn field turns agent-tasks.json into a minimal DAG (directed acyclic graph) without any external scheduler:
[
{ "id": "task-run-tests", "title": "Run test suite", "status": "pending", "dependsOn": [] },
{ "id": "task-deploy-prod","title": "Deploy to prod", "status": "pending", "dependsOn": ["task-run-tests"] },
{ "id": "task-notify", "title": "Reply with result", "status": "pending", "dependsOn": ["task-deploy-prod"] }
]
The Executor resolves this automatically:
function getNextTask(agentId) {
const queue = read(agentId);
const { tasks } = queue;
let dirty = false;
const pending = tasks
.filter(t => t.status === 'pending')
.sort((a, b) => (a.priority || 2) - (b.priority || 2));
let result = null;
for (const task of pending) {
if (!task.dependsOn?.length) { result = task; break; }
const deps = task.dependsOn.map(id => tasks.find(t => t.id === id));
const failedDep = deps.find(d => d?.status === 'failed');
if (failedDep) {
// Auto-skip tasks whose dependency failed — no manual intervention needed
task.status = 'skipped';
task.result = `Skipped: dependency "${failedDep.title}" failed`;
task.log.push({ ts: new Date().toISOString(), msg: task.result });
dirty = true;
continue;
}
if (deps.every(d => d?.status === 'done')) { result = task; break; }
}
if (dirty) write(agentId, queue);
return result;
}
If task-run-tests fails, task-deploy-prod and task-notify are automatically skipped. No cascade failure, no stuck queue.
Idempotency: Handling Re-delivered Emails
Email systems re-deliver. Networks retry. The Planner must be idempotent:
function addTask(agentId, newTask) {
const queue = read(agentId);
const existing = queue.tasks.find(t => t.threadId === newTask.threadId);
if (existing) {
if (existing.status === 'failed') {
// Explicit retry: reset to pending, increment retries counter
existing.status = 'pending';
existing.retries = (existing.retries || 0) + 1;
existing.log.push({ ts: new Date().toISOString(), msg: `Retry #${existing.retries}` });
write(agentId, queue);
}
// For any other status: silent no-op (dedup)
return queue;
}
queue.tasks.push({ retries: 0, log: [], dependsOn: [], ...newTask });
write(agentId, queue);
return queue;
}
The same threadId arriving twice results in one task. A failed task arriving again resets to pending with retries++. The retries field lets the Executor apply exponential backoff or hard-stop after N attempts.
Per-Task Progress Logging
The log[] array makes task execution fully observable without any external logging infrastructure:
{
"id": "task-deploy-prod",
"status": "done",
"log": [
{ "ts": "2026-05-31T10:00:01Z", "msg": "Iniciando: Deploy to prod" },
{ "ts": "2026-05-31T10:00:08Z", "msg": "SSH connected to 145.239.65.26" },
{ "ts": "2026-05-31T10:00:31Z", "msg": "docker pull done (847MB)" },
{ "ts": "2026-05-31T10:00:38Z", "msg": "Containers restarted, health check passed" }
],
"result": "Deployed v2.1.4 successfully"
}
Live monitoring: watch -n1 'cat agent-tasks.json | jq ".tasks[0].log[-3:]"'
No Grafana. No Datadog. The file is the dashboard.
Crash Recovery
When the server restarts, tasks that were in-progress (mid-execution) need to be reset. A one-time recovery pass runs at startup:
function recoverStaleTasks(agentId) {
const queue = read(agentId);
let recovered = 0;
for (const task of queue.tasks) {
if (task.status !== 'in-progress') continue;
task.status = 'pending';
task.retries = (task.retries || 0) + 1;
task.log.push({ ts: new Date().toISOString(), msg: 'Recovered from stale in-progress (server restart)' });
recovered++;
}
if (recovered > 0) write(agentId, queue);
return recovered;
}
// In startPoller():
function startPoller() {
const agents = listAgents().filter(a => a.enabled && a.ready);
for (const a of agents) taskQueue.recoverStaleTasks(a.id);
// ... start cron jobs
}
A crash mid-deploy becomes a retried deploy, not a lost task.
Atomic Writes
The JSON file is the single source of truth. Corruption on a mid-write crash would break everything. The fix: write to a .tmp file, then rename:
function write(agentId, data) {
const f = filePath(agentId);
const tmp = f + '.tmp';
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify({ ...data, updatedAt: new Date().toISOString() }, null, 2));
fs.renameSync(tmp, f); // atomic on POSIX
}
fs.renameSync is atomic on POSIX filesystems: readers either see the old file or the new one, never a partial write.
Timing and Concurrency
T+0s Email arrives
T+60s Poller tick detects new email → launches Scheduler
T+75s Scheduler reads email, writes tasks → exits
T+120s Executor tick fires → sees pending tasks → launches Executor
T+180s Executor completes tasks, replies to email → exits
T+240s Executor tick fires → no pending tasks → skips (noop)
Concurrency is controlled by in-memory flags that survive the process lifetime:
// Only one Scheduler active per agent at a time
if (agentSessions.isActive(skillId, 'scheduler')) return null;
// Only one Executor active per agent at a time
if (agentSessions.isActive(skillId, 'executor')) return null;
Crucially: the Scheduler and Executor can run simultaneously. While the Executor is working on task #1, the Scheduler can plan tasks #2 and #3.
Session Resumption
Both agents support --resume, which continues the same Claude conversation across invocations:
const resumeClaudeId = sess.schedulerClaudeId || null;
const args = [
'--output-format', 'stream-json',
'--dangerously-skip-permissions',
'--model', resolvedModel,
];
if (resumeClaudeId) args.push('--resume', resumeClaudeId);
The Executor doesn't start cold. It already knows the project structure, conventions, and recent decisions. The more emails processed, the more efficient it becomes — without a database.
Why Two Agents Instead of One?
| Concern | Single Agent | Planner-Executor |
|---|---|---|
| New email while executing | Missed until session ends | Scheduler handles it immediately |
| Task priority | FIFO only | Explicit priority 1-2-3 |
| Task dependencies | None | dependsOn[] with auto-skip on failure |
| Partial failure | Whole session fails | Task marked failed, next task continues |
| Crash mid-task | Task lost silently | Reset to pending on restart, retries++ |
| Long-running tasks | Blocks everything | Executor runs async, Scheduler stays free |
| Debugging | One long session, hard to inspect | agent-tasks.json + log[] per task |
| Cost control | Hard to limit mid-session | Monthly spend limit checked before each launch |
| Re-delivered emails | May process twice | Dedup by threadId, idempotent |
Spending Limits
Before launching either agent, the system checks monthly spend:
if (agent.spendingLimitMonthly != null) {
const spent = await getMonthlySpend(skillId); // async — must be awaited
if (spent >= agent.spendingLimitMonthly) {
console.warn(`monthly limit $${agent.spendingLimitMonthly} reached — launch blocked`);
return null;
}
}
The Planner is cheap (reads email, writes JSON — a few cents). The Executor is where real work — and cost — happens. Checking before each launch gives per-session cost granularity.
Complete Flow Diagram
Inbox (IMAP/Gmail)
│
│ (polled every 60s)
▼
gmail-poller.js
│
├─ Is it a !command? → handle locally, reply, mark read
│
└─ Is sender authorized? → yes
│
▼
launchScheduler(agent, { from, subject, threadId })
│
│ (Claude CLI, ROL: PLANIFICADOR)
│ reads email thread via mail_client.py
│ reads agent-tasks.json
│ deduplicates by threadId
│ appends tasks with priority + dependsOn
│ writes agent-tasks.json (atomic)
└─ exits
(2 min later...)
tickExecutor()
│
├─ hasPendingReady(agentId)? → no → skip
│
└─ yes
│
▼
launchExecutor(agent)
│
│ (Claude CLI, ROL: EJECUTOR)
│ reads agent-tasks.json
│ picks highest-priority pending task with deps satisfied
│ marks in-progress, appends to log[]
│ executes (code, email reply, API call, deploy...)
│ marks done/failed with result + final log entry
│ loops until queue empty or no more executable tasks
└─ exits
Implementation in ClonAgent
The full implementation is open source:
| File | Role |
|---|---|
server/lib/gmail-poller.js |
Orchestrator: poller ticks, triggers Scheduler and Executor, crash recovery on startup |
server/lib/relay-client.js |
Launches Scheduler and Executor via Claude CLI with role-specific prompts |
server/lib/task-queue.js |
Atomic reads/writes of agent-tasks.json, idempotent addTask, dependency-aware getNextTask, crash recovery |
server/lib/agent-sessions.js |
Tracks active Scheduler/Executor sessions, prevents overlaps |
Conclusion
The Planner-Executor pattern is a practical approach to building reliable AI agents that operate on asynchronous, real-world inputs like email.
The key insight is that planning and execution are different cognitive tasks that benefit from separation — not just conceptually, but as separate model invocations with different prompts, different time horizons, and different failure modes.
Production use has taught us additional lessons:
- Atomic writes (temp + rename) prevent file corruption that would break the whole agent
- Idempotency by
threadIdis mandatory — email systems re-deliver, networks retry log[]per task makes debugging possible without any external infrastructuredependsOn[]enables multi-step workflows without Airflow or Temporal- Crash recovery at startup means a server restart doesn't lose work in progress
awaitthe spend check — async bugs here mean spending limits silently don't apply
A shared JSON file replaces complex message queue infrastructure. Claude CLI's --resume flag provides session continuity without a database. Explicit priority and dependency fields give the agent the ability to triage and sequence, just like a human would.
The result is an agent that feels less like a script and more like a colleague: it reads your email, decides what matters, plans the work, and executes — without blocking, without crashing, and without forgetting what it learned yesterday.
Implementation: ClonAgent — open source at github.com/KikoCisBot/clonagent
- Downloads last month
- 27