KikoCis commited on
Commit
aa0b221
Β·
1 Parent(s): 2aeca9f

Production lessons: atomic writes, idempotency, dependsOn DAG, log[], crash recovery

Browse files
Files changed (1) hide show
  1. README.md +228 -76
README.md CHANGED
@@ -98,15 +98,21 @@ The only communication channel between Planner and Executor is a JSON file that
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
 
@@ -114,7 +120,7 @@ This file is readable by humans, inspectable at any time, and survives process c
114
 
115
  ### The Planner Prompt
116
 
117
- The Scheduler (Planner) receives a tightly scoped prompt:
118
 
119
  ```
120
  ROL: PLANIFICADOR
@@ -127,12 +133,18 @@ Nueva comunicaciΓ³n recibida:
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.
@@ -141,34 +153,196 @@ Tu tarea (sΓ© rΓ‘pido y concreto):
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
 
@@ -183,26 +357,17 @@ 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
 
@@ -219,10 +384,9 @@ const args = [
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
 
@@ -232,10 +396,13 @@ This means the Executor doesn't start cold each time. It already knows the agent
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
 
@@ -245,7 +412,7 @@ 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;
@@ -253,27 +420,14 @@ if (agent.spendingLimitMonthly != null) {
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
  β–Ό
@@ -289,15 +443,16 @@ gmail-poller.js
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
  β”‚
@@ -306,37 +461,25 @@ tickExecutor()
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
  ---
@@ -347,9 +490,18 @@ The Planner-Executor pattern is a practical approach to building reliable AI age
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
 
 
98
  "status": "pending",
99
  "threadId": "18f3a2b...",
100
  "from": "kikocisneros@gmail.com",
101
+ "createdAt": "2026-05-31T09:12:00.000Z",
102
+ "retries": 0,
103
+ "log": [],
104
+ "dependsOn": []
105
  }
106
  ],
107
  "updatedAt": "2026-05-31T09:12:05.123Z"
108
  }
109
  ```
110
 
111
+ **Task statuses**: `pending` β†’ `in-progress` β†’ `done` | `failed` | `skipped`
112
+ **Priority**: `1` = urgent, `2` = normal, `3` = low
113
+ **`retries`**: auto-incremented on failure and recovery
114
+ **`log[]`**: timestamped progress entries written by the Executor during execution
115
+ **`dependsOn[]`**: IDs of tasks that must be `done` before this one is eligible
116
 
117
  This file is readable by humans, inspectable at any time, and survives process crashes.
118
 
 
120
 
121
  ### The Planner Prompt
122
 
123
+ The Scheduler receives a tightly scoped prompt that constrains it to planning only:
124
 
125
  ```
126
  ROL: PLANIFICADOR
 
133
  Tu tarea (sΓ© rΓ‘pido y concreto):
134
  1. Lee el email: python3 mail_client.py get-thread "18f3a2b..."
135
  2. Lee el fichero de tareas actual: cat agent-tasks.json
136
+ 3. Decide quΓ© tareas hay que hacer. Por cada tarea, aΓ±Γ‘dela con esta forma:
137
+ {
138
+ "id": "<uuid4>", "title": "...", "description": "...",
139
+ "priority": 1, "status": "pending",
140
+ "threadId": "...", "from": "...", "createdAt": "<iso>",
141
+ "retries": 0, "log": [],
142
+ "dependsOn": [] ← IDs of other tasks that must be done first
143
+ }
144
+ - priority: 1=urgent, 2=normal, 3=low
145
+ - dependsOn: list task IDs in this file that must be "done" before this one runs
146
+ - Do NOT add tasks if threadId already exists with any status other than "failed"
147
+ - If threadId exists with status "failed", add nothing β€” the Executor will retry automatically
148
  4. Actualiza el campo "plan" con tu anΓ‘lisis breve
149
  5. Escribe el fichero actualizado
150
  6. Sal cuando hayas terminado de planificar.
 
153
  Key constraints on the Planner:
154
  - **It never executes**. It only reads and writes `agent-tasks.json`
155
  - **It deduplicates**: checks existing tasks by `threadId` before adding new ones
156
+ - **It models dependencies**: can express "deploy after tests pass" with `dependsOn`
157
  - **It exits immediately** after writing the plan
158
 
159
  ---
160
 
161
  ### The Executor Prompt
162
 
163
+ The Executor picks up `agent-tasks.json` and works through it, respecting dependencies and logging progress:
164
 
165
  ```
