KikoCis commited on
Commit
2aeca9f
Β·
verified Β·
1 Parent(s): 03a714b

Publish Planner-Executor pattern article

Browse files
Files changed (1) hide show
  1. README.md +356 -0
README.md ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: "Planner-Executor: A Two-Agent Pattern for Reliable Email-Driven Automation"
3
+ emoji: πŸ€–
4
+ colorFrom: purple
5
+ colorTo: blue
6
+ sdk: static
7
+ pinned: true
8
+ tags:
9
+ - agents
10
+ - architecture
11
+ - multi-agent
12
+ - planner-executor
13
+ - email-automation
14
+ - claude
15
+ - agentic-ai
16
+ ---
17
+
18
+ # Planner-Executor: A Two-Agent Pattern for Reliable Email-Driven Automation
19
+
20
+ > This pattern is implemented in **ClonAgent** ([clonagent.utopiaia.com](https://clonagent.utopiaia.com)) and has been running in production since July 2025.
21
+ > Source: [github.com/KikoCisBot/clonagent](https://github.com/KikoCisBot/clonagent)
22
+
23
+ ---
24
+
25
+ ## The Problem with Single-Agent Email Loops
26
+
27
+ The naive approach to email-driven AI automation looks like this:
28
+
29
+ ```
30
+ email arrives β†’ launch agent β†’ agent reads, thinks, acts, replies β†’ done
31
+ ```
32
+
33
+ This breaks down quickly in production:
34
+
35
+ - **Long tasks block the inbox**: while Claude is deploying code (which can take minutes), new emails pile up unread
36
+ - **Context collapse**: a single agent session mixes "what should I do?" with "how do I do it?" β€” two very different cognitive modes
37
+ - **No retry logic**: if the action fails mid-way, the whole session is lost
38
+ - **No priority**: email #3 might be urgent but gets queued behind email #1
39
+
40
+ The Planner-Executor pattern solves all of this.
41
+
42
+ ---
43
+
44
+ ## The Pattern
45
+
46
+ ```
47
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
48
+ β”‚ Email Arrives β”‚
49
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
50
+ β”‚ (poller tick, every 60s)
51
+ β–Ό
52
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
53
+ β”‚ SCHEDULER (Planner) β”‚
54
+ β”‚ β”‚
55
+ β”‚ Role: understand + plan β”‚
56
+ β”‚ Input: email thread β”‚
57
+ β”‚ Output: agent-tasks.json (list of structured tasks) β”‚
58
+ β”‚ Duration: seconds β”‚
59
+ β”‚ Blocks: nothing β”‚
60
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
61
+ β”‚ writes agent-tasks.json
62
+ β”‚ (async β€” Scheduler exits)
63
+ β–Ό
64
+ [2 min executor tick]
65
+ β”‚
66
+ β–Ό
67
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
68
+ β”‚ EXECUTOR β”‚
69
+ β”‚ β”‚
70
+ β”‚ Role: execute pending tasks, one by one β”‚
71
+ β”‚ Input: agent-tasks.json β”‚
72
+ β”‚ Output: task results + email replies β”‚
73
+ β”‚ Duration: seconds to minutes β”‚
74
+ β”‚ Blocks: only itself (never the Scheduler) β”‚
75
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
76
+ ```
77
+
78
+ Two separate Claude CLI sessions. Two separate prompts. One shared state file.
79
+
80
+ ---
81
+
82
+ ## Implementation
83
+
84
+ ### The State File: `agent-tasks.json`
85
+
86
+ The only communication channel between Planner and Executor is a JSON file that lives in the agent's workspace:
87
+
88
+ ```json
89
+ {
90
+ "agentId": "btc-signals",
91
+ "plan": "User requested BTC price analysis for the week. One task: generate report and reply.",
92
+ "tasks": [
93
+ {
94
+ "id": "a1b2c3d4-...",
95
+ "title": "Generate weekly BTC analysis",
96
+ "description": "Fetch price data, compute indicators, write summary, reply to thread",
97
+ "priority": 1,
98
+ "status": "pending",
99
+ "threadId": "18f3a2b...",
100
+ "from": "kikocisneros@gmail.com",
101
+ "createdAt": "2026-05-31T09:12:00.000Z"
102
+ }
103
+ ],
104
+ "updatedAt": "2026-05-31T09:12:05.123Z"
105
+ }
106
+ ```
107
+
108
+ **Task statuses**: `pending` β†’ `in-progress` β†’ `done` | `failed`
109
+ **Priority**: `1` = urgent, `2` = normal, `3` = low
110
+
111
+ This file is readable by humans, inspectable at any time, and survives process crashes.
112
+
113
+ ---
114
+
115
+ ### The Planner Prompt
116
+
117
+ The Scheduler (Planner) receives a tightly scoped prompt:
118
+
119
+ ```
120
+ ROL: PLANIFICADOR
121
+
122
+ Nueva comunicaciΓ³n recibida:
123
+ De: kikocisneros@gmail.com
124
+ Asunto: Weekly BTC report please
125
+ ThreadId: 18f3a2b...
126
+
127
+ Tu tarea (sΓ© rΓ‘pido y concreto):
128
+ 1. Lee el email: python3 mail_client.py get-thread "18f3a2b..."
129
+ 2. Lee el fichero de tareas actual: cat agent-tasks.json
130
+ 3. AΓ±ade las tareas necesarias en formato JSON:
131
+ { "id": "<uuid4>", "title": "...", "description": "...",
132
+ "priority": 1, "status": "pending", "threadId": "...",
133
+ "from": "...", "createdAt": "<iso>" }
134
+ - priority 1=urgente, 2=normal, 3=baja
135
+ - No dupliques tareas ya existentes para el mismo threadId
136
+ 4. Actualiza el campo "plan" con tu anΓ‘lisis breve
137
+ 5. Escribe el fichero actualizado
138
+ 6. Sal cuando hayas terminado de planificar.
139
+ ```
140
+
141
+ Key constraints on the Planner:
142
+ - **It never executes**. It only reads and writes `agent-tasks.json`
143
+ - **It deduplicates**: checks existing tasks by `threadId` before adding new ones
144
+ - **It exits immediately** after writing the plan
145
+
146
+ ---
147
+
148
+ ### The Executor Prompt
149
+
150
+ The Executor picks up `agent-tasks.json` and works through it:
151
+
152
+ ```
153
+ ROL: EJECUTOR
154
+
155
+ Ejecuta las tareas pendientes de agent-tasks.json.
156
+
157
+ Proceso (repite hasta que no haya mΓ‘s tareas pendientes):
158
+ 1. Lee agent-tasks.json
159
+ 2. Toma la tarea con status="pending" de mayor prioridad (1=urgente)
160
+ 3. Actualiza su status a "in-progress" en el fichero
161
+ 4. Ejecuta la tarea
162
+ 5. Actualiza: status="done" o "failed", result="descripciΓ³n", updatedAt=<iso>
163
+ 6. Si quedan mΓ‘s tareas pending, vuelve al paso 1
164
+ 7. Cuando no haya ninguna tarea pending, sal
165
+
166
+ Reglas:
167
+ - Marca "failed" (no crashees) si algo falla, continΓΊa con la siguiente
168
+ - Usa mail_client.py para enviar respuestas de email
169
+ ```
170
+
171
+ The Executor's loop is explicit in the prompt: it keeps going until the queue is empty. This means one Executor session can drain multiple tasks that accumulated while it was sleeping.
172
+
173
+ ---
174
+
175
+ ## Timing and Concurrency
176
+
177
+ ```
178
+ T+0s Email arrives
179
+ T+60s Poller tick detects new email β†’ launches Scheduler
180
+ T+75s Scheduler reads email, writes tasks β†’ exits
181
+ T+120s Executor tick fires β†’ sees pending tasks β†’ launches Executor
182
+ T+180s Executor completes tasks, replies to email β†’ exits
183
+ T+240s Executor tick fires β†’ no pending tasks β†’ skips (noop)
184
+ ```
185
+
186
+ Concurrency is controlled by boolean flags:
187
+
188
+ ```javascript
189
+ let schedulerRunning = false;
190
+ let executorRunning = false;
191
+
192
+ // Only one Scheduler active per agent at a time
193
+ if (agentSessions.isActive(skillId, 'scheduler')) {
194
+ console.log(`scheduler already active, skipping`);
195
+ return null;
196
+ }
197
+
198
+ // Only one Executor active per agent at a time
199
+ if (agentSessions.isActive(skillId, 'executor')) {
200
+ console.log(`executor already active, skipping`);
201
+ return null;
202
+ }
203
+ ```
204
+
205
+ Crucially: **the Scheduler and Executor can run simultaneously**. While the Executor is working on task #1, the Scheduler can plan tasks #2 and #3. They only share the file β€” they never block each other.
206
+
207
+ ---
208
+
209
+ ## Session Resumption
210
+
211
+ Both agents support `--resume`, which continues the same Claude conversation across invocations:
212
+
213
+ ```javascript
214
+ const resumeClaudeId = sess.schedulerClaudeId || null;
215
+
216
+ const args = [
217
+ '--output-format', 'stream-json',
218
+ '--dangerously-skip-permissions',
219
+ '--model', resolvedModel,
220
+ ];
221
+ if (resumeClaudeId) args.push('--resume', resumeClaudeId);
222
+ args.push('-p', `/${skillId}\n\n${prompt}`);
223
+ ```
224
+
225
+ This means the Executor doesn't start cold each time. It already knows the agent's project structure, coding conventions, and recent context from the previous session. The more emails processed, the more efficient it becomes.
226
+
227
+ ---
228
+
229
+ ## Why Two Agents Instead of One?
230
+
231
+ | Concern | Single Agent | Planner-Executor |
232
+ |---------|-------------|-----------------|
233
+ | New email while executing | Missed until session ends | Scheduler handles it immediately |
234
+ | Task priority | FIFO only | Explicit priority 1-2-3 |
235
+ | Partial failure | Whole session fails | Task marked "failed", next task continues |
236
+ | Long-running tasks | Blocks everything | Executor runs async, Scheduler stays free |
237
+ | Debugging | One long session, hard to inspect | `agent-tasks.json` is human-readable at all times |
238
+ | Cost control | Hard to limit mid-session | Per-task granularity, monthly spend limit enforced before each launch |
239
+
240
+ ---
241
+
242
+ ## Spending Limits
243
+
244
+ Before launching either agent, the system checks monthly spend:
245
+
246
+ ```javascript
247
+ if (agent.spendingLimitMonthly != null) {
248
+ const spent = await getMonthlySpend(skillId);
249
+ if (spent >= agent.spendingLimitMonthly) {
250
+ console.warn(`monthly limit $${agent.spendingLimitMonthly} reached β€” launch blocked`);
251
+ return null;
252
+ }
253
+ }
254
+ ```
255
+
256
+ This means you can run agents with hard cost caps. The Planner is cheap (reads email, writes JSON). The Executor is where the real work β€” and cost β€” happens.
257
+
258
+ ---
259
+
260
+ ## The `agent-tasks.json` as a Coordination Protocol
261
+
262
+ The file acts as a simple, durable message queue. It is:
263
+
264
+ - **Persistent**: survives process restarts
265
+ - **Inspectable**: `cat agent-tasks.json` shows exactly what the agent is doing
266
+ - **Editable by hand**: add a task manually and the Executor will pick it up
267
+ - **Self-documenting**: the `plan` field explains the agent's current understanding
268
+
269
+ This replaces Redis, RabbitMQ, or any external queue system with a 30-line module.
270
+
271
+ ---
272
+
273
+ ## Complete Flow Diagram
274
+
275
+ ```
276
+ Inbox (IMAP)
277
+ β”‚
278
+ β”‚ (polled every 60s)
279
+ β–Ό
280
+ gmail-poller.js
281
+ β”‚
282
+ β”œβ”€ Is it a !command? β†’ handle locally, reply, mark read
283
+ β”‚
284
+ └─ Is sender authorized? β†’ yes
285
+ β”‚
286
+ β–Ό
287
+ launchScheduler(agent, { from, subject, threadId })
288
+ β”‚
289
+ β”‚ (Claude CLI, ROL: PLANIFICADOR)
290
+ β”‚ reads email thread via mail_client.py
291
+ β”‚ reads agent-tasks.json
292
+ β”‚ appends new tasks with priority
293
+ β”‚ writes agent-tasks.json
294
+ └─ exits
295
+
296
+ (2 min later...)
297
+
298
+ tickExecutor()
299
+ β”‚
300
+ β”œβ”€ hasPending(agentId)? β†’ no β†’ skip
301
+ β”‚
302
+ └─ yes
303
+ β”‚
304
+ β–Ό
305
+ launchExecutor(agent)
306
+ β”‚
307
+ β”‚ (Claude CLI, ROL: EJECUTOR)
308
+ β”‚ reads agent-tasks.json
309
+ β”‚ picks highest-priority pending task
310
+ β”‚ marks in-progress
311
+ β”‚ executes (code, email reply, API call, deploy...)
312
+ β”‚ marks done/failed with result
313
+ β”‚ loops until queue empty
314
+ └─ exits
315
+ ```
316
+
317
+ ---
318
+
319
+ ## What This Enables in Practice
320
+
321
+ An agent built on this pattern can:
322
+
323
+ 1. **Handle multiple simultaneous email threads** β€” each gets planned independently, executed in priority order
324
+ 2. **Survive long-running tasks** β€” a deploy that takes 3 minutes doesn't block other planning
325
+ 3. **Recover from failures gracefully** β€” failed tasks are logged, not lost
326
+ 4. **Learn across sessions** β€” `--resume` means the Executor accumulates context over time
327
+ 5. **Be audited** β€” `agent-tasks.json` is the full audit log of what was planned and what happened
328
+
329
+ ---
330
+
331
+ ## Implementation in ClonAgent
332
+
333
+ The full implementation is open source:
334
+
335
+ | File | Role |
336
+ |------|------|
337
+ | [`server/lib/gmail-poller.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/gmail-poller.js) | Orchestrator: poller ticks, triggers Scheduler and Executor |
338
+ | [`server/lib/relay-client.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/relay-client.js) | Launches Scheduler and Executor via Claude CLI |
339
+ | [`server/lib/task-queue.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/task-queue.js) | Reads/writes `agent-tasks.json` |
340
+ | [`server/lib/agent-sessions.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/agent-sessions.js) | Tracks active Scheduler/Executor sessions, prevents overlaps |
341
+
342
+ ---
343
+
344
+ ## Conclusion
345
+
346
+ The Planner-Executor pattern is a practical approach to building reliable AI agents that operate on asynchronous, real-world inputs like email.
347
+
348
+ 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.
349
+
350
+ A shared JSON file replaces complex message queue infrastructure. Claude CLI's `--resume` flag provides session continuity without a database. And explicit priority fields give the agent the ability to triage, just like a human would.
351
+
352
+ The result is an agent that feels less like a script and more like a colleague: it reads your email, decides what matters, and gets to work β€” without blocking, without crashing, and without forgetting what it learned yesterday.
353
+
354
+ ---
355
+
356
+ *Implementation: [ClonAgent](https://clonagent.utopiaia.com) β€” open source at [github.com/KikoCisBot/clonagent](https://github.com/KikoCisBot/clonagent)*