-
Notifications
You must be signed in to change notification settings - Fork 441
Expand file tree
/
Copy pathcli.ts
More file actions
executable file
·707 lines (643 loc) · 27.3 KB
/
cli.ts
File metadata and controls
executable file
·707 lines (643 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
#!/usr/bin/env node
// Runtime check: node:sqlite requires Node.js >= 22 (real Node, not Bun's wrapper)
try {
await import("node:sqlite");
} catch {
console.error(
`Error: node:sqlite is not available.\n\n` +
`Antfarm requires Node.js >= 22 with native SQLite support.\n` +
`If you have Bun installed, its \`node\` wrapper does not support node:sqlite via ESM.\n\n` +
`Fix: ensure the real Node.js 22+ is first on your PATH.\n` +
` Check: node -e "require('node:sqlite')"\n` +
` See: https://github.com/snarktank/antfarm/issues/54`
);
process.exit(1);
}
import { installWorkflow } from "../installer/install.js";
import { uninstallAllWorkflows, uninstallWorkflow, checkActiveRuns } from "../installer/uninstall.js";
import { getWorkflowStatus, listRuns, stopWorkflow } from "../installer/status.js";
import { runWorkflow, dryRunWorkflow } from "../installer/run.js";
import { listBundledWorkflows } from "../installer/workflow-fetch.js";
import { readRecentLogs } from "../lib/logger.js";
import { getRecentEvents, getRunEvents, type AntfarmEvent } from "../installer/events.js";
import { startDaemon, stopDaemon, getDaemonStatus, isRunning } from "../server/daemonctl.js";
import { claimStep, completeStep, failStep, getStories, peekStep } from "../installer/step-ops.js";
import { ensureCliSymlink } from "../installer/symlink.js";
import { runMedicCheck, getMedicStatus, getRecentMedicChecks } from "../medic/medic.js";
import { installMedicCron, uninstallMedicCron, isMedicCronInstalled } from "../medic/medic-cron.js";
import { execSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkgPath = join(__dirname, "..", "..", "package.json");
function getVersion(): string {
try {
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
return pkg.version ?? "unknown";
} catch {
return "unknown";
}
}
function formatEventTime(ts: string): string {
const d = new Date(ts);
return d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: true });
}
function formatEventLabel(evt: AntfarmEvent): string {
const labels: Record<string, string> = {
"run.started": "Run started",
"run.completed": "Run completed",
"run.failed": "Run failed",
"step.pending": "Step pending",
"step.running": "Claimed step",
"step.done": "Step completed",
"step.failed": "Step failed",
"step.timeout": "Step timed out",
"story.started": "Story started",
"story.done": "Story done",
"story.verified": "Story verified",
"story.retry": "Story retry",
"story.failed": "Story failed",
"pipeline.advanced": "Pipeline advanced",
};
return labels[evt.event] ?? evt.event;
}
function printEvents(events: AntfarmEvent[]): void {
if (events.length === 0) { console.log("No events yet."); return; }
for (const evt of events) {
const time = formatEventTime(evt.ts);
const agent = evt.agentId ? ` ${evt.agentId.split("_").slice(-1)[0]}` : "";
const label = formatEventLabel(evt);
const story = evt.storyTitle ? ` — ${evt.storyTitle}` : "";
const detail = evt.detail ? ` (${evt.detail})` : "";
const run = evt.runId ? ` [${evt.runId.slice(0, 8)}]` : "";
console.log(`${time}${run}${agent} ${label}${story}${detail}`);
}
}
function printUsage() {
process.stdout.write(
[
"antfarm install Install all bundled workflows",
"antfarm uninstall [--force] Full uninstall (workflows, agents, crons, DB)",
"",
"antfarm workflow list List available workflows",
"antfarm workflow install <name> Install a workflow",
"antfarm workflow uninstall <name> Uninstall a workflow (blocked if runs active)",
"antfarm workflow uninstall --all Uninstall all workflows (--force to override)",
"antfarm workflow run <name> <task> Start a workflow run (--dry-run to validate only)",
"antfarm workflow status <query> Check run status (task substring, run ID prefix)",
"antfarm workflow runs List all workflow runs",
"antfarm workflow resume <run-id> Resume a failed run from where it left off",
"antfarm workflow stop <run-id> Stop/cancel a running workflow",
"antfarm workflow ensure-crons <name> Recreate agent crons for a workflow",
"",
"antfarm dashboard [start] [--port N] Start dashboard daemon (default: 3333)",
"antfarm dashboard stop Stop dashboard daemon",
"antfarm dashboard status Check dashboard status",
"",
"antfarm step peek <agent-id> Lightweight check for pending work (HAS_WORK or NO_WORK)",
"antfarm step claim <agent-id> Claim pending step, output resolved input as JSON",
"antfarm step complete <step-id> Complete step (reads output from stdin)",
"antfarm step fail <step-id> <error> Fail step with retry logic",
"antfarm step stories <run-id> List stories for a run",
"",
"antfarm medic install Install medic watchdog cron",
"antfarm medic uninstall Remove medic cron",
"antfarm medic run [--json] Run medic check now (manual trigger)",
"antfarm medic status Show medic health summary",
"antfarm medic log [<count>] Show recent medic check history",
"",
"antfarm logs [<lines>] Show recent activity (from events)",
"antfarm logs <run-id> Show activity for a specific run",
"",
"antfarm version Show installed version",
"antfarm update Pull latest, rebuild, and reinstall workflows",
].join("\n") + "\n",
);
}
async function main() {
const args = process.argv.slice(2);
const [group, action, target] = args;
if (group === "version" || group === "--version" || group === "-v") {
console.log(`antfarm v${getVersion()}`);
return;
}
if (group === "ant") {
const { printAnt } = await import("./ant.js");
printAnt();
return;
}
if (group === "update") {
const repoRoot = join(__dirname, "..", "..");
console.log("Pulling latest...");
try {
execSync("git pull", { cwd: repoRoot, stdio: "inherit" });
} catch {
process.stderr.write("Failed to git pull. Are you in the antfarm repo?\n");
process.exit(1);
}
console.log("Installing dependencies...");
execSync("npm install", { cwd: repoRoot, stdio: "inherit" });
console.log("Building...");
execSync("npm run build", { cwd: repoRoot, stdio: "inherit" });
// Reinstall workflows
const workflows = await listBundledWorkflows();
if (workflows.length > 0) {
console.log(`Reinstalling ${workflows.length} workflow(s)...`);
for (const workflowId of workflows) {
try {
await installWorkflow({ workflowId });
console.log(` ✓ ${workflowId}`);
} catch (err) {
console.log(` ✗ ${workflowId}: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
ensureCliSymlink();
console.log(`\nUpdated to v${getVersion()}.`);
return;
}
if (group === "uninstall" && (!args[1] || args[1] === "--force")) {
const force = args.includes("--force");
const activeRuns = checkActiveRuns();
if (activeRuns.length > 0 && !force) {
process.stderr.write(`Cannot uninstall: ${activeRuns.length} active run(s):\n`);
for (const run of activeRuns) {
process.stderr.write(` - ${run.id} (${run.workflow_id}): ${run.task}\n`);
}
process.stderr.write(`\nUse --force to uninstall anyway.\n`);
process.exit(1);
}
// Stop dashboard if running
if (isRunning().running) {
stopDaemon();
console.log("Dashboard stopped.");
}
await uninstallAllWorkflows();
console.log("Antfarm fully uninstalled (workflows, agents, crons, database, skill).");
return;
}
if (group === "install" && !args[1]) {
const workflows = await listBundledWorkflows();
if (workflows.length === 0) { console.log("No bundled workflows found."); return; }
console.log(`Installing ${workflows.length} workflow(s)...`);
for (const workflowId of workflows) {
try {
await installWorkflow({ workflowId });
console.log(` ✓ ${workflowId}`);
} catch (err) {
console.log(` ✗ ${workflowId}: ${err instanceof Error ? err.message : String(err)}`);
}
}
ensureCliSymlink();
console.log(`\nDone. Start a workflow with: antfarm workflow run <name> "your task"`);
// Auto-start dashboard if not already running
if (!isRunning().running) {
try {
const result = await startDaemon(3333);
console.log(`\nDashboard started (PID ${result.pid}): http://localhost:${result.port}`);
} catch (err) {
console.log(`\nNote: Could not start dashboard: ${err instanceof Error ? err.message : String(err)}`);
}
} else {
console.log("\nDashboard already running.");
}
return;
}
if (group === "dashboard") {
const sub = args[1];
if (sub === "stop") {
if (stopDaemon()) {
console.log("Dashboard stopped.");
} else {
console.log("Dashboard is not running.");
}
return;
}
if (sub === "status") {
const st = getDaemonStatus();
if (st && st.running) {
console.log(`Dashboard running (PID ${st.pid ?? "unknown"})`);
} else {
console.log("Dashboard is not running.");
}
return;
}
// start (explicit or implicit)
let port = 3333;
const portIdx = args.indexOf("--port");
if (portIdx !== -1 && args[portIdx + 1]) {
port = parseInt(args[portIdx + 1], 10) || 3333;
} else if (sub && sub !== "start" && !sub.startsWith("-")) {
// legacy: antfarm dashboard 4000
const parsed = parseInt(sub, 10);
if (!Number.isNaN(parsed)) port = parsed;
}
if (isRunning().running) {
const status = getDaemonStatus();
console.log(`Dashboard already running (PID ${status?.pid})`);
console.log(` http://localhost:${port}`);
return;
}
const result = await startDaemon(port);
console.log(`Dashboard started (PID ${result.pid})`);
console.log(` http://localhost:${result.port}`);
return;
}
if (group === "medic") {
if (action === "install") {
const result = await installMedicCron();
if (result.ok) {
console.log("Medic watchdog installed (checks every 5 minutes).");
} else {
console.error(`Failed to install medic: ${result.error}`);
process.exit(1);
}
return;
}
if (action === "uninstall") {
const result = await uninstallMedicCron();
if (result.ok) {
console.log("Medic watchdog removed.");
} else {
console.error(`Failed to uninstall medic: ${result.error}`);
process.exit(1);
}
return;
}
if (action === "run") {
const wantsJson = args.includes("--json");
const result = await runMedicCheck();
if (wantsJson) {
console.log(JSON.stringify({
id: result.id,
checkedAt: result.checkedAt,
issuesFound: result.issuesFound,
actionsTaken: result.actionsTaken,
summary: result.summary,
findings: result.findings,
}));
return;
}
if (result.issuesFound === 0) {
console.log(`All clear — no issues found (${result.checkedAt})`);
} else {
console.log(`Medic check complete: ${result.summary}`);
console.log("");
for (const f of result.findings) {
const icon = f.severity === "critical" ? "!!!" : f.severity === "warning" ? " ! " : " ";
const fix = f.remediated ? " [FIXED]" : "";
console.log(` ${icon} ${f.message}${fix}`);
}
}
return;
}
if (action === "status") {
const status = getMedicStatus();
const cronInstalled = await isMedicCronInstalled();
console.log("Antfarm Medic");
console.log(` Cron: ${cronInstalled ? "installed (every 5 min)" : "not installed"}`);
if (status.lastCheck) {
const ago = Math.round((Date.now() - new Date(status.lastCheck.checkedAt).getTime()) / 60000);
console.log(` Last check: ${ago}min ago — ${status.lastCheck.summary}`);
} else {
console.log(" Last check: never");
}
console.log(` Last 24h: ${status.recentChecks} checks, ${status.recentIssues} issues found, ${status.recentActions} auto-fixed`);
return;
}
if (action === "log") {
const limit = target ? parseInt(target, 10) || 20 : 20;
const checks = getRecentMedicChecks(limit);
if (checks.length === 0) {
console.log("No medic checks recorded yet.");
return;
}
for (const check of checks) {
const ts = new Date(check.checkedAt).toLocaleString("en-US", {
month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: true,
});
const icon = check.issuesFound > 0 ? (check.actionsTaken > 0 ? "~" : "X") : ".";
console.log(` ${icon} ${ts} — ${check.summary}`);
}
return;
}
printUsage();
process.exit(1);
}
if (group === "step") {
if (action === "peek") {
if (!target) { process.stderr.write("Missing agent-id.\n"); process.exit(1); }
const result = peekStep(target);
process.stdout.write(result + "\n");
return;
}
if (action === "claim") {
if (!target) { process.stderr.write("Missing agent-id.\n"); process.exit(1); }
const result = claimStep(target);
if (!result.found) {
process.stdout.write("NO_WORK\n");
} else {
process.stdout.write(JSON.stringify({ stepId: result.stepId, runId: result.runId, input: result.resolvedInput }) + "\n");
}
return;
}
if (action === "complete") {
if (!target) { process.stderr.write("Missing step-id.\n"); process.exit(1); }
// Read output from args or stdin
let output = args.slice(3).join(" ").trim();
if (!output) {
// Read from stdin (piped input)
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
output = Buffer.concat(chunks).toString("utf-8").trim();
}
const result = completeStep(target, output);
process.stdout.write(JSON.stringify(result) + "\n");
return;
}
if (action === "fail") {
if (!target) { process.stderr.write("Missing step-id.\n"); process.exit(1); }
const error = args.slice(3).join(" ").trim() || "Unknown error";
const result = await failStep(target, error);
process.stdout.write(JSON.stringify(result) + "\n");
return;
}
if (action === "stories") {
if (!target) { process.stderr.write("Missing run-id.\n"); process.exit(1); }
const stories = getStories(target);
if (stories.length === 0) { console.log("No stories found for this run."); return; }
for (const s of stories) {
const retryInfo = s.retryCount > 0 ? ` (retry ${s.retryCount})` : "";
console.log(`${s.storyId.padEnd(8)} [${s.status.padEnd(7)}] ${s.title}${retryInfo}`);
}
return;
}
process.stderr.write(`Unknown step action: ${action}\n`);
printUsage();
process.exit(1);
}
if (group === "logs") {
const arg = args[1];
if (arg && !/^\d+$/.test(arg)) {
// Looks like a run ID (or prefix)
const events = getRunEvents(arg);
if (events.length === 0) {
console.log(`No events found for run matching "${arg}".`);
} else {
printEvents(events);
}
return;
}
// Also support "antfarm logs #3" to show events for run number 3
if (arg && /^#\d+$/.test(arg)) {
const runNum = parseInt(arg.slice(1), 10);
const db2 = (await import("../db.js")).getDb();
const r = db2.prepare("SELECT id FROM runs WHERE run_number = ?").get(runNum) as { id: string } | undefined;
if (r) {
const events = getRunEvents(r.id);
if (events.length === 0) { console.log(`No events for run #${runNum}.`); }
else { printEvents(events); }
} else {
console.log(`No run found with number #${runNum}.`);
}
return;
}
const limit = parseInt(arg, 10) || 50;
const events = getRecentEvents(limit);
printEvents(events);
return;
}
if (args.length < 2) { printUsage(); process.exit(1); }
if (group !== "workflow") { printUsage(); process.exit(1); }
if (action === "runs") {
const runs = listRuns();
if (runs.length === 0) { console.log("No workflow runs found."); return; }
console.log("Workflow runs:");
for (const r of runs) {
const num = r.run_number != null ? `#${r.run_number}` : r.id.slice(0, 8);
console.log(` [${r.status.padEnd(9)}] ${num.padEnd(6)} ${r.id.slice(0, 8)} ${r.workflow_id.padEnd(14)} ${r.task.slice(0, 50)}${r.task.length > 50 ? "..." : ""}`);
}
return;
}
if (action === "list") {
const workflows = await listBundledWorkflows();
if (workflows.length === 0) { process.stdout.write("No workflows available.\n"); } else {
process.stdout.write("Available workflows:\n");
for (const w of workflows) process.stdout.write(` ${w}\n`);
}
return;
}
if (action === "stop") {
if (!target) { process.stderr.write("Missing run-id.\n"); printUsage(); process.exit(1); }
const result = await stopWorkflow(target);
if (result.status === "not_found") { process.stderr.write(result.message + "\n"); process.exit(1); }
if (result.status === "already_done") { process.stderr.write(result.message + "\n"); process.exit(1); }
console.log(`Cancelled run ${result.runId.slice(0, 8)} (${result.workflowId}). ${result.cancelledSteps} step(s) cancelled.`);
return;
}
if (!target) { printUsage(); process.exit(1); }
if (action === "install") {
const result = await installWorkflow({ workflowId: target });
process.stdout.write(`Installed workflow: ${result.workflowId}\nAgent crons will start when a run begins.\n`);
process.stdout.write(`\nStart with: antfarm workflow run ${result.workflowId} "your task"\n`);
return;
}
if (action === "uninstall") {
const force = args.includes("--force");
const isAll = target === "--all" || target === "all";
const activeRuns = checkActiveRuns(isAll ? undefined : target);
if (activeRuns.length > 0 && !force) {
process.stderr.write(`Cannot uninstall: ${activeRuns.length} active run(s):\n`);
for (const run of activeRuns) {
process.stderr.write(` - ${run.id} (${run.workflow_id}): ${run.task}\n`);
}
process.stderr.write(`\nUse --force to uninstall anyway.\n`);
process.exit(1);
}
if (isAll) { await uninstallAllWorkflows(); } else { await uninstallWorkflow({ workflowId: target }); }
return;
}
if (action === "status") {
const query = args.slice(2).join(" ").trim();
if (!query) { process.stderr.write("Missing search query.\n"); printUsage(); process.exit(1); }
const result = getWorkflowStatus(query);
if (result.status === "not_found") { process.stdout.write(`${result.message}\n`); return; }
const { run, steps } = result;
const runLabel = run.run_number != null ? `#${run.run_number} (${run.id})` : run.id;
const lines = [
`Run: ${runLabel}`,
`Workflow: ${run.workflow_id}`,
`Task: ${run.task.slice(0, 120)}${run.task.length > 120 ? "..." : ""}`,
`Status: ${run.status}`,
`Created: ${run.created_at}`,
`Updated: ${run.updated_at}`,
"",
"Steps:",
...steps.map((s) => ` [${s.status}] ${s.step_id} (${s.agent_id})`),
];
const stories = getStories(run.id);
if (stories.length > 0) {
const done = stories.filter((s) => s.status === "done").length;
const running = stories.filter((s) => s.status === "running").length;
const failed = stories.filter((s) => s.status === "failed").length;
lines.push("", `Stories: ${done}/${stories.length} done${running ? `, ${running} running` : ""}${failed ? `, ${failed} failed` : ""}`);
for (const s of stories) {
lines.push(` ${s.storyId.padEnd(8)} [${s.status.padEnd(7)}] ${s.title}`);
}
}
process.stdout.write(lines.join("\n") + "\n");
return;
}
if (action === "resume") {
if (!target) { process.stderr.write("Missing run-id.\n"); printUsage(); process.exit(1); }
const db = (await import("../db.js")).getDb();
// Find the run (support prefix match)
// Support run number lookup in addition to UUID prefix
let run: { id: string; run_number: number | null; workflow_id: string; status: string } | undefined;
if (/^\d+$/.test(target)) {
run = db.prepare(
"SELECT id, run_number, workflow_id, status FROM runs WHERE run_number = ?"
).get(parseInt(target, 10)) as typeof run;
}
if (!run) {
run = db.prepare(
"SELECT id, run_number, workflow_id, status FROM runs WHERE id = ? OR id LIKE ?"
).get(target, `${target}%`) as typeof run;
}
if (!run) { process.stderr.write(`Run not found: ${target}\n`); process.exit(1); }
if (run.status !== "failed") {
process.stderr.write(`Run ${run.id.slice(0, 8)} is "${run.status}", not "failed". Nothing to resume.\n`);
process.exit(1);
}
// Find the failed step (or first non-done step)
const failedStep = db.prepare(
"SELECT id, step_id, type, current_story_id FROM steps WHERE run_id = ? AND status = 'failed' ORDER BY step_index ASC LIMIT 1"
).get(run.id) as { id: string; step_id: string; type: string; current_story_id: string | null } | undefined;
if (!failedStep) {
process.stderr.write(`No failed step found in run ${run.id.slice(0, 8)}.\n`);
process.exit(1);
}
// If it's a loop step with a failed story, reset that story to pending
if (failedStep.type === "loop") {
const failedStory = db.prepare(
"SELECT id FROM stories WHERE run_id = ? AND status = 'failed' ORDER BY story_index ASC LIMIT 1"
).get(run.id) as { id: string } | undefined;
if (failedStory) {
db.prepare(
"UPDATE stories SET status = 'pending', updated_at = datetime('now') WHERE id = ?"
).run(failedStory.id);
}
db.prepare(
"UPDATE steps SET retry_count = 0 WHERE run_id = ? AND type = 'loop'"
).run(run.id);
}
// Check if the failed step is a verify step linked to a loop step's verify_each
const loopStep = db.prepare(
"SELECT id, loop_config FROM steps WHERE run_id = ? AND type = 'loop' AND status IN ('running', 'failed') LIMIT 1"
).get(run.id) as { id: string; loop_config: string | null } | undefined;
if (loopStep?.loop_config) {
const lc = JSON.parse(loopStep.loop_config);
if (lc.verifyEach && lc.verifyStep === failedStep.step_id) {
// Reset the loop step (developer) to pending so it re-claims the story and populates context
db.prepare(
"UPDATE steps SET status = 'pending', current_story_id = NULL, retry_count = 0, updated_at = datetime('now') WHERE id = ?"
).run(loopStep.id);
// Reset verify step to waiting (fires after developer completes)
db.prepare(
"UPDATE steps SET status = 'waiting', current_story_id = NULL, retry_count = 0, updated_at = datetime('now') WHERE id = ?"
).run(failedStep.id);
// Reset any failed stories to pending
db.prepare(
"UPDATE stories SET status = 'pending', updated_at = datetime('now') WHERE run_id = ? AND status = 'failed'"
).run(run.id);
// Reset run to running
db.prepare(
"UPDATE runs SET status = 'running', updated_at = datetime('now') WHERE id = ?"
).run(run.id);
// Ensure crons are running for this workflow
const { loadWorkflowSpec } = await import("../installer/workflow-spec.js");
const { resolveWorkflowDir } = await import("../installer/paths.js");
const { ensureWorkflowCrons } = await import("../installer/agent-cron.js");
try {
const workflowDir = resolveWorkflowDir(run.workflow_id);
const workflow = await loadWorkflowSpec(workflowDir);
await ensureWorkflowCrons(workflow);
} catch (err) {
process.stderr.write(`Warning: Could not start crons: ${err instanceof Error ? err.message : String(err)}\n`);
}
console.log(`Resumed run ${run.id.slice(0, 8)} — reset loop step "${loopStep.id.slice(0, 8)}" to pending, verify step "${failedStep.step_id}" to waiting`);
process.exit(0);
}
}
// Reset step to pending
db.prepare(
"UPDATE steps SET status = 'pending', current_story_id = NULL, retry_count = 0, updated_at = datetime('now') WHERE id = ?"
).run(failedStep.id);
// Reset run to running
db.prepare(
"UPDATE runs SET status = 'running', updated_at = datetime('now') WHERE id = ?"
).run(run.id);
// Ensure crons are running for this workflow
const { loadWorkflowSpec } = await import("../installer/workflow-spec.js");
const { resolveWorkflowDir } = await import("../installer/paths.js");
const { ensureWorkflowCrons } = await import("../installer/agent-cron.js");
try {
const workflowDir = resolveWorkflowDir(run.workflow_id);
const workflow = await loadWorkflowSpec(workflowDir);
await ensureWorkflowCrons(workflow);
} catch (err) {
process.stderr.write(`Warning: Could not start crons: ${err instanceof Error ? err.message : String(err)}\n`);
}
console.log(`Resumed run ${run.id.slice(0, 8)} from step "${failedStep.step_id}"`);
return;
}
if (action === "ensure-crons") {
const { loadWorkflowSpec } = await import("../installer/workflow-spec.js");
const { resolveWorkflowDir } = await import("../installer/paths.js");
const { setupAgentCrons, removeAgentCrons } = await import("../installer/agent-cron.js");
const workflowDir = resolveWorkflowDir(target);
const workflow = await loadWorkflowSpec(workflowDir);
// Force recreate: remove existing then create fresh
await removeAgentCrons(target);
await setupAgentCrons(workflow);
console.log(`Recreated agent crons for workflow "${target}".`);
return;
}
if (action === "run") {
let notifyUrl: string | undefined;
let dryRun = false;
const runArgs = args.slice(3);
const nuIdx = runArgs.indexOf("--notify-url");
if (nuIdx !== -1) {
notifyUrl = runArgs[nuIdx + 1];
runArgs.splice(nuIdx, 2);
}
const drIdx = runArgs.indexOf("--dry-run");
if (drIdx !== -1) {
dryRun = true;
runArgs.splice(drIdx, 1);
}
const taskTitle = runArgs.join(" ").trim();
if (dryRun) {
await dryRunWorkflow({ workflowId: target, taskTitle });
return;
}
if (!taskTitle) { process.stderr.write("Missing task title.\n"); printUsage(); process.exit(1); }
const run = await runWorkflow({ workflowId: target, taskTitle, notifyUrl });
process.stdout.write(
[`Run: #${run.runNumber} (${run.id})`, `Workflow: ${run.workflowId}`, `Task: ${run.task}`, `Status: ${run.status}`].join("\n") + "\n",
);
return;
}
process.stderr.write(`Unknown action: ${action}\n`);
printUsage();
process.exit(1);
}
main().catch((err) => {
process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
process.exit(1);
});