166
  ROL: EJECUTOR
167
 
168
  Ejecuta las tareas pendientes de agent-tasks.json.
169
 
170
+ Proceso (repite hasta que no haya mΓ‘s tareas ejecutables):
171
  1. Lee agent-tasks.json
172
  2. Toma la tarea con status="pending" de mayor prioridad (1=urgente)
173
+ cuyo dependsOn[] estΓ© vacΓ­o o todas sus deps estΓ©n "done".
174
+ Si ninguna cumple esto, sal.
175
+ 3. Actualiza status a "in-progress"; aΓ±ade al log[]: { "ts": "<iso>", "msg": "Iniciando: <tΓ­tulo>" }
176
+ 4. Ejecuta la tarea; aΓ±ade entradas al log[] con progreso real durante la ejecuciΓ³n
177
+ 5. Al terminar:
178
+ - status: "done" o "failed"
179
+ - result: descripciΓ³n breve del resultado
180
+ - updatedAt: <iso>
181
+ - Si retries >= 3: status="failed", result="Max retries reached: <reason>"
182
+ 6. Si quedan tareas pending ejecutables, vuelve al paso 1
183
+ 7. Cuando no haya ninguna tarea pending ejecutable, sal
184
 
185
  Reglas:
186
  - Marca "failed" (no crashees) si algo falla, continΓΊa con la siguiente
187
+ - El campo log[] es visible al usuario β€” ΓΊsalo para reflejar progreso real
188
  - Usa mail_client.py para enviar respuestas de email
