| --- |
| title: "Planner-Executor: A Two-Agent Pattern for Reliable Email-Driven Automation" |
| emoji: π€ |
| colorFrom: purple |
| colorTo: blue |
| sdk: static |
| pinned: true |
| tags: |
| - agents |
| - architecture |
| - multi-agent |
| - planner-executor |
| - email-automation |
| - claude |
| - agentic-ai |
| --- |
| |
| # Planner-Executor: A Two-Agent Pattern for Reliable Email-Driven Automation |
|
|
| > This pattern is implemented in **ClonAgent** ([clonagent.utopiaia.com](https://clonagent.utopiaia.com)) and has been running in production since July 2025. |
| > Source: [github.com/KikoCisBot/clonagent](https://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: |
|
|
| ```json |
| { |
| "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` = low |
| **`retries`**: auto-incremented on failure and recovery |
| **`log[]`**: timestamped progress entries written by the Executor during execution |
| **`dependsOn[]`**: 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 `threadId` before 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: |
|
|
| ```json |
| [ |
| { "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: |
|
|
| ```javascript |
| 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: |
|
|
| ```javascript |
| 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: |
|
|
| ```json |
| { |
| "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: |
|
|
| ```javascript |
| 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`: |
|
|
| ```javascript |
| 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: |
|
|
| ```javascript |
| // 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: |
|
|
| ```javascript |
| 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: |
|
|
| ```javascript |
| 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`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/gmail-poller.js) | Orchestrator: poller ticks, triggers Scheduler and Executor, crash recovery on startup | |
| | [`server/lib/relay-client.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/relay-client.js) | Launches Scheduler and Executor via Claude CLI with role-specific prompts | |
| | [`server/lib/task-queue.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/task-queue.js) | Atomic reads/writes of `agent-tasks.json`, idempotent `addTask`, dependency-aware `getNextTask`, crash recovery | |
| | [`server/lib/agent-sessions.js`](https://github.com/KikoCisBot/clonagent/blob/main/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 `threadId`** is mandatory β email systems re-deliver, networks retry |
| - **`log[]` per task** makes debugging possible without any external infrastructure |
| - **`dependsOn[]`** enables multi-step workflows without Airflow or Temporal |
| - **Crash recovery** at startup means a server restart doesn't lose work in progress |
| - **`await` the 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](https://clonagent.utopiaia.com) β open source at [github.com/KikoCisBot/clonagent](https://github.com/KikoCisBot/clonagent)* |
|
|