189
  ```
190
 
191
+ ---
192
+
193
+ ## Task Dependencies: Basic DAG
194
+
195
+ The `dependsOn` field turns `agent-tasks.json` into a minimal DAG (directed acyclic graph) without any external scheduler:
196
+
197
+ ```json
198
+ [
199
+ { "id": "task-run-tests", "title": "Run test suite", "status": "pending", "dependsOn": [] },
200
+ { "id": "task-deploy-prod","title": "Deploy to prod", "status": "pending", "dependsOn": ["task-run-tests"] },
201
+ { "id": "task-notify", "title": "Reply with result", "status": "pending", "dependsOn": ["task-deploy-prod"] }
202
+ ]
203
+ ```
204
+
205
+ The Executor resolves this automatically:
206
+
207
+ ```javascript
208
+ function getNextTask(agentId) {
209
+ const queue = read(agentId);
210
+ const { tasks } = queue;
211
+ let dirty = false;
212
+
213
+ const pending = tasks
214
+ .filter(t => t.status === 'pending')
215
+ .sort((a, b) => (a.priority || 2) - (b.priority || 2));
216
+
217
+ let result = null;
218
+ for (const task of pending) {
219
+ if (!task.dependsOn?.length) { result = task; break; }
220
+
221
+ const deps = task.dependsOn.map(id => tasks.find(t => t.id === id));
222
+ const failedDep = deps.find(d => d?.status === 'failed');
223
+
224
+ if (failedDep) {
225
+ // Auto-skip tasks whose dependency failed β€” no manual intervention needed
226
+ task.status = 'skipped';
227
+ task.result = `Skipped: dependency "${failedDep.title}" failed`;
228
+ task.log.push({ ts: new Date().toISOString(), msg: task.result });
229
+ dirty = true;
230
+ continue;
231
+ }
232
+
233
+ if (deps.every(d => d?.status === 'done')) { result = task; break; }
234
+ }
235
+
236
+ if (dirty) write(agentId, queue);
237
+ return result;
238
+ }
239
+ ```
240
+
241
+ If `task-run-tests` fails, `task-deploy-prod` and `task-notify` are automatically skipped. No cascade failure, no stuck queue.
242
+
243
+ ---
244
+
245
+ ## Idempotency: Handling Re-delivered Emails
246
+
247
+ Email systems re-deliver. Networks retry. The Planner must be idempotent:
248
+
249
+ ```javascript
250
+ function addTask(agentId, newTask) {
251
+ const queue = read(agentId);
252
+ const existing = queue.tasks.find(t => t.threadId === newTask.threadId);
253
+
254
+ if (existing) {
255
+ if (existing.status === 'failed') {
256
+ // Explicit retry: reset to pending, increment retries counter
257
+ existing.status = 'pending';
258
+ existing.retries = (existing.retries || 0) + 1;
259
+ existing.log.push({ ts: new Date().toISOString(), msg: `Retry #${existing.retries}` });
260
+ write(agentId, queue);
261
+ }
262
+ // For any other status: silent no-op (dedup)
263
+ return queue;
264
+ }
265
+
266
+ queue.tasks.push({ retries: 0, log: [], dependsOn: [], ...newTask });
267
+ write(agentId, queue);
268
+ return queue;
269
+ }
270
+ ```
271
+
272
+ 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.
273
+
274
+ ---
275
+
276
+ ## Per-Task Progress Logging
277
+
278
+ The `log[]` array makes task execution fully observable without any external logging infrastructure:
279
+
280
+ ```json
281
+ {
282
+ "id": "task-deploy-prod",
283
+ "status": "done",
284
+ "log": [
285
+ { "ts": "2026-05-31T10:00:01Z", "msg": "Iniciando: Deploy to prod" },
286
+ { "ts": "2026-05-31T10:00:08Z", "msg": "SSH connected to 145.239.65.26" },
287
+ { "ts": "2026-05-31T10:00:31Z", "msg": "docker pull done (847MB)" },
288
+ { "ts": "2026-05-31T10:00:38Z", "msg": "Containers restarted, health check passed" }
289
+ ],
290
+ "result": "Deployed v2.1.4 successfully"
291
+ }
292
+ ```
293
+
294
+ Live monitoring: `watch -n1 'cat agent-tasks.json | jq ".tasks[0].log[-3:]"'`
295
+
296
+ No Grafana. No Datadog. The file is the dashboard.
297
+
298
+ ---
299
+
300
+ ## Crash Recovery
301
+
302
+ When the server restarts, tasks that were `in-progress` (mid-execution) need to be reset. A one-time recovery pass runs at startup:
303
+
304
+ ```javascript
305
+ function recoverStaleTasks(agentId) {
306
+ const queue = read(agentId);
307
+ let recovered = 0;
308
+ for (const task of queue.tasks) {
309
+ if (task.status !== 'in-progress') continue;
310
+ task.status = 'pending';
311
+ task.retries = (task.retries || 0) + 1;
312
+ task.log.push({ ts: new Date().toISOString(), msg: 'Recovered from stale in-progress (server restart)' });
313
+ recovered++;
314
+ }
315
+ if (recovered > 0) write(agentId, queue);
316
+ return recovered;
317
+ }
318
+
319
+ // In startPoller():
320
+ function startPoller() {
321
+ const agents = listAgents().filter(a => a.enabled && a.ready);
322
+ for (const a of agents) taskQueue.recoverStaleTasks(a.id);
323
+ // ... start cron jobs
324
+ }
325
+ ```
326
+
327
+ A crash mid-deploy becomes a retried deploy, not a lost task.
328
+
329
+ ---
330
+
331
+ ## Atomic Writes
332
+
333
+ 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`:
334
+
335
+ ```javascript
336
+ function write(agentId, data) {
337
+ const f = filePath(agentId);
338
+ const tmp = f + '.tmp';
339
+ fs.mkdirSync(path.dirname(f), { recursive: true });
340
+ fs.writeFileSync(tmp, JSON.stringify({ ...data, updatedAt: new Date().toISOString() }, null, 2));
341
+ fs.renameSync(tmp, f); // atomic on POSIX
342
+ }
343
+ ```
344
+
345
+ `fs.renameSync` is atomic on POSIX filesystems: readers either see the old file or the new one, never a partial write.
346
 
347
  ---
348
 
 
357
  T+240s Executor tick fires β†’ no pending tasks β†’ skips (noop)
358
  ```
359
 
360
+ Concurrency is controlled by in-memory flags that survive the process lifetime:
361
 
362
  ```javascript
 
 
 
363
  // Only one Scheduler active per agent at a time
364
+ if (agentSessions.isActive(skillId, 'scheduler')) return null;
 
 
 
365
 
366
  // Only one Executor active per agent at a time
367
+ if (agentSessions.isActive(skillId, 'executor')) return null;
 
 
 
368
  ```
369
 
370
+ Crucially: **the Scheduler and Executor can run simultaneously**. While the Executor is working on task #1, the Scheduler can plan tasks #2 and #3.
371
 
372
  ---
373
 
 
384
  '--model', resolvedModel,
385
  ];
386
  if (resumeClaudeId) args.push('--resume', resumeClaudeId);
 
387
  ```
388
 
389
+ 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.
390
 
391
  ---
392
 
 
396
  |---------|-------------|-----------------|
397
  | New email while executing | Missed until session ends | Scheduler handles it immediately |
398
  | Task priority | FIFO only | Explicit priority 1-2-3 |
399
+ | Task dependencies | None | `dependsOn[]` with auto-skip on failure |
400
+ | Partial failure | Whole session fails | Task marked `failed`, next task continues |
401
+ | Crash mid-task | Task lost silently | Reset to `pending` on restart, `retries++` |
402
  | Long-running tasks | Blocks everything | Executor runs async, Scheduler stays free |
403
+ | Debugging | One long session, hard to inspect | `agent-tasks.json` + `log[]` per task |
404
+ | Cost control | Hard to limit mid-session | Monthly spend limit checked before each launch |
405
+ | Re-delivered emails | May process twice | Dedup by `threadId`, idempotent |
406
 
407
  ---
408
 
 
412
 
413
  ```javascript
414
  if (agent.spendingLimitMonthly != null) {
415
+ const spent = await getMonthlySpend(skillId); // async β€” must be awaited
416
  if (spent >= agent.spendingLimitMonthly) {
417
  console.warn(`monthly limit $${agent.spendingLimitMonthly} reached β€” launch blocked`);
418
  return null;
 
420
  }
421
  ```
422
 
423
+ 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
424
 
425
  ---
426
 
427
  ## Complete Flow Diagram
428
 
429
  ```
430
+ Inbox (IMAP/Gmail)
431
  β”‚
432
  β”‚ (polled every 60s)
433
  β–Ό
 
443
  β”‚ (Claude CLI, ROL: PLANIFICADOR)
444
  β”‚ reads email thread via mail_client.py
445
  β”‚ reads agent-tasks.json
446
+ β”‚ deduplicates by threadId
447
+ β”‚ appends tasks with priority + dependsOn
448
+ β”‚ writes agent-tasks.json (atomic)
449
  └─ exits
450
 
451
  (2 min later...)
452
 
453
  tickExecutor()
454
  β”‚
455
+ β”œβ”€ hasPendingReady(agentId)? β†’ no β†’ skip
456
  β”‚
457
  └─ yes
458
  β”‚
 
461
  β”‚
462
  β”‚ (Claude CLI, ROL: EJECUTOR)
463
  β”‚ reads agent-tasks.json
464
+ β”‚ picks highest-priority pending task with deps satisfied
465
+ β”‚ marks in-progress, appends to log[]
466
  β”‚ executes (code, email reply, API call, deploy...)
467
+ β”‚ marks done/failed with result + final log entry
468
+ β”‚ loops until queue empty or no more executable tasks
469
  └─ exits
470
  ```
471
 
472
  ---
473
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  ## Implementation in ClonAgent
475
 
476
  The full implementation is open source:
477
 
478
  | File | Role |
479
  |------|------|
480
+ | [`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 |
481
+ | [`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 |
482
+ | [`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 |
483
  | [`server/lib/agent-sessions.js`](https://github.com/KikoCisBot/clonagent/blob/main/server/lib/agent-sessions.js) | Tracks active Scheduler/Executor sessions, prevents overlaps |
484
 
485
  ---
 
490
 
491
  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.
492
 
493
+ Production use has taught us additional lessons:
494
+
495
+ - **Atomic writes** (temp + rename) prevent file corruption that would break the whole agent
496
+ - **Idempotency by `threadId`** is mandatory β€” email systems re-deliver, networks retry
497
+ - **`log[]` per task** makes debugging possible without any external infrastructure
498
+ - **`dependsOn[]`** enables multi-step workflows without Airflow or Temporal
499
+ - **Crash recovery** at startup means a server restart doesn't lose work in progress
500
+ - **`await` the spend check** β€” async bugs here mean spending limits silently don't apply
501
+
502
+ 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.
503
 
504
+ 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.
505
 
506
  ---
507